/// <summary> /// Test modbus RTU master function on a slave RTU id = 5 /// </summary> private static void Test_ModbusRTUMaster() { byte unit_id = 5; // Create instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5). ModbusMasterSerial mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM20", 9600, 8, Parity.Even, StopBits.One, Handshake.None); // Initialize the MODBUS connection. mm.Connect(); // Read and write some registers on RTU n. 5. Random rnd = new Random(); while (true) { // Print some nice formatting to the console. Console.WriteLine("---------------------- READING ----------------------"); // Read from a register. ushort inputReg1 = mm.ReadHoldingRegisters(unit_id, 0, 1).First(); // Print the result to the console. Console.WriteLine("Holding register n.1 : " + inputReg1.ToString("D5")); // Read from another register. ushort inputReg41 = mm.ReadInputRegisters(unit_id, 40, 1).First(); // Print the result to the console. Console.WriteLine("Input register n.41 : " + inputReg41.ToString("D5")); // Read from a coil. bool coil23 = mm.ReadCoils(unit_id, 22, 1).First(); // Print the results to the console. Console.WriteLine("Coil register n 23 : " + coil23.ToString()); // Print some nice formatting to the console. Console.WriteLine("---------------------- WRITING ----------------------"); // Write to a register. mm.WriteSingleRegister(unit_id, 4, (ushort)rnd.Next(ushort.MinValue, ushort.MaxValue)); // ...then read it back. ushort holdingReg4 = mm.ReadHoldingRegisters(unit_id, 4, 1).First(); // Print the result to the console. Console.WriteLine("Holding register n.5 : " + holdingReg4.ToString("D5") + Environment.NewLine); // Write to another register. mm.WriteSingleCoil(unit_id, 2, Convert.ToBoolean(rnd.Next(0, 1))); // ...then read it back. bool holdingReg3 = mm.ReadCoils(unit_id, 2, 1).First(); // Print the result to the console. Console.WriteLine("Coil register n.3 : " + holdingReg3.ToString() + Environment.NewLine); // Repeat every 2 seconds. Thread.Sleep(2000); } }
private void reconnect() { if (Properties.Settings.Default.CommPort != "") { try { if (mm != null) { mm.Disconnect(); } } catch (Exception) { } try { mm = new ModbusMasterSerial(ModbusSerialType.RTU, Properties.Settings.Default.CommPort, 19200, 8, Parity.None, StopBits.One, Handshake.None); setCommPortMenu(Properties.Settings.Default.CommPort); mm.RxTimeout = 500; mm.Connect(); commStatus.Text = "COMM OK"; } catch (Exception) { commStatus.Text = "COMM ERR"; } } }
/// <summary> /// Test modbus RTU master function on a slave RTU id = 5 /// </summary> static void Test_ModbusRTUMaster() { byte unit_id = 5; // Crete instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5) ModbusMasterSerial mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM1", 9600, 8, Parity.Even, StopBits.One, Handshake.None); // Exec the connection mm.Connect(); // Read and write some registers on RTU n. 5 Random rnd = new Random(); while (true) { Console.Write( "---------------------- READING ----------------------" + Environment.NewLine + "Holding register n.1 : " + mm.ReadHoldingRegisters(unit_id, 0, 1).First().ToString("D5") + Environment.NewLine + "Input register n.41 : " + mm.ReadInputRegisters(unit_id, 40, 1).First().ToString("D5") + Environment.NewLine + "Coil register n 23 : " + mm.ReadCoils(unit_id, 22, 1).First().ToString() + Environment.NewLine + "---------------------- WRITING ----------------------" + Environment.NewLine); mm.WriteSingleRegister(unit_id, 4, (ushort)rnd.Next(ushort.MinValue, ushort.MaxValue)); Console.WriteLine( "Holding register n.5 : " + mm.ReadHoldingRegisters(unit_id, 4, 1).First().ToString("D5") + Environment.NewLine); mm.WriteSingleCoil(unit_id, 2, Convert.ToBoolean(rnd.Next(0, 1))); Console.WriteLine( "Coil register n.3 : " + mm.ReadCoils(unit_id, 2, 1).First().ToString() + Environment.NewLine); // Exec the cicle each 2 seconds Thread.Sleep(2000); } }
//construct public cModBusData() { // Crete instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5) mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM8", 460800, 8, Parity.None, StopBits.One, Handshake.None); // Exec the connection mm.Connect(); Th_mb_pauseEvent = new ManualResetEvent(true); //intial modbus //ModBusData.ModbusRTUMaster_Initial(); }
// ------------------------------------------------------------------------ /// <summary>Se conecta al PLC</summary> public bool conectar() { switch (Protocol) { case "MODBUS/TCP": { if (!connected) { try { connect(IPAddress, Port); } catch (Exception ex) { MessageLog.Add(ex.Message); } } bCommError = false; return(connected); } case "MODBUS/RTU": { if (!connected_rtu) { try { if (Type == "slave") { mm = new ModbusMasterSerial(ModbusSerialType.RTU, SerialPort, BaudRate, 8, Parity, StopBits, Handshake.None); mm.Connect(); connected_rtu = true; } else { connected_rtu = false; throw new Exception("No se reconoce tipo"); } } catch (Exception err) { MessageLog.Add(err.Message + "\r\n" + err.StackTrace + "\r\n" + err.TargetSite + "\r\n"); connected_rtu = false; } } bCommError = false; return(connected_rtu); } default: return(!connected); } }
private void button1_Click(object sender, EventArgs e) { byte unit_id = 1; // Crete instance of modbus serial RTU (replace COMx with a free serial port - ex. COM5) ModbusMasterSerial mm = new ModbusMasterSerial(ModbusSerialType.RTU, "COM1", 9600, 8, Parity.Even, StopBits.One, Handshake.None); // Exec the connection mm.Connect(); // Read and write some registers on RTU n. 5 Random rnd = new Random(); while (true) { textBox1.Text = "Holding register n.1 : " + mm.ReadHoldingRegisters(unit_id, 0, 1).First().ToString("D5") + "Input register n.41 : " + mm.ReadInputRegisters(unit_id, 40, 1).First().ToString("D5") + "Coil register n 23 : " + mm.ReadCoils(unit_id, 22, 1).First().ToString(); mm.WriteSingleRegister(unit_id, 4, (ushort)rnd.Next(ushort.MinValue, ushort.MaxValue)); textBox2.Text = "Holding register n.5 : " + mm.ReadHoldingRegisters(unit_id, 4, 1).First().ToString("D5"); mm.WriteSingleCoil(unit_id, 2, Convert.ToBoolean(rnd.Next(0, 1))); textBox3.Text = "Coil register n.3 : " + mm.ReadCoils(unit_id, 2, 1).First().ToString(); // Exec the cicle each 2 seconds Thread.Sleep(2000); } }
/// <summary> /// When the user selects a radio button, open or close the serial port. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RadioButton_CheckedChanged(object sender, EventArgs e) { // Do stuff only if the radio button is checked. // (Otherwise the actions will run twice.) if (((RadioButton)sender).Checked) { try { // If the "Open" radio button has been checked... if (((RadioButton)sender) == radioButtonOpen) { // Alert the user. toolStripStatusLabel1.Text = "Opening serial port..."; // Fetch the selected serial port. string portName = comboBoxSerialPort.SelectedItem.ToString(); if (string.IsNullOrEmpty(portName)) { throw new ArgumentException("Serial Port not selected."); } // Fetch the selected baud rate. if (int.TryParse(comboBoxBaudRate.SelectedItem.ToString(), out int baudRate) == false) { throw new ArgumentException("Invalid baud rate."); } // Get the selected parity mode. string parityName = comboBoxParity.SelectedItem.ToString(); if (string.IsNullOrEmpty(parityName)) { throw new ArgumentException("Parity type not selected"); } Parity parity = Parity.Even; if (parityName == "None") { parity = Parity.None; } else if (parityName == "Odd") { parity = Parity.Odd; } // Get the selected MODBUS mode (ASCII or RTU). string modeString = comboBoxMode.SelectedItem.ToString(); if (modeString == null) { throw new ArgumentException("Modbus Mode not selected"); } ModbusSerialType mode = ModbusSerialType.RTU; if (modeString == "ASCII") { mode = ModbusSerialType.ASCII; } // Select the MODBUS packet size based on the selected mode. int datasize = 8; if (mode == ModbusSerialType.ASCII) { datasize = 7; } // Get the selected number of stop bits. object stopBits = comboBoxStopBits.SelectedItem; if (stopBits == null) { throw new ArgumentException("Stop Bits not selected"); } // Convert stop bits string to comm port setting. StopBits stopbits = StopBits.One; if (stopBits.ToString() == "2") { stopbits = StopBits.Two; } // Create and open serial port. _mbMaster = new ModbusMasterSerial(mode, portName.ToString(), baudRate, datasize, parity, stopbits, Handshake.None); _mbMaster.Connect(); // Disable the serial port controls. buttonPortRefresh.Enabled = false; comboBoxSerialPort.Enabled = false; comboBoxBaudRate.Enabled = false; comboBoxParity.Enabled = false; comboBoxMode.Enabled = false; comboBoxStopBits.Enabled = false; // Enable the MODBUS communication controls. groupBoxAddress.Enabled = true; groupBoxData.Enabled = true; // Update the status bar. toolStripStatusLabel1.Text = "Port open."; } else if (((RadioButton)sender) == radioButtonClosed) { // Alert the user. toolStripStatusLabel1.Text = "Closing serial port..."; // Dispose of the MODBUS class. _mbMaster?.Disconnect(); // Enable the serial port controls. buttonPortRefresh.Enabled = true; comboBoxSerialPort.Enabled = true; comboBoxBaudRate.Enabled = true; comboBoxParity.Enabled = true; comboBoxMode.Enabled = true; comboBoxStopBits.Enabled = true; // Disable the MODBUS communication controls. groupBoxAddress.Enabled = false; groupBoxData.Enabled = false; // Update the status bar. toolStripStatusLabel1.Text = "Port closed."; } } // If an error occurs... catch (Exception ex) { // Alert the user. MessageBox.Show(ex.Message, ex.GetType().Name.ToString()); // Undo the user action. radioButtonClosed.Checked = true; } } }