.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);

相关推荐
蜗牛互联网1 小时前
Python Agent工具调用的白名单、参数校验与审批门禁
java·服务器·前端·人工智能·后端·python
zxanz12 小时前
SSL 证书申请下来快吗?
网络·网络协议·ssl
false_or_true2 小时前
一次由 tcp_tw_recycle 引发的“灵异”故障排查:基于双网闸架构的踩坑记
网络·tcp/ip·架构
小HANN2 小时前
华为云企业网站上云实战|从零搭建高可用WordPress全站架构(ECS+RDS+ELB+弹性伸缩+云监控闭环)
linux·运维·服务器·经验分享
爱写代码的倒霉蛋2 小时前
我用book-to-skill把尹圣雨的《TCP/IP网络编程》做成了知识库(适合快速入门网络编程)
网络·网络编程·知识库
..过云雨2 小时前
19.【网络】多路转接poll、epoll、Reactor反应堆 - 修正版
网络
Raas1003 小时前
MAI Gateway(魔芋企业级AI网关)功能全解:AI网关能做Prompt注入防护吗?一文看懂AI网关能力矩阵(v1.2.0)
网络·人工智能·gateway·prompt·mai gateway·企业级ai网关·企业级产品
Lzg_na3 小时前
DHCP 作用、原理、机制和报文格式详解
网络
祖力553 小时前
驱动工程搭建与字符设备驱动框架
linux·运维·服务器·内核·arm·imx6ull·驱动
发量惊人的中年网工3 小时前
SD-WAN 组网方案怎么选?跨地域与多分支企业的选型指南(含成本对比)
服务器·网络·数据库