How to Receive Variable-Length Data Over RS485 Using HAL_UART_Receive_IT on STM32F4?
Hello everyone, So I have this custom STM32F4 MCU board and need to receive various data sequences from a Master board over an RS485 network. The lengths of the data sequences are variable, such as 10 bytes, 25 bytes, etc. I need to handle each sequence and respond accordingly.
How can I effectively use the HAL functions
HAL_UART_Receive_IT
and HAL_UART_RxCpltCallback
to properly receive variable-length data?
I noticed that the third argument of HAL_UART_Receive_IT
requires a fixed number of bytes, like this:
Can you suggest a good implementation for this?
The frame format for receiving data is as follows:
Where Byte count
represents the number of bytes from Func. ID
to Checksum byte 2
.Solution:Jump to solution
define the states for your state machine
```c
typedef enum {
RX_STATE_WAIT_FOR_HEADER,
RX_STATE_WAIT_FOR_PAYLOAD...
4 Replies
Hello @Sterling to handle variable-length data sequences, you can use a state machine approach within your
HAL_UART_RxCpltCallback
function. The idea is to first receive the header of the frame which includes the Start byte
, Slave Addr
, and Byte count
. Once you have the Byte count
, you can set up the UART to receive the remaining bytes, let me know if u need code examples to understand it betterVery much @Enthernet Code ... A few code samples would help 🙏
Hey @Sterling something like the should sort you out.
Solution
define the states for your state machine
define buffers and variables to store the received data
Initialize UART reception in the main function
Implement the HAL_UART_RxCpltCallback to handle the reception