Lecture 7 - UART: Universal Asynchronous Read and Write
UART. Lesing av og skriving til serieporten. Forklaring av baudrate.
UART
pass
Exercise: Send data from your board to PC
On the STM32CubeMX
- Launch STM32CubeMX.
- Start a New Project:
- Click File > New Project or click the New Project icon.
- In the Board Selector tab, search for NUCLEO-F767ZI.
- Select the board and click Start Project.
-
Select No when prompted for the default configuration.
- Go to System Core > RCC: Set HSE to Crystal/Ceramic Resonator.
5.Configure UART (USART3)
- In the Pinout & Configuration tab:
- Navigate to Connectivity > USART3.
- Set Mode to
Asynchronous
.
- In the Configuration tab for USART3, set the following Parameter Settings:
- Baud Rate:
115200
(This must match yourplatformio.ini
and code.) - Word Length:
8 Bits (No Parity)
(You may also use8 Bits (+ Parity)
, but for this example,8 Bits (No Parity)
is fine.) - Parity:
None
- Stop Bits:
1
-
Data Direction:
Receive and Transmit
Note: The UART baud rate you set in CubeMX (e.g., 115200) must match the baud rate you use in your serial terminal (such as PuTTY, Tera Term, or PlatformIO Monitor). If they do not match, you will see garbled or no output. You can enable Global Interrupt for
USART3 global interrupt
in the NVIC Settings tab if you plan to use interrupt-driven UART later, but it’s not strictly necessary for this basic example.
- Baud Rate:
- Adjust the clock settings as needed for your board as show in figure.
- Click Project > Generate Code to create your project files.
- Give a good project name and generate code.
On the Platformio
- Inside
platformio.ini
:[env:nucleo_f767zi] platform = ststm32 board = nucleo_f767zi framework = stm32cube build_flags = -IInc upload_protocol = stlink debug_tool = stlink monitor_speed = 115200 ; Set the baud rate for the serial monitor
- Inside
main.c
, between/* USER CODE BEGIN 3 */
uint8_t value = 5; HAL_UART_Transmit(&huart3, &value, 1, HAL_MAX_DELAY); HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin); HAL_Delay(500);
Also observe the Logic analyzer output:
What if we want to send a string data?
const char *message = "Hello world from HAL_UART_Transmit!\r\n";
HAL_UART_Transmit(&huart3, (uint8_t *)message, strlen(message), HAL_MAX_DELAY);
HAL_GPIO_TogglePin(LD1_GPIO_Port, LD1_Pin);
HAL_Delay(500);
After the upload, you should press the socket icon, or Ctrl + Alt + S
to open serial monitor and see this output:
Also observe the Logic analyzer output:
Warning: Pay attention that the type of your data is important. String data is converted into ASCII. When we sent data:5 as integer and observed the binary value of 5. However, if we sent data:5 as string, we wouldn’t see its binary value on the logic analyzer, but it’s ASCII code.
const char *message = "5\n";
HAL_UART_Transmit(&huart3, (uint8_t *)message, strlen(message), HAL_MAX_DELAY);
Exercise: Send data between two boards
pass
Bluetooth exercise
pass (maybe)