以前这个问题困扰我多天最后查资料一大堆,最后最终攻克了,看到非常多人做C#串口都遇到相同的问题,所以写一篇博文,以便学习交流。
一定要在com实例化的时候设置ReceivedBytesThreshold 属性就能够
SerialPort com = new SerialPort();com.BaudRate = 19200;
com.PortName = "COM1";
com.DataBits = 8;
com.Parity = (Parity)0;
com.StopBits = 1;
com.WriteTimeout = 3000;
com.ReadTimeout = 3000;
com.ReceivedBytesThreshold = 1; //必须一定要加上这句话。意思是接收缓冲区其中假设有一个字节的话就出发接收函数。假设不加上这句话,那就有时候触发接收有时候都发了好多次了也没有触发接收,有时候延时现象等等,
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived);
这个问题问了好多人都说的不正确。最后突然在网上一片博文中发现的准备发一篇博文呢。还没有写呢。今天正好写一个
接收方法
/// <summary>
/// 接受返回消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
//接收数据
do
{
int count = com.BytesToRead;
if (count <= 0)
break;
g_RS232DataBuff = new byte[count];
com.Read(g_RS232DataBuff, 0, count);
g_i_DataBuffLen += count;
g_l_ReceivedCount += count;
//g_Data += Encoding.ASCII.GetString(g_RS232DataBuff);
foreach (byte b in g_RS232DataBuff)
{
g_s_Data += Convert.ToChar(b);
//g_Data += Encoding.Unicode.GetString(g_RS232DataBuff);
//queue.Enqueue(g_RS232DataBuff);
}
} while (com.BytesToRead > 0);
//处理接收后的命令
TranslateCommand2();
}
catch (Exception ex)
{
LogClass.WriteFile("error:接收返回消息异常。详细原因:" + ex.Message);
}
}