"UART" In STM32, UART Receive (Rx) is managed through an interrupt-based mechanism (HAL_UART_Receive_IT) to receive data asynchronously, storing incoming bytes in buffer without blocking the CPU. The HAL_UART_RxCpltCallbackis executed when a UART receive interrupt occurs for the specified *huart.
Transmit (Tx) functionality in STM32 UART also operates on the same interrupt-driven principle as receive (Rx).
4. Setup
9600 Baudrate UART 설정Interrupt 설정
5. Code Review
UART_HandleTypeDef huart2;
HAL_UART_Receive_IT(&huart2, &rx_data, 1); // UART 인터럽트 시작 구현, uart로 받은 데이터를 rx_data로 저장
Initializes the UART interrupt reception, configuring huart2 to store received UART data into the variable rx_data one byte at a time.
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) // UART Call Back 함수 구현.
{
volatile static int i = 0;
if(huart == &huart2)
{
uint8_t data;
data = rx_data;
if(data == '\n')
{
rx_buffer[rear][i++] = '\0'; // strncpy 사용 시, 문자열의 끝은 NULL이여야 복사가 가능하기 때문에 NULL 문자를 끝에 추가해준다.
i = 0;
rear++;
rear %= COMMAND_NUMBER;
}
else
{
rx_buffer[rear][i++] = data;
}
}
HAL_UART_Receive_IT(&huart2, &rx_data, 1); // UART2의 다음 Interrupt를 받기 위해 해당 함수를 실행한다.
}
UART receive callback function, HAL_UART_RxCpltCallback, which is triggered upon receiving data via UART. It processes incoming data into a circular buffer (rx_buffer) and re-enables the interrupt to continue receiving subsequent data.
** UART 송신시 일반적으로 \n, \0, \r, 또는 특정 종료 코드가 사용된다. 이 코드에서는 \n을 감지하여 데이터 송신이 끝난 것을 확인함!
pc_command_processing, checks for new commands in the circular buffer (rx_buffer) and parses them using string comparison. Based on the command, it sets func_index to the corresponding function index for execution.