title: Modbus Serial Port Data Reading in C#
body: <p>Hi I am trying to read the Serial Port Data. I used NModbus library for the modbus communication. Code works fine for read and write purpose. But sometimes i am having some unknown errors and i wanted to see the serial port activity. I tried using the <code>SerialDataReceivedEventHandler</code> but i am not getting anything from the port but still i am able to read the value of the holding registers. Here is my code. All i want to see the data packet being sent / received over the serial port.</p>
  
  <pre><code>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 &amp;&amp; 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 &amp;&amp; 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);
                      }
  
  
                  }
  
              }
          }
     }
  }
  </code></pre>