STM32 UART Part 11: RS485 Reception

Part 2 focuses on receiving data over an RS-485 bus, where correct timing and bus state management are critical for reliable communication.

For demonstration purposes only, the system behavior is to echo back the received data, allowing reception and bus control to be observed and verified easily.

In this guide, we shall cover the following:

  • STM32CubeMX configuration.
  • Firmware development.
  • Results.

1. STM32CubeMX Configuration:

We shall continue from the previous guide here.

Open the RS485 project in STM32CubeMX and select the UART that has been used, for this guide, USART1 has been used.

Enable the interrupt for USART1 from NVIC settings tabs and click on generate project as follows:

This will update the project to make the UART operates in interrupt mode.

Thats all for the STM32CubeMX configuration.

Note: It is possible to use DMA to receive the data. You may apply the steps from here to convert the project from interrupt base to DMA based.

2. Firmware Development:

Open STM32CubeIDE and open main.c source file since the project is already imported to STM32CubeIDE from the previous guide.

First, make sure that while 1 loop is empty as follows:

while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */



  }
  /* USER CODE END 3 */

Since everything is handled in the interrupt ISR.

Next, in user code begin 2 in main function, start the UART to receive data in interrupt mode with IDLE line detection as follows:

HAL_UARTEx_ReceiveToIdle_IT(&huart1, buffer, 20);

In user code begin 0 in main.c file:

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)

{	if(huart->Instance==USART1)
	{
		HAL_UART_Transmit(huart, buffer, Size, 100);

		HAL_UARTEx_ReceiveToIdle_IT(&huart1, buffer, 20);
	}
}

This function will be called either when full 20 characters are received or IDLE line is detected.

Once the function is called, transmit the data that being received and rearm the UART to receive the data in interrupt mode again.

That all for the firmware.

Save, build and run the project as follows:

3. Results:

Using your choice of Serial terminal, send data to the RS485 using RS-485-USB adapter and you should see the data is echoed back.

Here, I am sending the data each 1 second:

This is all for the RS485.

Happy coding 😉

Add Comment

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