Fix: Fixed a reading bug in MODBUS-RTU when using DMA #105
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Subject: fix(rtu): Correct flush implementation for DMA transport layer
OverviewThis PR fixes a bug in the DMA-based RTU transport layer where the flush() operation was ineffective.
The original read_serial function in nanomodbus_config.c did not properly handle a zero-timeout call, which is used by the core library to flush the receive buffer. This failure to clear the buffer makes the Modbus client susceptible to spurious data or late responses on the bus, leading to incorrect errors such as NMBS_ERROR_INVALID_UNIT_ID even when the physical communication is successful.
Steps to Reproduce
Environment: Configure nanomodbus as an RTU client on an MCU using FreeRTOS. Use the DMA-based transport layer implementation for read_serial that relies on a FreeRTOS queue (rtu_rx_q) populated by a UART ReceiveToIdle_DMA interrupt.
A special case has been added at the beginning of the function. If byte_timeout_ms is 0, the call is identified as a flush request. Instead of attempting to read from the queue, the function now calls xQueueReset(rtu_rx_q).
This ensures that any flush() call reliably and instantly discards all pending data in the receive queue, guaranteeing that each new Modbus transaction begins with a clean state. This makes the client robust against noise and synchronization issues common in physical environments.
Test ResultsThis fix was validated on physical hardware. No formal unit tests were written.
Before Fix: When polling a physical slave device in an environment with typical electrical noise, the application frequently reported NMBS_ERROR_INVALID_UNIT_ID. A logic analyzer confirmed that the frames on the bus were largely correct, but spurious data was present between transactions.
None.