Since 2002 began to contact the Modbus agreement, in the future in the PLC, DOS, Windows,. Net Micro framework, such as the use of the Protocol, in my previous blog to write a detailed record of this experience, interested friends can look at the " My Modbus slave/client development process (RTU/ASCII/TCP). The protocol is open, concise and reliable, at present most intelligent instruments, intelligent modules and some PLC have adopted the protocol, some time ago, a netizen asked about the relevant Modbus problem, so here on the implementation of the Modbus as a. Net MF Development Board example serial port.
This example consists of two parts, one running on the development Board, as the Modbus RTU slave service, and the other part of the typical. Net framework code that implements the Modbus RTU client-side functionality, You can use the Slave service on the Development Board to control the LED lights on the development Board and get the button status.
The implementation of the Slave class is as follows (see sample source code for specific implementation):
namespace YFSoft.Modbus
{
public class Slave
{
//数据区读写事件
public event ReadDataEventHandler ReadData;
public event WriteDataEventHandler WriteData;
//启动Modbus服务
public void Start(string portName, int baudRate, Parity parity);
//停止Modbus服务
public void Stop();
}
}
The call is relatively simple and the code is as follows:
public static void Main()
{
Graphics.Clear(Color.Black);
Graphics.Print("Modbus Rtu Test\r\n");
… …
RtuSlave.ReadData += new ReadDataEventHandler(RtuSlave_ReadData);
RtuSlave.WriteData += new WriteDataEventHandler(RtuSlave_WriteData);
RtuSlave.Start("COM2", 19200, System.IO.Ports.Parity.None);
int index = 0;
while (true)
{
//leds[0].Write(!leds[0].Read());
Graphics.FillRectangle(0, 305, 240, 15, Color.White);
Graphics.DrawString(5, 306, (index++).ToString(), Color.Blue);
Thread.Sleep(1000);
}
//RtuSlave.Stop();
}