Documentation
FieldTalk Modbus Master Library for .NET
Examples |
This topic contains the following sections:
The following example sersimple.cpp shows how to configure a serial Modbus protocol and read values:
using System; using System.Threading; using FieldTalk.Modbus.Master; class SerSimpleApp { //MbusAsciiMasterProtocol mbusProtocol = new MbusAsciiMasterProtocol(); // Use this declaration for ASCII MbusRtuMasterProtocol mbusProtocol = new MbusRtuMasterProtocol(); // Use this declaration for RTU void openProtocol() { int result; result = mbusProtocol.openProtocol("COM1", 19200, // Baudrate MbusSerialClientBase.SER_DATABITS_8, MbusSerialClientBase.SER_STOPBITS_1, MbusSerialClientBase.SER_PARITY_EVEN); if (result != BusProtocolErrors.FTALK_SUCCESS) { Console.WriteLine("Error opening protocol: " + BusProtocolErrors.getBusProtocolErrorText(result)); Environment.Exit(result); } } void closeProtocol() { mbusProtocol.closeProtocol(); } void runPollLoop() { Int16[] dataArr = new Int16[10]; for (;;) { int result; result = mbusProtocol.readMultipleRegisters(1, 100, dataArr); if (result == BusProtocolErrors.FTALK_SUCCESS) for (int i = 0; i < dataArr.Length; i++) Console.WriteLine("[" + (100 + i) + "]: " + dataArr[i]); else { Console.WriteLine(BusProtocolErrors.getBusProtocolErrorText(result) + "!"); // Stop for fatal errors if ((result & BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS) != BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS) return; } Thread.Sleep(1000); } } public static void Main() { SerSimpleApp app = new SerSimpleApp(); app.openProtocol(); app.runPollLoop(); app.closeProtocol(); } }
The following example tcpsimple.cpp shows how to configure a MODBUS/TCP protocol and read values:
using System; using System.Threading; using FieldTalk.Modbus.Master; class TcpSimpleApp { MbusTcpMasterProtocol mbusProtocol = new MbusTcpMasterProtocol(); void openProtocol() { int result; result = mbusProtocol.openProtocol("127.0.0.1"); if (result != BusProtocolErrors.FTALK_SUCCESS) { Console.WriteLine("Error opening protocol: " + BusProtocolErrors.getBusProtocolErrorText(result)); Environment.Exit(result); } } void closeProtocol() { mbusProtocol.closeProtocol(); } void runPollLoop() { Int16[] dataArr = new Int16[10]; for (;;) { int result; result = mbusProtocol.readMultipleRegisters(1, 100, dataArr); if (result == BusProtocolErrors.FTALK_SUCCESS) { for (int i = 0; i < dataArr.Length; i++) Console.WriteLine("[" + (100 + i) + "]: " + dataArr[i]); } else { Console.WriteLine(BusProtocolErrors.getBusProtocolErrorText(result) + "!"); // Stop for fatal errors if ((result & BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS) != BusProtocolErrors.FTALK_BUS_PROTOCOL_ERROR_CLASS) return; } Thread.Sleep(1000); } } public static void Main() { TcpSimpleApp app = new TcpSimpleApp(); app.openProtocol(); app.runPollLoop(); app.closeProtocol(); } }