温湿度变送器 MODBUS RTU C# demo
1.打开visual studio 2012以及以上版本,在NuGet中搜NMobus程序包并安装。
2.在自己新建的C#项目中添加引用NModbus4.dll
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Threading.Tasks;
using Modbus;
using Modbus.Device;
namespace MXModbus
{
public class ModbusRtuClient {
public string deviceName;
public int deviceID;
public string softVersion;
private SerialPort port=null;
private IModbusSerialMaster master = null;
public float temperature;
public float humidity;
public ModbusRtuClient(string comNumber, int baudRate, int dataBit, StopBits stopBit, Parity p)
{
this.port = new SerialPort();
this.port.PortName = comNumber;
this.port.BaudRate = baudRate;
this.port.Parity = p;
this.port.DataBits = dataBit;
this.port.StopBits = stopBit;
if (!port.IsOpen)
{
port.Open();
master = ModbusSerialMaster.CreateRtu(port);
//master.Transport.ReadTimeout = 500;//读取数据超时500ms
//master.Transport.WriteTimeout = 500;//写入数据超时500ms
//master.Transport.Retries = 3;//重试次数
//master.Transport.WaitToRetryMilliseconds = 1000;//重试间隔
}
else
{
port.Close();
port.Open();
master = ModbusSerialMaster.CreateRtu(port);
}
}
public void ReadTempAndHum(int slaveID,out float temp, out float humidity)
{
ushort tempStartAddress = 0;
ushort humStartAddress = 1;
ushort[] holding_register1 = master.ReadHoldingRegisters((byte)slaveID, tempStartAddress, 1);
ushort[] holding_register2 = master.ReadHoldingRegisters((byte)slaveID, humStartAddress, 1);
temp = processTemp(holding_register1[0]);
humidity = processHumidity(holding_register2[0]);
}
public float ReadTemp(int salveID)
{
float temp = 0;
ushort tempStartAddress = 0;
ushort[] holding_register1 = master.ReadHoldingRegisters((byte)salveID, tempStartAddress, 1);
temp = processTemp(holding_register1[0]);
return temp;
}
public float ReadHumidity(int slaveID)
{
float temp = 0;
ushort tempStartAddress = 1;
ushort[] holding_register1 = master.ReadHoldingRegisters((byte)slaveID, tempStartAddress, 1);
temp = processHumidity(holding_register1[0]);
return temp;
}
~ModbusRtuClient()
{
master.Dispose();
port.Close();
}
private float processTemp(ushort temp)
{
float temp1 = 0;
if (temp >= 0 && temp <= 32767)
{
temp1 = Convert.ToSingle(temp / 10.0);
}
//负数范围0X8000-0XFFFF
else if (temp >= 32768 && temp <= 65535)
{
temp1 = Convert.ToSingle((temp- 65535) / 10.0);
}
return temp1;
}
private float processHumidity(ushort hum)
{
return Convert.ToSingle(hum / 10.0);
}
}
}