eModbus / eModbus

Modbus library for RTU, ASCII and TCP protocols. Primarily developed on and for ESP32 MCUs.

Home Page:https://emodbus.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Some problem with this sketch

carminelau opened this issue · comments

`#include "ModbusClientRTU.h"

//ModbusClientRTU RS485(); // for auto half-duplex
ModbusClientRTU RS485(5); // use rtsPin to toggle DE/RE in half-duplex

void handleData(ModbusMessage msg, uint32_t token)
{
Serial.printf("Response: serverID=%d, FC=%d, Token=%08X, length=%d:\n", msg.getServerID(), msg.getFunctionCode(), token, msg.size());
for (auto& byte : msg) {
Serial.printf("%02X ", byte);
}
Serial.println("");
}

void handleError(Error error, uint32_t token)
{
// ModbusError wraps the error code and provides a readable error message for it
ModbusError me(error);
Serial.printf("Error response: %02X - %s\n", error, (const char *)me);
}

void setup() {
Serial.begin(9600);
// Set up Serial2 connected to Modbus RTU
RTUutils::prepareHardwareSerial(Serial1);
Serial1.begin(9600, SERIAL_8E1, 7, 6);

// Set up ModbusClientRTU client.
// - provide onData and onError handler functions
RS485.onDataHandler(&handleData);
RS485.onErrorHandler(&handleError);

// Start ModbusClientRTU background task
RS485.begin(Serial1);
}

void loop(){
Error err = RS485.addRequest(0x12345678, 1, READ_HOLD_REGISTER, 0, 1);
if (err!=SUCCESS) {
ModbusError e(err);
Serial.printf("Error creating request: %02X - %s\n", err, (const char *)e);
}

delay(10000);

}
`

My problem is that I always get these messages:
Error response: E5 - Packet length error
Error response: E2 - CRC check error

how i can resolve it ?