コード例 #1
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="serialPort">串口</param>
        /// <param name="txData">要发送的数据</param>
        /// <param name="isWriteData">是否是写数据</param>
        public static void SendData(SerialPort serialPort, byte[] txData, bool isWriteData = true)
        {
            if (serialPort == null)
            {
                return;
            }

            List <byte> sendData = new List <byte>();

            sendData.AddRange(txData);
            sendData.Add(HelperTool.GetChecksum(crc8, txData));

            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }

            if (!serialPort.IsOpen)
            {
                serialPort.Open();
            }

            receDataLength = -1;
            recData?.Clear();

            serialPort.DiscardOutBuffer();
            if (isWriteData == false)
            {
                isReadAll = true;
                serialPort.DiscardInBuffer();
            }
            else
            {
                isReadAll = false;
            }

            serialPort.Write(sendData.ToArray(), 0, sendData.Count());

            Console.WriteLine("发送数据!");
        }
コード例 #2
0
        private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)sender;
            // 接收到数据之前,需要设置接收的数据长度
            int bytesToRead = serialPort.BytesToRead;

            byte[] ReDatas = new byte[bytesToRead];
            serialPort.Read(ReDatas, 0, bytesToRead);
            if (bytesToRead == 0)
            {
                return;
            }

            if (isReadAll == false)
            {
                return;
            }

            receDataLength += bytesToRead;
            Console.WriteLine("接收数据长度:" + receDataLength);
            if (recData == null)
            {
                recData = new List <byte>();
            }

            recData.AddRange(ReDatas);
            if ((receDataLength + 1) == (headLength + dataAllToRead + checkCodeLength) && HelperTool.GetChecksum(crc8, recData.ToArray()) == 0)
            {
                // 解析数据
                ParseReData(recData.ToArray());

                receDataLength = -1;
                recData.Clear();
            }
        }