Commication with two modbus devices on the same bus in a row throws a timeout exception for second device. Adding a short delay between communicating with each device appears to fix it.
static void MyModbus()
{
Modbus modbus = new Modbus(6);
DateTime dtOld = DateTime.Now;
TimeSpan ts;
while (true)
{
dtOld = DateTime.Now;
modbus.Send(11);
Thread.Sleep(10);
modbus.Send(10);
ts = DateTime.Now - dtOld;
Debug.WriteLine($"MyModbus {ts.TotalMilliseconds}");
Thread.Sleep(10);
}
}
internal class Modbus
{
UartController serial;
ModbusMaster mbMaster;
byte modbusAddr = 0;
ushort[] reply = null;
int count = 0;
int TotalCount = 0;
public Modbus(int portNr)
{
IModbusInterface mbInterface;
UartSetting uartSetting;
if (portNr == 6)
{
serial = UartController.FromName(SC20100.UartPort.Uart7);
modbusAddr = 10;
uartSetting = new UartSetting()
{
BaudRate = 57600,
DataBits = 8,
Parity = UartParity.None,
StopBits = UartStopBitCount.One,
EnableDePin = true,
InvertDePolarity = true,
};
mbInterface = new ModbusRtuInterface(serial, 57600, 8, UartStopBitCount.One, UartParity.None);
}
else
{
serial = UartController.FromName(SC20100.UartPort.Uart2);
modbusAddr = 11;
uartSetting = new UartSetting()
{
BaudRate = 9600,
DataBits = 8,
Parity = UartParity.None,
StopBits = UartStopBitCount.One,
EnableDePin = true,
InvertDePolarity = true,
};
mbInterface = new ModbusRtuInterface(serial, 9600, 8, UartStopBitCount.One, UartParity.None);
}
mbMaster = new ModbusMaster(mbInterface);
serial.SetActiveSettings(uartSetting);
serial.Enable();
}
public void Send(byte addr)
{
try
{
TotalCount++;
reply = mbMaster.ReadInputRegisters(addr, 49, 20, 2000);
count++;
}
catch (System.Exception error)
{
Debug.WriteLine($"Modbus Timeout: {modbusAddr} + {error}");
Thread.Sleep(100);
}
if(TotalCount % 30 == 0)
{
Debug.WriteLine($"Modbus addr:{modbusAddr}, Total:{TotalCount}, succed: {count}, diff: {TotalCount-count}");
}
}
}