'Separate connection file in C# and ModbusClient
Could you help me with this:
I need to create a connection file to a PLC through ModbusClient, a separate file from the Main, but within the same solution. I have it like this: enter image description here
And this is the code:
namespace HMIOperations
{
internal class Connection_PLC
{
public ModbusClient Connect(ModbusClient modbusClientreturn)
{
IPAddress plcIp = IPAddress.Parse("192.168.3.250");
int plcPort = 49501;
modbusClientreturn = new ModbusClient
{
IpAddress = plcIp,
Port = plcPort
};
//Connect to PLC
try
{
modbusClientreturn.Connect();
}
catch (Exception exception)
{
MessageBox.Show("Conexion no establecida con el PLC.\n Intenta de nuevo.");
}
return modbusClientreturn;
}
}
}
My question is, how can I use this file in the main and in the other files where I need it. That I have to do?
Solution 1:[1]
The problem can be solved like this:
Class internal : you can just use the same namespace. Try this:
Public class Connection_PLC
Replace this solution with the following code that has been tested and my currently used one.
using EasyModbus; ModbusClient Plc= new ModbusClient(); private Thread Data_thread = (Thread)null; private int[] Registerlist; private void connect() { Plc.Disconnect(); ServerIP = "192.168.3.250"; Plc.Connect(ServerIP, 502); this.Data_thread = new Thread(new ThreadStart(this.getmessage)); this.Data_thread.Start(); } private void getmessage() { while (Plc.Connected) { Registerlist= Plc.ReadHoldingRegisters(8,1);//yourregister } }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ugurrrn |