Getting Started with STM32F103: UART Receiver in interrupt mode

In the previous guide (here), we took a look at how to receive a character using polling mode. In this guide, we shall use interrupt to receive the data.

In this guide, we shall cover the following:

  • Enable RX in interrupt mode.
  • Interrupt handler.
  • Code.
  • Demo.

1. Enable RX in interrupt mode:

In order to enable the RX in interrupt mode, we need the following two steps:

  • Enable RXNEIE in Control Register 1 (CR1).
  • Enable UART2 interrupt in NVIC.

To enable the RXNEIE for the UART, we need to set the RXNEIE bit in CR1 to 1:

C

Then enable USART2 interrupt in NVIC:

C

Thats all to enable interrupt.

2. Interrupt handler:

Within the interrupt handler, we shall implement the following sequence:

  • Check if the interrupt source is RXNE.
  • If it is, Read the register.
  • Echo back the character.
  • Print new line and return the cursor.
  • Clear the status register.

For the main Interrupt handler, the function as follows:

C

Within the function:

  • Check if the interrupt source is RXNE as following:
C

Read the character:

C

Echo back the character:

C

Print newline and return the cursor:

C

Clear the pending flag:

C

3. Code:

Hence, the entire code as following:

C

4. Demo:

Open you favourite serial terminal and set the buadrate to be 115200 and send any character and you should receive the same sent character:

Happy coding 🙂

Add Comment

Your email address will not be published. Required fields are marked *