C# 串口传送汉字

serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
发送文本模式时直接serialPort1.Write(tbInput.Text);
发送16进制时,转换成字节数组后再发送
serialPort1.Write(data, 0, data.Length);
接收信息时使用DataReceived事件触发,
在serialPort1_DataReceived事件中,等待数据传完毕后,再一起接收并转换成文本或者16进制数据。
       private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
       {
int index = serialPort1.BytesToRead;
               do
               {
                   NumOfBytesToRead = index;
                   Thread.Sleep(50);
                   index = serialPort1.BytesToRead;
               }
               while ((NumOfBytesToRead != index) && (index != 0));
               this.Invoke(new EventHandler(btnRec_Click));
           }

       private void btnRec_Click(object sender, EventArgs e)
       {
           try
           {
               if (RecDataMode == "Text")
               {
                   tbRec.Text = tbRec.Text + serialPort1.ReadExisting();
               }
               else
               {
                   int bytes = serialPort1.BytesToRead;

                   // 创建字节数组
                   byte[] buffer = new byte[bytes];
                   serialPort1.Read(buffer, 0, bytes);
                   tbRec.Text = tbRec.Text + ByteArrayToHexString(buffer);
               }
               NumOfBytesToRead = 0;

           }
           catch
           {
           }
       }

 

你可能感兴趣的