Modbus RTU Unable to Write

I am using Modbus lib by Alexander Emelianov on ESP32. I’ve already try Modbus Tcp Server, Client and RTU Slave and it’s works nice. With RTU Master only read works fine, can not write to device. I want to write single reg.



#include <ModbusRTU.h>

// Modbus rtu
ModbusRTU rtu;

//Serial2 pins
#define RXD2 16	//(RX2)
#define TXD2 17	//(TX2)

//Var
const int firstReg = 0;               // Modbus Hreg Offset
const int numOfReg = 120;
uint16_t rtuBuffer[numOfReg];
byte id = 1;


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;
}


// the setup function runs once when you press reset or power the board
void setup() {
	//Serial
	Serial.begin(921600);
	Serial.setTimeout(3);
	Serial2.begin(19200, SERIAL_8N1, RXD2, TXD2);

    //Modbus
	rtu.begin(&Serial2);
    rtu.client();
	rtu.addHreg(firstReg, 0, numOfReg);
	rtu.setBaudrate(19200);
}

// the loop function runs over and over again until power down or reset
void loop() {
	rtu.task();

	if (!rtu.slave()) {
		rtu.readHreg(id, firstReg, rtuBuffer, numOfReg, cb); // Read Hreg from Modbus Slave
		delay(10);
	}
	Serial.printf("Hreg 10: %d, Hreg 11: %d, Hreg 99: %d, Hreg 100: %d\n",
		rtuBuffer[10], rtuBuffer[11], rtuBuffer[99], rtuBuffer[100]);

	if (Serial.available()) {
		int dataIN = Serial.parseInt();
		rtuBuffer[99] = dataIN;
		rtu.Hreg(99, dataIN)
	rtu.writeHreg(id, 99, rtuBuffer, 1); //Send Single Hreg
	}

}

I am not sure is this a proper way to write single reg.

I would look at the library member functions and/or the library examples. After a successfull compile, just select the library name and rt click and click on Goto Definition

In the examples there is just read example.

 uint16_t writeHreg(TYPEID id, uint16_t offset, uint16_t* value, uint16_t numregs = 1, cbTransaction cb = nullptr, uint8_t unit = MODBUSIP_UNIT);

Did you mean about this? I’ve already looked at this, so this sholud be correct I think.

rtu.writeHreg(id, 99, rtuBuffer, 1); //Send Single Hreg

But for some reasons that does’t work.