CH340:ReadTimeout需设置到80ms,才稳定
FT232:ReadTimeout设置在3ms,很稳定
结论:使用该方法,FT232的设备较好。
using System.Threading;
//中断接收线程
Thread threadIntRx = null;
//串口接收缓存大小
private const int rxBufNum = 20000;
private int RxCnt = 0; //接收字节计数, 作用相当于全局变量
private byte[] RxBuf = new byte[rxBufNum];
private const ushort RX_FRAME_MAX = 2000;
public Form1()
{
//串口接收中断
serialPort1.ReadTimeout = 30;
threadIntRx = new Thread(new ThreadStart(ThreadReceive));
threadIntRx.Start();
}
//串口空闲中断接收
void ThreadReceive()
{
while (true)
{
if (serialPort1.IsOpen)
{
try
{
int cnt = serialPort1.BytesToRead; //获取接收缓冲区中的字节数
if (cnt > 0) //缓存中有数据,先一次行读完
{
double length = cnt + RxCnt;
if (length <= RX_FRAME_MAX)
{
serialPort1.Read(RxBuf, RxCnt, cnt);
RxCnt += cnt;
}
else
{
serialPort1.DiscardInBuffer(); //清空接收缓存
RxCnt = 0;
}
}
byte data = (byte)serialPort1.ReadByte();
RxBuf[RxCnt++] = data;
}
catch //30ms超时
{
if(RxCnt >= 12)
{
Invoke((EventHandler)(delegate
{
CmdParse(RxBuf, RxCnt);
}));
}
RxCnt = 0;
}
}
else
{
System.Threading.Thread.Sleep(200);
}
}
}