C#读取串口数据不完整是怎么回事?

w254873233 2010-06-11 10:30:49
发过去了 读的时候只读了一些,还有些没有读出来!
用的是SerialPort控件,没有用DataReceived事件
另外开的线程读的,请问怎么解决呢???
...全文
510 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
捷哥1999 2010-06-11
  • 打赏
  • 举报
回复
1、设置大一点的缓冲区,如果一次读取不完,自然要分多次读取!
2、关于SerialPort写串口程序的问题
w254873233 2010-06-11
  • 打赏
  • 举报
回复
多次serialPort1.Read(data, 0, data.Length);什么意思,怎么做!!!上面给的代码看不懂!
rroo 2010-06-11
  • 打赏
  • 举报
回复
比如一个扫码枪读到条码之后,你需要通过多次serialPort1.Read(data, 0, data.Length);才能读到完整的数据,要不然就会出现断码的现象,特别是那种USB转COM的设备,这种情况特别容易出现
rroo 2010-06-11
  • 打赏
  • 举报
回复
你要用一个全局变量来保存每次读到的数据,直到读取完整了,也就是说,erialPort1.Read(data, 0, data.Length);有时候并不能一次性把数据读取完整,之前我也遇到过这样的问题,给你一段代码参考一下
#region serialPort1_DataReceived - 接受COM数据
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
lock (locker)
{
switch (e.EventType)
{
case SerialData.Chars:
byte[] data = new byte[256];
int length = serialPort1.Read(data, 0, data.Length);

if (length > 0)
{
if (data[length - 1] == 13)
{
if (length > 1)
{
buffer += Encoding.ASCII.GetString(data, 0, length - 1);
}
string temp = buffer;
buffer = "";
//DealBarcode(temp);
this.Invoke(new DealBarcodeEvent(this.DealBarcode), new object[] { temp });
}
else if (data[length - 1] == 10)
{
if (length == 1)
{
return;
}
else if (length == 2)
{
string temp = buffer;
buffer = "";
//DealBarcode(temp);
this.Invoke(new DealBarcodeEvent(this.DealBarcode), new object[] { temp });
}
else // length > 2 含有数据
{
buffer += Encoding.ASCII.GetString(data, 0, length - 2);
string temp = buffer;
buffer = "";
//DealBarcode(temp);
this.Invoke(new DealBarcodeEvent(this.DealBarcode), new object[] { temp });
}
}
else
{
buffer += Encoding.ASCII.GetString(data, 0, length);
}
}
break;
case SerialData.Eof:
break;
}
}
}
#endregion

其中的temp就是前面说的全局变量
而this.Invoke(new DealBarcodeEvent(this.DealBarcode), new object[] { temp });就是在判定所有数据读完了之后,做的一段业务逻辑,自己去改改吧
garfieldzf 2010-06-11
  • 打赏
  • 举报
回复

DataReceived
w254873233 2010-06-11
  • 打赏
  • 举报
回复
不会,先帮下解决下问题先!
casinosun 2010-06-11
  • 打赏
  • 举报
回复
用VC不行吗?
rroo 2010-06-11
  • 打赏
  • 举报
回复
上面的代码用的是事件,你先试试看

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧