c#处理基于Modbus协议的串口通讯程序

下位机是Modbus协议,上位机是用c#写的串口通讯程序。

VS工具箱有自带的串口通讯控件;或者直接用代码SerialPort serialPort = new SerialPort();生成串口通讯的对象,但是记得要绑定收到数据的响应事件。(本文用的是第二个方式)

代码如下:

1. 打开串口

SerialPort serialPort = new SerialPort();

private void Form1_Load(object sender, EventArgs e)
        {
//绑定事件
            serialPort.DataReceived += SerialPort_DataReceived;
            OpenSerialPort();
        }


private void OpenSerialPort()//打开串口
        {
            if (serialPort.IsOpen)
            {
                return;
            }
            try
            {
                serialPort.Encoding = Encoding.GetEncoding("GB18030");
  

foreach (string com in System.IO.Ports.SerialPort.GetPortNames())//枚举所有可用的串口
            {
                comboBox1.Items.Add(com);
            }              

comboBox1.SelectedIndex = 0;

serialPort.PortName = comboBox1.Text;

serialPort.BaudRate = 115200;

serialPort.Parity = Parity.None;

serialPort.StopBits = StopBits.One;

serialPort.DataBits = 8;

//注意,如果串口打不开一定是你的串口参数设置不对,一定要看清楚
                serialPort.DataReceived += SerialPort_DataReceived;
                serialPort.Open();
            }
            catch
            {
                MessageBox.Show("打开串口失败!");
            }
        }


2.发送数据

private void SerialPortSend()
        {
            if (!serialPort.IsOpen)
            {
                MessageBox.Show("串口未打开,无法发送数据!");
                return;
            }
            try
            {
               Encoding encoding = Encoding.GetEncoding("GB2312");
                    byte[] bytes = encoding.GetBytes(data);
                    SendCount += (long)bytes.Length;
                    serialPort.Write(bytes, 0, bytes.Length); }
           
catch
            {
                MessageBox.Show("发送失败!");
            }
        }


3. 收数据

private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (this.SerialPortIsReceiving)
            {
                return;
            }
            try
            {
                SerialPortIsReceiving = true;
                string text = string.Empty;
                int num;
                text = serialPort.ReadExisting();
                    num = serialPort.Encoding.GetBytes(text).Length;

            }
            finally
            {
                SerialPortIsReceiving = false;
            }
        }


展开阅读全文

没有更多推荐了,返回首页