1+ /*
2+ Modbus-Arduino Example - Master (Modbus IP ESP8266/ESP32)
3+ Write multiple coils to Slave device
4+
5+ (c)2019 Alexander Emelianov ([email protected] ) 6+ https://github.com/emelianov/modbus-esp8266
7+ */
8+
9+ #ifdef ESP8266
10+ #include < ESP8266WiFi.h>
11+ #else
12+ #include < WiFi.h>
13+ #endif
14+ #include < ModbusIP_ESP8266.h>
15+
16+ const int REG = 100 ; // Modbus Coils Offset
17+ const int COUNT = 5 ; // Count of Coils
18+ IPAddress remote (192 , 168 , 20 , 102 ); // Address of Modbus Slave device
19+
20+ ModbusIP mb; // ModbusIP object
21+
22+ void setup () {
23+ #ifdef ESP8266
24+ Serial.begin (74880 );
25+ #else
26+ Serial.begin (115200 );
27+ #endif
28+
29+ WiFi.begin ();
30+
31+ while (WiFi.status () != WL_CONNECTED) {
32+ delay (500 );
33+ Serial.print (" ." );
34+ }
35+
36+ Serial.println (" " );
37+ Serial.println (" WiFi connected" );
38+ Serial.println (" IP address: " );
39+ Serial.println (WiFi.localIP ());
40+
41+ mb.master ();
42+ }
43+
44+ bool cb (Modbus::ResultCode event, uint16_t transactionId, void * data) { // Modbus Transaction callback
45+ if (event != Modbus::EX_SUCCESS) // If transaction got an error
46+ Serial.printf (" Modbus result: %02X\n " , event); // Display Modbus error code
47+ if (event == Modbus::EX_TIMEOUT) { // If Transaction timeout took place
48+ mb.disconnect (remote); // Close connection to slave and
49+ mb.dropTransactions (); // Cancel all waiting transactions
50+ }
51+ return true ;
52+ }
53+
54+ bool res[COUNT] = {false , true , false , true , true };
55+
56+ void loop () {
57+ if (!mb.isConnected (remote)) { // Check if connection to Modbus Slave is established
58+ mb.connect (remote); // Try to connect if no connection
59+ Serial.print (" ." );
60+ }
61+ if (!mb.writeCoil (remote, REG, res, COUNT, cb)) // Try to Write array of COUNT of Coils to Modbus Slave
62+ Serial.print (" #" );
63+ mb.task (); // Modbus task
64+ delay (50 ); // Pushing interval
65+ }
0 commit comments