We are using Modbus implementation and we got the library on Arduino IDE for Reading the slave register but we are unable to write to slave register using that library.
Meanwhile we are also trying and written one code which reads the data successfully, write operation does not generate any error but it doesn’t write into slave register.
i am attaching the library link that we are using currently and the modified code.
Master - ESP32
Slave - Energy meter
Modified Code
#include <ModbusRTU.h>
ModbusRTU mb;
//#include <SoftwareSerial.h>
int DE_RE = 4; //D4 For MAX485 chip
#define RXPIN GPIO_NUM_16
#define TXPIN GPIO_NUM_17
#include "IntToFloat.h"
//SoftwareSerial S(RX, TX);//D6/D7 (RX , TX)
uint16_t Mread0[2];
bool cbWrite(Modbus::ResultCode event, uint16_t transactionId, void* data) {
Serial.printf_P("Request result: 0x%02X, Mem: %d\n", event, ESP.getFreeHeap());
return true;
}
void setup() {
Serial.begin(115200);
Serial2.begin(9600, SERIAL_8N2, RXPIN, TXPIN);
mb.begin(& Serial2, DE_RE); //Assing Software serial port to Modbus instance for MAX485 chip having DI,DE,RE,RO Pin at TTL side
mb.master(); //Assing Modbus function as master
Serial.println(); //Print empty line
Serial.println(sizeof(Mread0)); //Reaing size of first array
}
void loop() {
if (!mb.slave()) {
mb.readHreg(12, 0x0020, Mread0, 4 , cbWrite); //(SlaevID,Address,Buffer,Range of data,Modus call)
Serial.println(InttoFloat(Mread0[0], Mread0[1]));
}
mb.task();
delay(1000);
yield();
}
Header file
float InttoFloat(uint16_t Data0,uint16_t Data1) {
float x;
unsigned long *p;
p = (unsigned long*)&x;
*p = (unsigned long)Data0 << 16 | Data1; //Big-endian
return(x);
}