ReceiveByteThreshold设为1了,但是进入消息处理函数,查看BytesToRead属性,每次都是0xf。
这怎么回事,不能一个字节触发一次吗?
private void bz_comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (closing) return; //如果正在关闭,忽略操作,直接返回,尽快的完成串口监听线程的一次循环
try
{
listening = true; //设置标记,已经开始处理数据,要使用系统UI
Thread.Sleep(60);//用于接收完整信息
if (bz_comm.IsOpen == false) return;
int n = bz_comm.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致
byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据
bz_comm.Read(buf, 0, n);//读取缓冲数据
bz_builder.Clear();//清除字符串构造器的内容
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
foreach (byte b in buf)
{
bz_builder.Append(b.ToString("x2") + " ");
}
bz_info(bz_builder.ToString());
}));
}
finally
{
listening = false; //线程完成 UI可以关闭串口
}
}
serialport.ReceivedBytesThreshold
SerialPort.ReceivedBytesThreshold属性决定了当串口读缓存中数据多少个时才触发DataReceived事件,默认为1
根据你接收的数据格式可以使用不同的Read方法。ReadTo()方法是直到读到相应的字符为止,ReadLine()方法是读到一个新行,Read()读取缓冲区的字节数。
另起一个接受线程,线程里定义一个定时器,定时器里执行接受函数扫面,有接受到有效字符就处理
可以每次读取一个字节readByte
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//byte[] rxbyte = new byte[1];
byte[] rxbyte = new byte[8];
byte currentbyte;
port.Read(rxbyte, 0, port.BytesToRead);
currentbyte = rxbyte[0];
int channel = (currentbyte >> 6) & 3; //3 = binary 11, ANDS the last 2 bits
int msb_2bit = (currentbyte >> 0) & 255; //AND compare all bits in a byte
currentbyte = rxbyte[1];
int val = ((msb_2bit << 8) | (currentbyte << 0));
//Extra stuff
SetText_tmp1(val.ToString());
}
应该是串口传来的数据太多了,我的测试是前几次数据会多出设定的触发数,串口读几次后就是按设定的触发数来触 发了