Hello
I am experimenting with the Modbus RTU and using the Arduino MKR boards and RS485 shields. The sketches for both server and client are given below:
****************** Server sketch **************
#include <ArduinoRS485.h>
#include <ArduinoModbus.h>
void setup() {
Serial.begin(9600);
// start the Modbus RTU server, with (slave) id 1
if (!ModbusRTUServer.begin(1, 9600)) {
Serial.println("Failed to start Modbus RTU Server!");
while (1);
}
// configure holding registers at address 0x00
ModbusRTUServer.configureHoldingRegisters(0x00, 1);
}
void loop() {
// poll for Modbus RTU requests
ModbusRTUServer.poll();
ModbusRTUServer.holdingRegisterWrite(0, 100);
delay(5000);
}
}
The client sketch is:
***************Client*****************
#include <ArduinoRS485.h>
#include <ArduinoModbus.h>
void setup() {
Serial.begin(9600);
while (!Serial);
// start the Modbus RTU client
if (!ModbusRTUClient.begin(9600)) {
Serial.println("Failed to start Modbus RTU Client!");
while (1);
}
}
void loop() {
readHoldingRegisterValues();
delay(5000);
Serial.println();
}
void readHoldingRegisterValues() {
Serial.print("Reading Holding Register values ... ");
ModbusRTUClient.holdingRegisterRead(0x00, 1);
while (ModbusRTUClient.available()) {
Serial.print(ModbusRTUClient.read());
Serial.print(' ');
}
Serial.println();
}
When I see the serial monitor for client side, I do not read anything. However, if I use this following sketch for the client side:
***************Client sketch 2******************
#include <ArduinoRS485.h>
#include <ArduinoModbus.h>
void setup() {
Serial.begin(9600);
while (!Serial);
// start the Modbus RTU client
if (!ModbusRTUClient.begin(9600)) {
Serial.println("Failed to start Modbus RTU Client!");
while (1);
}
}
void loop() {
readHoldingRegisterValues();
delay(5000);
Serial.println();
}
void readHoldingRegisterValues() {
Serial.print("Reading Holding Register values ... ");
if (!ModbusRTUClient.requestFrom(1, HOLDING_REGISTERS, 0x00, 1)) {
Serial.print("failed! ");
Serial.println(ModbusRTUClient.lastError());
} else {
Serial.println("success");
}
while (ModbusRTUClient.available()) {
Serial.print(ModbusRTUClient.read());
Serial.print(' ');
}
Serial.println();
}
then the serial monitor shows success and the value 100 three times, and then fails with the error timeout one time. Again three times 100 value and then one timeout.
My question is, why can't I read the 100 value with the first sketch of the client but can read with the second sketch, and secondly, why do I have a timeout error after three consecutive successful readings? Looking forward to your assistance. Thank you