Enthernet Code
Enthernet Code
DIIDevHeads IoT Integration Server
Created by Sterling on 8/6/2024 in #firmware-and-baremetal
How to Receive Variable-Length Data Over RS485 Using HAL_UART_Receive_IT on STM32F4?
define the states for your state machine
typedef enum {
RX_STATE_WAIT_FOR_HEADER,
RX_STATE_WAIT_FOR_PAYLOAD
} RxState;

RxState rx_state = RX_STATE_WAIT_FOR_HEADER;
typedef enum {
RX_STATE_WAIT_FOR_HEADER,
RX_STATE_WAIT_FOR_PAYLOAD
} RxState;

RxState rx_state = RX_STATE_WAIT_FOR_HEADER;
define buffers and variables to store the received data
#define HEADER_SIZE

uint8_t uart_rx_header[HEADER_SIZE];
uint8_t uart_rx_payload[256];
uint8_t uart_rx_byte;
uint8_t byte_count = 0;
#define HEADER_SIZE

uint8_t uart_rx_header[HEADER_SIZE];
uint8_t uart_rx_payload[256];
uint8_t uart_rx_byte;
uint8_t byte_count = 0;
Initialize UART reception in the main function
HAL_UART_Receive_IT(&huart1, &uart_rx_byte, 1);
HAL_UART_Receive_IT(&huart1, &uart_rx_byte, 1);
Implement the HAL_UART_RxCpltCallback to handle the reception
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
static uint8_t header_index = 0;
static uint8_t payload_index = 0;

if (huart->Instance == USART1) {
switch (rx_state) {
case RX_STATE_WAIT_FOR_HEADER:
uart_rx_header[header_index++] = uart_rx_byte;

if (header_index == HEADER_SIZE) {
byte_count = uart_rx_header[2];
rx_state = RX_STATE_WAIT_FOR_PAYLOAD;
header_index = 0;
payload_index = 0;

HAL_UART_Receive_IT(huart, uart_rx_payload, byte_count + 2);
} else {
HAL_UART_Receive_IT(huart, &uart_rx_byte, 1);
}
break;

case RX_STATE_WAIT_FOR_PAYLOAD;

rx_state = RX_STATE_WAIT_FOR_HEADER;
HAL_UART_Receive_IT(huart, &uart_rx_byte, 1);
break;
}
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
static uint8_t header_index = 0;
static uint8_t payload_index = 0;

if (huart->Instance == USART1) {
switch (rx_state) {
case RX_STATE_WAIT_FOR_HEADER:
uart_rx_header[header_index++] = uart_rx_byte;

if (header_index == HEADER_SIZE) {
byte_count = uart_rx_header[2];
rx_state = RX_STATE_WAIT_FOR_PAYLOAD;
header_index = 0;
payload_index = 0;

HAL_UART_Receive_IT(huart, uart_rx_payload, byte_count + 2);
} else {
HAL_UART_Receive_IT(huart, &uart_rx_byte, 1);
}
break;

case RX_STATE_WAIT_FOR_PAYLOAD;

rx_state = RX_STATE_WAIT_FOR_HEADER;
HAL_UART_Receive_IT(huart, &uart_rx_byte, 1);
break;
}
}
}
6 replies