Chinaunix首页 | 论坛 | 博客
  • 博客访问: 12371117
  • 博文数量: 1293
  • 博客积分: 13501
  • 博客等级: 上将
  • 技术积分: 17974
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 18:11
文章分类

全部博文(1293)

文章存档

2019年(1)

2018年(1)

2016年(118)

2015年(257)

2014年(128)

2013年(222)

2012年(229)

2011年(337)

分类: C#/.net

2015-11-26 21:10:22

这里关注两个问题:

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

阅读(3673) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~