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

相关推荐
阿巴~阿巴~15 小时前
JsonCpp:C++ JSON处理利器
linux·网络·c++·json·tcp·序列化和反序列化
j***294815 小时前
IPV6公网暴露下的OPENWRT防火墙安全设置(只允许访问局域网中指定服务器指定端口其余拒绝)
服务器·安全·php
ao_lang15 小时前
数据链路层
linux·服务器·网络
yangshuquan15 小时前
关于 C# 函数参数修饰符 out 和 in 的真相
c#·参数·in·修饰符·out
全栈师15 小时前
C#中控制权限的逻辑写法
开发语言·c#
额呃呃15 小时前
零拷贝I/O的核心概念
服务器·php·apache
执笔论英雄16 小时前
【RL】python协程
java·网络·人工智能·python·设计模式
夏霞16 小时前
c# 使用vs code 创建.net8.0以及.net6.0 webApi项目的教程
开发语言·c#·.net
追逐时光者16 小时前
C#/.NET/.NET Core优秀项目和框架2025年11月简报
后端·.net
小兔薯了16 小时前
7. LNMP-wordpress
android·运维·服务器·数据库·nginx·php