forked from emelianov/modbus-esp8266
-
Notifications
You must be signed in to change notification settings - Fork 0
/
masterSync.ino
47 lines (40 loc) · 1.09 KB
/
masterSync.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
Modbus Library for Arduino Example - Modbus RTU Client
Read Holding Registers from Modbus RTU Server in blocking way
ESP8266 Example
(c)2020 Alexander Emelianov ([email protected])
https://github.com/emelianov/modbus-esp8266
*/
#include <ModbusRTU.h>
#include <SoftwareSerial.h>
#define SLAVE_ID 1
#define FIRST_REG 0
#define REG_COUNT 2
SoftwareSerial S(D2, D1);
ModbusRTU mb;
bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) { // Callback to monitor errors
if (event != Modbus::EX_SUCCESS) {
Serial.print("Request result: 0x");
Serial.print(event, HEX);
}
return true;
}
void setup() {
Serial.begin(115200);
S.begin(9600, SWSERIAL_8N1);
mb.begin(&S);
mb.master();
}
void loop() {
uint16_t res[REG_COUNT];
if (!mb.slave()) { // Check if no transaction in progress
mb.readHreg(SLAVE_ID, FIRST_REG, res, REG_COUNT, cb); // Send Read Hreg from Modbus Server
while(mb.slave()) { // Check if transaction is active
mb.task();
delay(10);
}
Serial.println(res[0]);
Serial.println(res[1]);
}
delay(1000);
}