serial port
Delay configuration using CubeMX
Turn on serial port interrupt
Clock configuration
Configure a general timer to define delay_us()
timer interrupt
Rewriting of programs in Keil
Create delay_us() function to complete delay us
First add code in user code 1 of the tim.c program
/* USER CODE BEGIN 1 */
void delay_us(uint16_t us)
{
uint16_t differ = 0xffff-us-5;
__HAL_TIM_SET_COUNTER(&htim7,differ); //??TIM7??????
HAL_TIM_Base_Start(&htim7); //?????
while(differ < 0xffff-5){
//??
differ = __HAL_TIM_GET_COUNTER(&htim7); //?????????
}
HAL_TIM_Base_Stop(&htim7);
}
/* USER CODE END 1 */
Add in tim.h header file
void delay_us(uint16_t us);
Test the program
Serial port configuration
For printf redirection in usart.c, two modifications are made to modify USART2 and huart2 according to the serial port number. The following program is an example of USART2
/* USER CODE BEGIN 0 */
uint8_t data_buff[1];
#if 1
#pragma import(__use_no_semihosting)
struct __FILE
{
int handle;
};
FILE __stdout;
void _sys_exit(int x)
{
x = x;
}
int fputc(int ch, FILE *f)
{
while((USART2->SR&0X40)==0);
USART2->DR = (uint8_t) ch;
return ch;
}
#endif
/* USER CODE END 0 */
Enable serial port interrupt
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart);
Add header file in usart.h
Add interrupt permission in main.c function
__HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE);
__HAL_UART_ENABLE_IT(&huart2, UART_IT_TC);
Test serial port ok
to complete universal Cube MX serial port communication
Copyright © 2021 by RichardYang. All rights reserved.
For reference only, reprinting is strictly prohibited, thank you.