- 设置接收超时毫秒数ReadTimeout
- 线程接收,每次读一个字节,添加到列表中
- 接收超时时,捕获异常,生成一帧数据
啥也不说了,看代码
private void Form1_Load(object sender, EventArgs e)
{
var sList = SerialPort.GetPortNames();
this.serialPort1.PortName = sList.Last();
this.serialPort1.BaudRate = 9600;
this.serialPort1.ReadTimeout = 10;
this.serialPort1.Open();
thread = new Thread(new ThreadStart(ThreadReceive));
thread.Start();
timer1.Start();
}
Queue<List<byte>> queueList = new Queue<List<byte>>();
Thread thread = null;
List<byte> receiveList = new List<byte>();
void ThreadReceive()
{
while (true)
{
try
{
int data = this.serialPort1.ReadByte();
if (data >= 0)
receiveList.Add((byte)data);
}
catch
{
if (receiveList.Count > 0)
{
queueList.Enqueue(receiveList);
receiveList = new List<byte>();
}
}
}
}
本文介绍了一种通过串口接收数据并进行处理的方法。利用C#编程实现了一个应用程序,该程序可以设置串口参数,并在接收数据时采用超时机制来捕获完整的数据帧。当读取操作超过预设的超时时间后,会生成一帧数据并将其存入队列以备后续处理。
532

被折叠的 条评论
为什么被折叠?



