这里关注两个问题:
1、DataReceived 不能触发问题
2、接收大于8的数据分段发回的问题
- public static bool OpenDeviceCOM(string portName)
- {
- try
- {
- DeviceCOM = new SerialPort();
- DeviceCOM.PortName = portName;
- DeviceCOM.BaudRate = 19200;
- DeviceCOM.Parity = System.IO.Ports.Parity.None;
- DeviceCOM.DataBits = 8;
- DeviceCOM.StopBits = StopBits.One;
- DeviceCOM.ReadTimeout = 1000;
- DeviceCOM.RtsEnable = true;
- DeviceCOM.ReceivedBytesThreshold = 1;
- DeviceCOM.DataReceived += new SerialDataReceivedEventHandler(DeviceCOM_DataReceived);
- DeviceCOM.Open();
- if (DeviceCOM.IsOpen)
- IsDeviceCOMOpen = true;
- return true;
- }
- catch (Exception xcptn)
- {
- CLogManager.SendException(new System.Diagnostics.StackTrace(new System.Diagnostics.StackFrame(true)), xcptn);
- return false;
- }
- }
将DeviceCOM.ReceivedBytesThreshold = 1;是解决事件不触发的办法之一。
- private static void DeviceCOM_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- byte[] rcvBytes = null;
- rcvBytes = CSerialPortIO.ReadDeviceCOMBytes();
- ThreadPool.QueueUserWorkItem(new WaitCallback((object obj) =>
- {
- if (rcvBytes != null)
- {
- // handle the ecvBytes here……
- }
- }));
- }
有时候发现,串口接收的回来的数据是以8个字节为一次发回来的,当远程发过来的数据长度大于8,如达到11字节时,会分8字节和3字节回来。这种情况要特殊处理。
- public static Byte[] ReadDeviceCOMBytes()
- {
- try
- {
- List byteList = new List();
- byte[] rcvBytes = null;
- do
- {
- int count = DeviceCOM.BytesToRead;
- Console.WriteLine("in ReadDeviceCOMBytes : count={0}", count);
-
- rcvBytes = new byte[count];
- DeviceCOM.Read(rcvBytes, 0, count);
- foreach (byte by in rcvBytes)
- {
- byteList.Add(by);
- if (byteList.Count == 11)
- break;
- }
- } while (byteList.Count 11);
-
- return byteList.ToArray();
- }
- catch
- {
- return null;
- }
- }
参考文献: