SerialDataReceivedEventHandler is not firing
本文关键字:firing not is SerialDataReceivedEventHandler | 更新日期: 2023-09-27 18:16:04
我正在尝试使用c#编写从串行端口接收的代码。
我使用VSPC实用程序从两个端口COM27和COM28生成桥当我写COM27发送数据到COM28,我可以看到它使用Putty连接,但是当我试图使用以下代码制作程序时,它不起作用,SerialDataReceivedEventHandler没有触发。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
namespace csh_serial2_pic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//
private void button1_Click(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
//
string t;
private void button2_Click(object sender, EventArgs e)
{
t = comboBox1.Text.ToString();
sErial(t);
}
// Method
SerialPort sp;
void sErial(string Port_name)
{
//ThreadPool.SetMinThreads(2, 4);
sp = new SerialPort(Port_name, 9600, Parity.None, 8, StopBits.One);
sp.ReadTimeout = 1000;
sp.WriteTimeout = 1000;
sp.ReadBufferSize = 4096;
sp.ReceivedBytesThreshold = 1;
//
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandeler);
sp.Open();
sp.DtrEnable = true;
sp.RtsEnable = true;
//System.Threading.Thread.Sleep(10);
//sp.Close();
}
//
private void DataReceivedHandeler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender ;
Debug.Print("receiving!");
string data = sp.ReadExisting();
Console.WriteLine("received: " + data);
Debug.Print(data);
string w = sp.ReadLine();
if (w != string.Empty)
{
Invoke(new Action (() => richTextBox1.AppendText(w)));
}
}
}
}
所以谁都可以帮我解决这个问题
尝试使用没有设置缓冲区大小,超时,rts/dts启用的端口。如果您在没有完全理解为什么这样做的情况下乱用默认值,您可能会搬起石头砸自己的脚。例如,如果读取仅在1秒(1000毫秒)后超时,则在超时之前可能没有接收到任何数据。
发送的数据是文本吗?否则,您可能会接收到不能转换为字符串的数据,因此不会生成任何输出。
同时,您正在读取用于调试的数据,然后试图读取另一行数据以显示。第一次读取后,缓冲区将为空