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

相关推荐
飞奔的瓜牛11 小时前
Linux 数据盘分区、格式化与自动挂载完整实践
linux·运维·服务器
Lucas. Wáng12 小时前
Linux网络编程之网络套接字
linux·服务器·网络
数字新视界12 小时前
动环智能监控在机房管理中的智能应用与安全保障
服务器·数据中心·机房·环境管理·环控系统
进击的荆棘12 小时前
Linux网络——Socket编程TCP
linux·运维·服务器·网络·tcp/ip
大今野13 小时前
2026 专转本计算机|Linux CentOS7 软件包管理:yum 仓库配置与常用命令考点全解(附例题)
linux·运维·服务器·专转本
无奈笑天下13 小时前
Wine适配Windows程序常见故障标准处理流程
linux·运维·服务器·windows
沫璃染墨14 小时前
从零入门计算机网络系列(二十六):IPv4分片机制详解——从MTU与MSS到报文分片与重组
运维·服务器·网络·网络协议·tcp/ip·ip
无足鸟ICT15 小时前
【RHCA+】hdparm命令(查看硬盘)
linux·运维·服务器
Jeff-Tsai15 小时前
Day 28:DateTime 的时区转换
.net·架构设计·erp·definition-driven
IT规划师16 小时前
Redis 核心机制 | Lua 脚本:服务端原子操作·架构决策与生产落地
redis·.net