Author: Admin 12/08/2024
Language:
C#
Tags: modbus tcp
The following example shows how to configure a MODBUS/TCP protocol and read values.
The following example tcpsimple.cpp shows how to configure a MODBUS/TCP protocol and read values
This code uses the FieldTalk Modbus driver/dll. I used this in a SCADA system I built for an Irrigation District.
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();
}
}
Read more here https://www.modbusdriver.com/doc/mbusmaster.net/examples.htm