NMODBUS4中负值写到D寄存器中以32位数据传输得方法。
/// <summary>
/// Write a 32 bit value.
/// </summary>
public static void ReadWrite32BitValue()
{
using (SerialPort port = new SerialPort("COM1"))
{
// configure serial port
port.BaudRate = 9600;
port.DataBits = 8;
port.Parity = Parity.None;
port.StopBits = StopBits.One;
port.Open();
var adapter = new SerialPortAdapter(port);
// create modbus master
ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(adapter);
byte slaveId = 1;
ushort startAddress = 1008;
uint largeValue = UInt16.MaxValue + 5;
ushort lowOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(largeValue), 0);
ushort highOrderValue = BitConverter.ToUInt16(BitConverter.GetBytes(largeValue), 2);
// write large value in two 16 bit chunks
master.WriteMultipleRegisters(slaveId, startAddress, new ushort[] { lowOrderValue, highOrderValue });
// read large value in two 16 bit chunks and perform conversion
ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, 2);
uint value = ModbusUtility.GetUInt32(registers[1], registers[0]);
}
}