Home Using Uart on Stm32f407g
Post
Cancel

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”.

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

In SYS, set Debug and Timebase Source.

Set PA0 to UART4_TX and PA1 to UART4_RX.

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

Now press Ctrl+S to automatically generate the code.

Test Output String

The wiring of the board is as follows:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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 */
}

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  /* 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 */

This post is licensed under CC BY 4.0 by the author.

Send mail from Outlook using SmtpClient

Fibdrv

Comments powered by Disqus.