DEV Community

Jack Lin
Jack Lin

Posted on • Edited on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay