UART Modbus Read response
Posted: 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:
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:
- uint8_t fByte = (uint8_t)((startReg & 0xFF00) >> 8);
- uint8_t sByte = (uint8_t)(startReg & 0x00FF);
- ESP_LOGD(TAG, "Reading from register %d", startReg);
- uint8_t data[8] = {slave_id, MODBUS_READ_HOLDING_REG, fByte, sByte, 0x00,
- length};
- uint16_t crc = calculateCRC(data, 6);
- data[6] = (uint8_t)(crc & 0x00FF);
- data[7] = (uint8_t)((crc & 0xFF00) >> 8);
- int writeLen = Serial::write(data, 8);
- ESP_LOGV(TAG, "Wrote %d bytes", writeLen);
- //TODO Wait for response here
- size_t dataLength = 0;
- Serial::getBufferedDataLength(&dataLength);
- if (dataLength < 6) {
- return false;
- }
- //Read response