Advertisement
dianartanto

connecting modbus tcp with serial communication

Jan 20th, 2025 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 0.96 KB | Source Code | 0 0
  1. #ifdef ESP8266
  2.  #include <ESP8266WiFi.h>
  3. #else //ESP32
  4.  #include <WiFi.h>
  5. #endif
  6. #include <ModbusIP_ESP8266.h>
  7. ModbusIP mb;
  8. int a1 = 0;
  9. int b1 = 0;
  10. void setup() {
  11.   Serial.begin(9600);
  12.   WiFi.begin("SSID", "PASS");//replace with WiFi name & password
  13.   while (WiFi.status() != WL_CONNECTED) {
  14.     delay(500);
  15.     Serial.print(".");
  16.   }
  17.   Serial.println("");
  18.   Serial.println("WiFi connected");
  19.   Serial.println("IP address: ");
  20.   Serial.println(WiFi.localIP());
  21.   mb.server();
  22.   mb.addHreg(0);  //input - i
  23.   mb.addHreg(1);  //color - a
  24.   mb.addHreg(2);  //enum/state - b
  25. }
  26. void loop() {
  27.   mb.task();
  28.   int a = mb.Hreg(1);
  29.   if (a1 != a) {
  30.     Serial.println(a);
  31.     a1 = a;
  32.   }
  33.   int b = mb.Hreg(2);
  34.   if (b != b1) {
  35.     Serial.println(b + 10);
  36.     if (b == 0) a1 = 0;
  37.     b1 = b;
  38.   }
  39. }
  40. void serialEvent() {
  41.   while (Serial.available()) {
  42.     int i = Serial.parseInt();
  43.     if (Serial.read() == char(13)) {
  44.       mb.Hreg(0, i);
  45.     }
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement