Add ModBus communication with hardcoded values
This commit is contained in:
@@ -1,10 +1,50 @@
|
|||||||
namespace TestApp
|
using NModbus;
|
||||||
|
using System.Net.Sockets;
|
||||||
|
|
||||||
|
namespace TestApp
|
||||||
{
|
{
|
||||||
internal class Program
|
internal class Program
|
||||||
{
|
{
|
||||||
static void Main(string[] args)
|
static void Main(string[] args)
|
||||||
{
|
{
|
||||||
Console.WriteLine("Hello, World!");
|
while (true)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ConnectToModBus();
|
||||||
}
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Error connecting to ModBus slave: {ex.Message}");
|
||||||
|
Thread.Sleep(5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ConnectToModBus()
|
||||||
|
{
|
||||||
|
var factory = new ModbusFactory();
|
||||||
|
var tcpClient = new TcpClient("192.168.188.21", 502);
|
||||||
|
var master = factory.CreateMaster(tcpClient);
|
||||||
|
Console.WriteLine("ModBus TCP Connection established!");
|
||||||
|
|
||||||
|
while (tcpClient.Connected)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ushort input = master.ReadHoldingRegisters(1, 1000, 1)[0];
|
||||||
|
ushort output = (ushort)(input + 50);
|
||||||
|
master.WriteMultipleRegisters(1, 1100, new ushort[] { output });
|
||||||
|
Console.WriteLine($"Register values updated to {input} + 50 = {output}");
|
||||||
|
Thread.Sleep(100);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Error updating ModBus registers: {e.Message}");
|
||||||
|
Thread.Sleep(1000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,4 +7,8 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="NModbus" Version="3.0.72" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
Reference in New Issue
Block a user