分为两步:
1.串口接收支持中文显示
1.1.在软件初始化时写入此代码以支持汉字显示
//串口接收支持中文显示serialPort1.Encoding = Encoding.GetEncoding("GB2312"); //串口1的解码支持GB2312汉字
2.串口发送支持中文输出
//支持中文输出Encoding Chinese = System.Text.Encoding.GetEncoding("GB2312");//定义一个可以进行中文编码的变量byte[] Sendbytes = Chinese.GetBytes(textBox5.Text);//将发送框的内容编译为中文
3.完整代码
//串口发送按钮private void button29_Click(object sender, EventArgs e){byte[] data = new byte[1];//发送函数需要定义数组首地址//发送格式为ASCIIif (!checkBox24.Checked)//复用框没有被选择时{try{//支持中文输出Encoding Chinese = System.Text.Encoding.GetEncoding("GB2312");//定义一个可以进行中文编码的变量byte[] Sendbytes = Chinese.GetBytes(textBox5.Text);//将发送框的内容编译为中文//遍历发送用法foreach (byte Member in Sendbytes)//循环函数{data[0] = Member;serialPort1.Write(data, 0, 1);//单字节发送}//发送回车换行if (checkBox26.Checked)//发空复选框{data[0] = 0x0D;//发送回车serialPort1.Write(data, 0, 1);data[0] = 0x0A;//发送换行serialPort1.Write(data, 0, 1);}}catch{textBox1.AppendText("\r\n串口数据发送错误!\r\n");//textBox5.Text = "";//若出现错误不清空发送框的内容//串口按钮显示为关闭serialPort1.Close();button2.BackgroundImage = Properties.Resources.Image_CloseSerial;button2.Tag = "OFF";}}//发送格式为HEXelse{//处理字符串string Buf = textBox5.Text;Buf = Buf.Replace("0x", string.Empty);//将buf中的0x替换为空格,消除0x的不规范书写方式Buf = Buf.Replace("0X", string.Empty);Buf = Buf.Replace(" ", string.Empty);byte[] Calculate_CRC = new byte[(Buf.Length - Buf.Length % 2) / 2];//CRC缓存区textBox5.Text = " ";//循环发送for (int i = 0; i < (Buf.Length - Buf.Length % 2) / 2; i++)//取余运算作用是防止用户输入的字符为奇数个{textBox5.AppendText(Buf.Substring(i * 2, 2) + " ");//Buf.Substring为Buf的子字符串,长度为2try{data[0] = Convert.ToByte(Buf.Substring(i*2,2),16);//将字符串转换为十六进制的整型serialPort1.Write(data, 0, 1);//单字节发送Calculate_CRC[i] = data[0];//CRC参数赋值}catch{textBox1.AppendText("\r\n串口数据发送错误!\r\n");//textBox5.Text = "";//若出现错误不清空发送框的内容//串口按钮显示为关闭serialPort1.Close();button2.BackgroundImage = Properties.Resources.Image_CloseSerial;button2.Tag = "OFF";}}//发送CRCif (checkBox25.Checked){UInt32 CRC = Crc_Check(Calculate_CRC, (byte)Calculate_CRC.Length);//crc计算byte CRC_H = (byte)(CRC >> 8);byte CRC_L = (byte)CRC;try{data[0] = CRC_L;serialPort1.Write(data, 0, 1);//发送低位data[0] = CRC_H;serialPort1.Write(data, 0, 1);//发送高位}catch{textBox1.AppendText("\r\n串口数据发送错误!\r\n");//textBox5.Text = "";//若出现错误不清空发送框的内容//串口按钮显示为关闭serialPort1.Close();button2.BackgroundImage = Properties.Resources.Image_CloseSerial;button2.Tag = "OFF";}}}//发送完清空if (checkBox23.Checked)//发空复选框{textBox5.Text = "";}}
4.测试结果
将自定义串口助手与SSCOM进行通讯,测试中文的发送接收,显示发送接收成功表示中文支持功能添加成功