DEV Community

Jack Lin
Jack Lin

Posted on • Edited on

Using Uart on Stm32f407g

Environment: windows 10, STM32CubeIDE 1.8.0

In this tutorial we will use uart4 through PA0 and PA1 pins.

Project Initialization

First, add a new stm32f407g project in CubeIDE, and name the project "uart_test".

Image description

In RCC, set High Speed Clock and Low Speed Cock.

Image description

In SYS, set Debug and Timebase Source.

Image description

Set PA0 to UART4_TX and PA1 to UART4_RX.

Image description

Set UART4->Mode to Asynchronous and Baud Rate to 9600 Bits/s.

Image description

Now press Ctrl+S to automatically generate the code.

Test Output String

The wiring of the board is as follows:

Image description

Rewrite the main function of the project's main.c as follows:

int main(void)
{
  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* Configure the system clock */
  SystemClock_Config();

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_UART4_Init();
  /* USER CODE BEGIN 2 */
  char text[13] = "Hello World\r\n";
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    HAL_UART_Transmit(&huart4, text, 13, HAL_MAX_DELAY);
    HAL_Delay(1000);
  }
  /* USER CODE END 3 */
}
Enter fullscreen mode Exit fullscreen mode

Next, execute the program, and it is expected to output a line of "Hello World" every second:

Image description

Print User-Input Strings

Rewrite the while loop as the following, and the screen will output strings entered by users.

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
    uint8_t receive;
    while (HAL_UART_Receive(&huart4, &receive, 1, 1000) != HAL_OK);
    HAL_UART_Transmit(&huart4, &receive, 1, HAL_MAX_DELAY);
    if ((char)receive == '\r')
        HAL_UART_Transmit(&huart4, "\n", 1, HAL_MAX_DELAY);
  }
  /* USER CODE END 3 */
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)