c# 串口数据获取、发送,解决乱码

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;

namespace CYSY.Simulation
{
    public partial class Serial : Form
    {
        public Serial()
        {
            InitializeComponent();
            settextevent += set;
        }

        private SerialPort device = new SerialPort();
        StringBuilder builder = new StringBuilder();
        private void button1_Click(object sender, EventArgs e)
        {
            if (device.IsOpen)
            {
                if (!string.IsNullOrEmpty(this.textBox1.Text))
                {
                    //device.WriteLine(this.textBox1.Text + "\r\n");//发送的数据有乱码问题
                    string cmd = this.textBox1.Text;
                    byte[] SendBytes = null;
                    Encoding chs = Encoding.GetEncoding("utf-8");
                    byte[] bytes = chs.GetBytes(cmd);
                    string str = "";
                    for (int i = 0; i < bytes.Length; i++)
                    {
                        str += string.Format("{0:X2}", bytes[i]);
                    }
                    List<string> SendDataList = new List<string>();
                    for (int i = 0; i < str.Length; i = i + 2)
                    {
                        SendDataList.Add(str.Substring(i, 2));
                    }
                    SendDataList.Add("0D");
                    SendBytes = new byte[SendDataList.Count];
                    for (int j = 0; j < SendBytes.Length; j++)
                    {
                        SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16));
                    }
                    device.Write(SendBytes, 0, SendBytes.Length);//发送数据
                }
                else
                {
                    MessageBox.Show("数据为空");
                }
            }
            else
            {
                MessageBox.Show("COM1未打开!");
            }


        }

        public delegate void settext(string text);
        public event settext settextevent;
        public void set(string text)
        {
            this.textBox2.Text = text;
        }

        //在接收到了ReceivedBytesThreshold设置的字符个数或接收到了文件结束字符并将其放入了输入缓冲区时被触发
        public void device_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Console.WriteLine("接收中...");
            int n = device.BytesToRead;
            byte[] buf = new byte[n];    //声明临时数组存储串口数据
            device.Read(buf, 0, n);      //读取缓冲数据
            builder.Remove(0, builder.Length); //清除字符串构造器的内容
            builder.Append(Encoding.Default.GetString(buf));
            string comdata = builder.ToString();
            Console.WriteLine("data:" + comdata);
            if(!string.IsNullOrEmpty(comdata)) this.Invoke(settextevent, comdata);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!device.IsOpen)
            {
                try
                {
                    //串口号
                    device.PortName = "COM1";
                    //波特率
                    device.BaudRate = 115200;
                    //数据位
                    device.DataBits = 8;
                    //停止位
                    device.StopBits = StopBits.One;
                    //奇偶校验位
                    device.Parity = Parity.Even;
                    //DataReceived事件发送前,内部缓冲区里的字符数
                    device.ReceivedBytesThreshold = 1;
                    device.RtsEnable = true; device.DtrEnable = true; device.ReadTimeout = 3000;
                    // Control.CheckForIllegalCrossThreadCalls = false;
                    //表示将处理 System.IO.Ports.SerialPort 对象的数据接收事件的方法。
                    device.DataReceived += new SerialDataReceivedEventHandler(device_DataReceived);
                    //打开
                    device.Open();
                    MessageBox.Show("COM1打开成功!");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("COM1打开失败!");
                }
            }
            else
            {
                MessageBox.Show("COM1打开成功!");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (device.IsOpen)
            {
                device.Close();
                MessageBox.Show("COM1关闭成功!");
            }
        }
    }
}


使用 AccessPort 测试数据发送和接口,如遇乱码问题,设置电脑:控制面板——设备管理——端口——通信端口,右键——属性——端口设置,里面的波特率等信息需要设置为一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值