serialPort 接收事件不触发及接收长数据

这里关注两个问题:

1、DataReceived 不能触发问题

2、接收大于8的数据分段发回的问题


  1. public static bool OpenDeviceCOM(string portName)
  2. {
  3.     try
  4.     {
  5.         DeviceCOM = new SerialPort();
  6.         DeviceCOM.PortName = portName;
  7.         DeviceCOM.BaudRate = 19200;
  8.         DeviceCOM.Parity = System.IO.Ports.Parity.None;
  9.         DeviceCOM.DataBits = 8;
  10.         DeviceCOM.StopBits = StopBits.One;
  11.         DeviceCOM.ReadTimeout = 1000;
  12.         DeviceCOM.RtsEnable = true;
  13.         DeviceCOM.ReceivedBytesThreshold = 1;
  14.         DeviceCOM.DataReceived += new SerialDataReceivedEventHandler(DeviceCOM_DataReceived);
  15.         DeviceCOM.Open();
  16.         if (DeviceCOM.IsOpen)
  17.             IsDeviceCOMOpen = true;
  18.         return true;
  19.     }
  20.     catch (Exception xcptn)
  21.     {
  22.         CLogManager.SendException(new System.Diagnostics.StackTrace(new System.Diagnostics.StackFrame(true)), xcptn);
  23.         return false;
  24.     }
  25. }



将DeviceCOM.ReceivedBytesThreshold = 1;是解决事件不触发的办法之一。


  1. private static void DeviceCOM_DataReceived(object sender, SerialDataReceivedEventArgs e)
  2. {
  3.     byte[] rcvBytes = null;
  4.     rcvBytes = CSerialPortIO.ReadDeviceCOMBytes();
  5.     ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) =>
  6.     {
  7.         if (rcvBytes != null)
  8.         {
  9. // handle the ecvBytes here……
  10.         }
  11.    }));
  12. }


有时候发现,串口接收的回来的数据是以8个字节为一次发回来的,当远程发过来的数据长度大于8,如达到11字节时,会分8字节和3字节回来。这种情况要特殊处理。


  1. public static Byte[] ReadDeviceCOMBytes()
  2. {
  3.     try
  4.     {
  5.         List byteList = new List();
  6.         byte[] rcvBytes = null;
  7.         do
  8.         {
  9.             int count = DeviceCOM.BytesToRead;
  10.             Console.WriteLine("in ReadDeviceCOMBytes : count={0}", count);

  11.             rcvBytes = new byte[count];
  12.             DeviceCOM.Read(rcvBytes, 0, count);
  13.             foreach (byte by in rcvBytes)
  14.             {
  15.                 byteList.Add(by);
  16.                 if (byteList.Count == 11)
  17.                     break;
  18.             }
  19.         } while (byteList.Count 11);

  20.         return byteList.ToArray();
  21.     }
  22.     catch
  23.     {
  24.         return null;
  25.     }
  26. }


参考文献:

http://blog.csdn.net/chenhongwu666/article/details/40142513

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值