.net winform 使用NModbus4建立 modbus tcp通讯

1、使用nuget引入NModbus4。

2、编写TCP访问modbus的方法

public void StartTcpClient(string ipstr,string portstr,ushort adress, ushort readLenth)

{

try

{

IPAddress myIP =IPAddress.Parse(ipstr);

int port = int.Parse(portstr);

IsListen = true;

TcpClient myclient = new TcpClient(ipstr, port);

ModbusMaster myMaster = ModbusIpMaster.CreateIp(myclient);

myMaster.Transport.ReadTimeout = 2000;

myMaster.Transport.Retries = 3;

myMaster.Transport.WaitToRetryMilliseconds = 250;

ushort[] value = myMaster.ReadHoldingRegisters(1, adress, readLenth);

}

catch (Exception ex)

{

Log4netHelper.MyErrorMsgLog("StartTcpClient 方法出错:" + ex.Message);

}

}

3、更多参数设置

连接参数设置:

master.Transport.ReadTimeout = 1000;//读取连接(串口)数据超时为

master.Transport.WriteTimeout = 1000;//写入连接(串口)数据超时

master.Transport.Retries = 3;//重试次数

master.Transport.WaitToRetryMilliSeconds = 250;//重试间隔

可读写线圈调用函数:

//读线圈,参数:从站地址 (8位 ) 、起始地址 (16位 ) 、数量 (16位 ) ;返回布尔型数 组

bool[] ReadCoils(byte slaveAddress, ushort startAddress, ushort numberOfPoints);

//读输入离散量,参数:从站地址 (8位 ) 、起始地址 (16位 ) 、数量 (16位 ) ;返回布 尔型数组

bool[] ReadInputs(byte slaveAddress, ushort startAddress, ushort numberOfPoints);

//读保持寄存器,参数:从站地址 (8位 ) 、起始地址 (16位 ) 、数量 (16位 ) ;返回 16位整型数组

ushort[] ReadHoldingRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints);

//读输入寄存器,参数:从站地址 (8位 ) 、起始地址 (16位 ) 、数量 (16位 ) ;返回 16位整型数组

ushort[] ReadInputRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints);

//写单个线圈,参数:从站地址 (8位 ) ,线圈地址 (16位 ) ,线圈值 (布尔型 )

void WriteSingleCoil(byte slaveAddress, ushort coilAddress, bool value);

//写单个寄存器,参数:从站地址 (8位 ) ,寄存器地址 (16位 ) ,寄存器值 (16位 )

void WriteSingleRegister(byte slaveAddress, ushort registerAddress, ushort value);

//写多个寄存器,参数:从站地址 (8位 ) ,起始地址 (16位 ) ,寄存器值 (16位整型 数组 )

void WriteMultipleRegisters(byte slaveAddress, ushort startAddress, ushort[] data);

//写多个线圈,参数:从站地址 (8位 ) ,起始地址 (16位 ) ,线圈值 (布尔型数组 )

void WriteMultipleCoils(byte slaveAddress, ushort startAddress, bool[] data);

//读写多个寄存器,参数:从站地址 (8位 ) ,读起始地址 (16位 ) ,数量 (16位 ) ,写 起始地址 (16位 ) ,写入值 (16位整型数组 ) ;返回 16位整型数组

ushort[] ReadWriteMultipleRegisters(byte slaveAddress, ushort startReadAddress, ushort numberOfPointsToRead, ushort startWriteAddress, ushort[] writeData);

相关推荐
啊?啊?30 分钟前
4 解锁 Linux 操作新姿势:man、grep、tar ,创建用户及添加权限等 10 大实用命令详解
linux·服务器·实用指令
时空潮汐34 分钟前
神卓 N600:内网穿透需求的高效安全之选
网络·安全·群晖nas·神卓n600
爱倒腾的老唐43 分钟前
24、Linux 路由管理
linux·运维·网络
程序员Aries1 小时前
自定义网络协议与序列化/反序列化
linux·网络·c++·网络协议·程序人生
_清浅1 小时前
计算机网络【第六章-应用层】
运维·服务器·计算机网络
正在努力的小河1 小时前
Linux 自带的 LED 灯驱动实验
linux·运维·服务器
济南java开发,求内推1 小时前
Redis一个服务器部署多个节点
服务器·数据库·redis
恒创科技HK2 小时前
如何选30G、60G、100G的香港高防服务器?
运维·服务器
Le_ee2 小时前
Apache2
服务器·网络安全·apache·web
wanhengidc2 小时前
云手机 手游专用虚拟手机
运维·服务器·安全·游戏·智能手机