UART Modbus Read response

stijnb1234
Posts: 4
Joined: Tue Feb 27, 2024 12:15 pm

UART Modbus Read response

Postby stijnb1234 » Mon Apr 22, 2024 11:37 am

I'm trying to send a 0x03 Read holding registers request as a Modbus master to the listening slaves. What is the best way to send a request (the read request), wait for the response, and then read it? I'm stuck at waiting for the response. Could you please help me further?

I tried a fixed delay, but that's not the best solution. I also tried working with events, but I can't find a stable way.

Example code:
  1. uint8_t fByte = (uint8_t)((startReg & 0xFF00) >> 8);
  2. uint8_t sByte = (uint8_t)(startReg & 0x00FF);
  3.  
  4. ESP_LOGD(TAG, "Reading from register %d", startReg);
  5. uint8_t data[8] = {slave_id, MODBUS_READ_HOLDING_REG, fByte, sByte, 0x00,
  6.                     length};
  7. uint16_t crc = calculateCRC(data, 6);
  8. data[6] = (uint8_t)(crc & 0x00FF);
  9. data[7] = (uint8_t)((crc & 0xFF00) >> 8);
  10. int writeLen = Serial::write(data, 8);
  11. ESP_LOGV(TAG, "Wrote %d bytes", writeLen);
  12.  
  13. //TODO Wait for response here
  14.  
  15. size_t dataLength = 0;
  16. Serial::getBufferedDataLength(&dataLength);
  17. if (dataLength < 6) {
  18.   return false;
  19. }
  20.  
  21. //Read response

ESP_alisitsyn
Posts: 211
Joined: Fri Feb 01, 2019 4:02 pm
Contact:

Re: UART Modbus Read response

Postby ESP_alisitsyn » Wed May 15, 2024 1:35 pm

Hi @stijnb1234,

It is hard to recognize what is the issue on your side. It will be better if you print the sent request and add some additional code.
If you provide your full request in HEX it will be more clear what goes wrong on your side.

For example the read holding registers request and response from slave:
Rx:006574-01 03 00 20 00 04 45 C3
Tx:006575-01 03 08 00 E4 40 46 00 E4 40 46 46 D3

Also, please make sure that your slave is configured correctly to be able to respond to your request.

I think the more simple way for you to read data from your slave is to use esp-modbus component https://github.com/espressif/esp-modbus
Documentation:
https://docs.espressif.com/projects/esp ... est/esp32/

Who is online

Users browsing this forum: Bing [Bot], MicroController and 204 guests