Simvik

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 into rx_byte.
  • HAL_UART_RxCpltCallback(huart): runs in the interrupt when the byte has arrived. Put rx_byte into the ring buffer rb (if it already holds RB_SIZE bytes, count the byte in rb_dropped instead), 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 -1 if 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=0

A 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=0

Learn it first

More Working with vendor SDKs and HALs problems