|
楼主 |
发表于 2020-1-8 13:57:38
|
显示全部楼层
本帖最后由 BS_good200xy 于 2020-1-8 14:05 编辑
按下面这样可以吗?
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//Thread.Sleep(500);//这个延时非常重要
int n = sp.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
sp.Read(buf, 0, n);//读取缓冲数据
for(int i=0; i < n; i++) FrameBuff[LastLocal + i] += buf[ i ] ; //当前数据存入帧缓存
if((FrameBuff[0]==0xaa)&&(FrameBuff[LastLocal + n -1]==0xa5)) //收到完整的一帧数据则立即处理并清零
{
.......//一帧数据处理程序
for(int i=0; i < LastLocal + n; i++) //帧缓存清零。
{
FrameBuff[ i ] = 0 ;
}
LastLocal = 0 ;
}
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
for(int i;i<n;i++)
{
textBox1.text += buf.ToString();
}
}));
} |
|