Receive with the HAL's interrupt API
Keep a console receiving by re-arming the HAL in its callbacks, and buffer the bytes for the main loop. A medium embedded C problem (Working with vendor SDKs…
medium · Working with vendor SDKs and HALs · hal · uart · callbacks · ring-buffer · isr
A console reads characters with the HAL's interrupt API, one byte at a time. Write the four pieces:
console_start(): arm the first reception of one byte intorx_byte.HAL_UART_RxCpltCallback(huart): runs in the interrupt when the byte has arrived. Putrx_byteinto the ring bufferrb(if it already holdsRB_SIZEbytes, count the byte inrb_droppedinstead), then arm the next reception.HAL_UART_ErrorCallback(huart): runs in the interrupt after a receive error, which the HAL has already counted. Arm reception again so the console keeps working.console_getc(): called by the main loop. Return the oldest buffered byte, or-1if there is none.
rb_head and rb_tail are free-running 8-bit counters: the slot is the counter modulo RB_SIZE, and the number of bytes waiting is (uint8_t)(rb_head - rb_tail).
Starter code
void console_start(void) {
HAL_UART_Receive_IT(&huart2, &rx_byte, 1);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
rb[rb_head % RB_SIZE] = rx_byte;
rb_head++;
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) {
}
int console_getc(void) {
if (rb_head == rb_tail) return -1;
return rb[rb_tail++ % RB_SIZE];
}Example tests
A typed command
console_start();
wire_rx("help");
read_all();Expected output:
read "help" lost=0 dropped=0A receive error in the middle of a line
console_start();
wire_rx("ab");
wire_error();
wire_rx("cd");
read_all();Expected output:
read "abcd" lost=0 dropped=0Learn it first
- Working with vendor SDKs and HALs · SDK layers, generated code, HAL handles, status codes and callbacks, and when to go below the HAL.
More Working with vendor SDKs and HALs problems
- Fix: the LED pin never changes · GPIO register writes are ignored because the port's clock was never switched on.