The use of the ESP8266 in the world of IoT

User avatar
By TechShanky
#91961 I am trying to get energy meter data to nodemcu(esp8266) through rs485 modbus rtu. i have written some sample code for the same but not getting the required result. pl help me with the same.

////////
#include <SoftwareSerial.h>

#define RX 2 //Serial Receive pin
#define TX 3 //Serial Transmit pin
#define RTS_pin 9 //RS485 Direction control
#define RS485Transmit HIGH
#define RS485Receive LOW

SoftwareSerial RS485Serial(RX, TX);
unsigned long rate = 60000; // default refresh rate in ms
unsigned long lastMillis = 0;


void setup() {

pinMode(RTS_pin, OUTPUT);

// Start the built-in serial port, for Serial Monitor
Serial.begin(9600);
Serial.println("Energy_meter");

// Start the Modbus serial Port, for Energymeter
RS485Serial.begin(9600);
delay(1000);
}

void loop() {

digitalWrite(RTS_pin, RS485Transmit); // init Transmit
byte Em_request[] = {0x15, 0x03, 0x1B, 0x07, 0x09, 0x0B, 0x19, 0x0F}; // inquiry frame
RS485Serial.write(Em_request, sizeof(Em_request));
RS485Serial.flush();

digitalWrite(RTS_pin, RS485Receive); // Init Receive
byte Em_buf[7];
RS485Serial.readBytes(Em_buf, 7);

Serial.print("PF: ");
for( byte i=0; i<7; i++ ) {
Serial.print(Em_buf[i], HEX);
Serial.print(" ");
}
Serial.print(" ==> ");
Serial.print(int(Em_buf[4]));
Serial.print("");
Serial.println();
delay(100);

}
////////


above is the code