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

相关推荐
勤奋的小王同学~6 分钟前
(网络编程)网络编程套接字 UDP的socket API 代码解析
网络
paopaokaka_luck7 分钟前
绿色环保活动平台(AI问答、WebSocket即时通讯、协同过滤算法、Echarts图形化分析)
java·网络·vue.js·spring boot·websocket·网络协议·架构
wow_DG7 分钟前
【WebSocket✨】入门之旅(三):WebSocket 的实战应用
网络·websocket·网络协议
NiKo_W18 分钟前
Linux 深入理解权限
linux·运维·服务器
江流月照38 分钟前
PCIE地址空间介绍
java·服务器·网络
好望角雾眠42 分钟前
第四阶段C#通讯开发-1:通讯基础理论,串口,通讯模式,单位转换,代码示例
开发语言·笔记·c#·串口·通讯
代码炼金术士1 小时前
服务器更换jar包,重启后端服务
服务器·jar
郝学胜-神的一滴1 小时前
深入探索 Python 元组:从基础到高级应用
运维·服务器·开发语言·python·程序人生
CheungChunChiu1 小时前
嵌入式 Linux 启动机制全解析:从 Boot 到 Rootfs
linux·运维·服务器·ubuntu·uboot·boot·extboot
白鹭1 小时前
nginx(介绍+源码安装+平滑升级和回滚)
linux·运维·服务器·nginx·回滚·平滑升级