Skip to content

Commit 4be4d04

Browse files
committed
Add example for RTU with RS485 parameters
1 parent baacd3a commit 4be4d04

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/*
2+
Modbus RTU Client Parameters
3+
4+
This sketch is the same as ModbusRTUClientToggle and shows how to set
5+
a few RS485 parameters.
6+
7+
Circuit:
8+
- Arduino Opta
9+
- GND connected to GND of the Modbus RTU server
10+
- A(-) connected to A of the Modbus RTU server
11+
- B(+) connected to B of the Modbus RTU server
12+
*/
13+
14+
#include <ArduinoRS485.h> // ArduinoModbus depends on the ArduinoRS485 library
15+
#include <ArduinoModbus.h>
16+
17+
constexpr auto baudrate { 19200 };
18+
19+
// Calculate preDelay and postDelay in microseconds as per Modbus RTU Specification
20+
//
21+
// MODBUS over serial line specification and implementation guide V1.02
22+
// Paragraph 2.5.1.1 MODBUS Message RTU Framing
23+
// https://modbus.org/docs/Modbus_over_serial_line_V1_02.pdf
24+
constexpr auto bitduration { 1.f / baudrate };
25+
constexpr auto wordlen { 9.6f }; // try also with 10.0f
26+
constexpr auto preDelayBR { bitduration * wordlen * 3.5f * 1e6 };
27+
constexpr auto postDelayBR { bitduration * wordlen * 3.5f * 1e6 };
28+
29+
void setup() {
30+
Serial.begin(9600);
31+
while (!Serial);
32+
33+
Serial.println("Modbus RTU Client Toggle w/ Parameters");
34+
35+
RS485.setDelays(preDelayBR, postDelayBR);
36+
37+
// start the Modbus RTU client in 8E1 mode
38+
if (!ModbusRTUClient.begin(baudrate, SERIAL_8E1)) {
39+
Serial.println("Failed to start Modbus RTU Client!");
40+
while (1);
41+
}
42+
}
43+
44+
void loop() {
45+
// for (slave) id 1: write the value of 0x01, to the coil at address 0x00
46+
if (!ModbusRTUClient.coilWrite(1, 0x00, 0x01)) {
47+
Serial.print("Failed to write coil! ");
48+
Serial.println(ModbusRTUClient.lastError());
49+
}
50+
51+
// wait for 0.5 second
52+
delay(500);
53+
54+
// for (slave) id 1: write the value of 0x00, to the coil at address 0x00
55+
if (!ModbusRTUClient.coilWrite(1, 0x00, 0x00)) {
56+
Serial.print("Failed to write coil! ");
57+
Serial.println(ModbusRTUClient.lastError());
58+
}
59+
60+
// wait for 0.5 second
61+
delay(500);
62+
63+
auto coil = ModbusRTUClient.coilRead(0x02, 0x00);
64+
65+
if (coil < 0) {
66+
Serial.print("Failed to read coil: ");
67+
Serial.println(ModbusRTUClient.lastError());
68+
} else {
69+
Serial.print("Coil: ");
70+
Serial.println(coil);
71+
}
72+
73+
// wait for 0.5 second
74+
delay(500);
75+
}

0 commit comments

Comments
 (0)