C#中的Modbus串行端口数据读取

本文关键字:数据 读取 串行端口 Modbus 中的 | 更新日期: 2023-09-27 18:32:46

嗨,我正在尝试读取串行端口数据。我使用NModbus库进行modbus通信。代码适用于读取和写入目的。但有时我会遇到一些未知的错误,我想查看串行端动。我尝试使用SerialDataReceivedEventHandler但我没有从端口获得任何东西,但我仍然能够读取保持寄存器的值。这是我的代码。我只想看到通过串行端口发送/接收的数据包。

namespace ModbusMaster
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;

        }
        void Form1_Load(object sender, EventArgs e)
        {
            int[] baud = new int[] {4800,9600,19200,38400,57600,115200};
            int[] databit = new int[] { 7, 8 };
            int[] stpBits = new int[] { 1, 2 };
            string[] party = new string[] { "None", "Odd", "Even" };
            string[] Mode = new string[] { "ASCII", "RTU" };
            ModbusMode.DataSource = Mode;
            Baud_Rate.DataSource = baud;
            Data.DataSource = databit;
            Stop.DataSource = stpBits;
            Pari.DataSource = party;
            GetPortList();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string ProtocolMode = ModbusMode.GetItemText(ModbusMode.SelectedItem);
            string portName = listBox1.GetItemText(listBox1.SelectedItem);
            if (listBox1.SelectedIndex == -1)
            {
                MessageBox.Show("Please select Serial Port!!!");
            }
            else
            {
                using ( SerialPort port = new SerialPort(portName))
                {
                    if (port != null && port.IsOpen)
                    {
                        port.Close();
                    }
                    // configure serial port
                    port.BaudRate = int.Parse(Baud_Rate.Text);
                    port.DataBits = int.Parse(Data.Text);
                    port.Parity = (Parity)Enum.Parse(typeof(Parity), Pari.Text);
                    port.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Stop.Text);
                    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
                    port.Open();
                    // create modbus master
                    if (ProtocolMode == "RTU")
                    {
                        IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
                        int temp = ushort.Parse(StrtAdd.Text)- 1;
                        byte slaveId = byte.Parse(Slave.Text);
                        ushort startAddress = (ushort)(temp);
                        ushort points = ushort.Parse(regis.Text);
                        ushort[] holding_register = new ushort[] { };
                        holding_register = master.ReadHoldingRegisters(slaveId, startAddress, points);
                        string tempString = " ";
                        foreach (ushort value in holding_register)
                        {
                            tempString += value + " ";
                        }
                        val.Text = tempString;
                       // val.Text = Convert.ToString(holding_register[0] + " " + holding_register[1]);
                    }
                    if (ProtocolMode == "ASCII")
                    {
                        IModbusSerialMaster master = ModbusSerialMaster.CreateAscii(port);
                        int temp = ushort.Parse(StrtAdd.Text)- 1;
                        byte slaveId = byte.Parse(Slave.Text);
                        ushort startAddress = (ushort)(temp);
                        ushort points = ushort.Parse(regis.Text);
                        ushort[] holding_register = new ushort[] { };
                        holding_register = master.ReadHoldingRegisters(slaveId, startAddress, points);
                        string tempString = " ";
                        foreach (ushort value in holding_register)
                        {
                            tempString += value + " ";
                        }
                    }
                }
            }
        }
        private void port_DataReceived(object sender,    SerialDataReceivedEventArgs e)
        {
            // Show all the incoming data in the port's buffer
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            RcdPacket.Text = indata;
        }
        private void GetPortList()
        {
            listBox1.Items.Clear();
            foreach (string item in System.IO.Ports.SerialPort.GetPortNames())
            {
                //store the each retrieved available prot names into the Listbox...
                listBox1.Items.Add(item);
            }

        }
        private void WriteData_Click(object sender, EventArgs e)
        {
            string ProtocolMode = ModbusMode.GetItemText(ModbusMode.SelectedItem);
            string portName1 = listBox1.GetItemText(listBox1.SelectedItem);
            if (listBox1.SelectedIndex == -1)
            {
                MessageBox.Show("Please select Serial Port!!!");
            }
            else
            {
                using (SerialPort port1 = new SerialPort(portName1))
                {
                    if (port1 != null && port1.IsOpen)
                    {
                        port1.Close();
                    }
                    port1.BaudRate = int.Parse(Baud_Rate.Text);
                    port1.DataBits = int.Parse(Data.Text);
                    port1.Parity = (Parity)Enum.Parse(typeof(Parity), Pari.Text);
                    port1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Stop.Text);


                    if (ProtocolMode == "RTU")
                    {
                        port1.Open();
                        IModbusSerialMaster master1 = ModbusSerialMaster.CreateRtu(port1);
                        int temp = ushort.Parse(WriteAdd.Text) - 1;
                        byte slaveId = byte.Parse(SlvIdd.Text);
                        ushort startAdd = (ushort)(temp);
                        ushort WrValue = ushort.Parse(WriteVal.Text);
                        master1.WriteSingleRegister(slaveId, startAdd, WrValue);
                    }
                    if (ProtocolMode == "ASCII")
                    {
                        port1.Open();
                        IModbusSerialMaster master1 = ModbusSerialMaster.CreateAscii(port1);
                        int temp = ushort.Parse(WriteAdd.Text) - 1;
                        byte slaveId = byte.Parse(SlvIdd.Text);
                        ushort startAdd = (ushort)(temp);
                        ushort WrValue = ushort.Parse(WriteVal.Text);
                        master1.WriteSingleRegister(slaveId, startAdd, WrValue);
                    }

                }
            }
        }
   }
}

C#中的Modbus串行端口数据读取

如果你只想查看流动的流量,我建议使用 Sysinternals 的 Portmon。这也保证了您所看到的实际上是在端口上收到的内容