以前这个问题困扰我多天最后查资料一大堆,最后最终攻克了,看到非常多人做C#串口都遇到相同的问题,所以写一篇博文,以便学习交流。
一定要在com实例化的时候设置ReceivedBytesThreshold 属性就能够
SerialPort com = new SerialPort();这个问题问了好多人都说的不正确。最后突然在网上一片博文中发现的准备发一篇博文呢。还没有写呢。今天正好写一个
接收方法
/// <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);
}
}
C# 中串口通信 serialport1.DataReceived 函数无法触发或者出发延时等等问题解决方法
原文:http://www.cnblogs.com/jzssuanfa/p/6822399.html