ModbusTCP在C#下的实现代码.pdf
文本预览下载声明
ModbusTCP 在C#下的实现代码
using (TcpClient client = new TcpClient(ip, 502))
using (ModbusIpMaster master = ModbusIpMaster.CreateIp(client))
{
//处理逻辑
//例:
//读取 %MW100.3 的值
bool requestIn = master.GetX(100, 3);
//设置 %MW100.3 的值
master.SetX(100,3,true);
}
//获取bool 值
public static bool GetX(this ModbusIpMaster master, ushort pos, ushort index)
{
bool returnValue = false;
try
{
if (master != null)
{
int iReturn = Convert.ToInt32(master.ReadHoldingRegisters(pos, 1)[0]);
string str = Convert.ToString(iReturn, 2).PadLeft(16, 0);
//char[] arr = str.ToCharArray();
return str[15 - index] == 0 ? false : true;
}
}
catch (Exception e)
{
throw (e);
}
return returnValue;
}
//设置bool 值
public static void SetX(this ModbusIpMaster master, ushort pos, ushort index, bool
value)
{
try
{
if (master != null)
{
int iReturn = Convert.ToInt32(master.ReadHoldingRegisters(pos, 1)[0]);
string str = Convert.ToString(iReturn, 2).PadLeft(16, 0);
char c = 0;
if (value)
c = 1;
char[] cc = str.ToArray();
cc[15 - index] = c;
ushort ivalue = Convert.ToUInt16(Stri
显示全部