【stm32】hal库学习笔记-UART/USART串口通信(超详细!)
【stm32】hal库学习笔记-UART/USART串口通信
hal库驱动函数
CubeMX图形化配置
导入LCD.ioc
RTC设置
时钟树配置
设置LSE为RTC时钟源
程序编写
编写主函数
/* USER CODE BEGIN 2 */ lcd_init(); lcd_show_str(10, 10, 16, "Demo12_1:USART1-CH340", RED); lcd_show_str(10, 30, 16, "Please connect board with PC", RED); lcd_show_str(10, 50, 16, "via MiniUSB line before power on", RED); uint8_t hello1[] = "Hello, blocking\n"; HAL_UART_Transmit(&huart1, hello1, sizeof(hello1), 500); HAL_Delay(10); uint8_t hello2[] = "Hello, none blocking\n"; HAL_UART_Transmit_IT(&huart1, hello2, sizeof(hello2)); lcd_show_str(10, 90, 16, "Received command string is: ", RED); HAL_UART_Receive_IT(&huart1, rxBuffer, RX_CMD_LEN); /* USER CODE END 2 */
在rtc.c中重写回调函数
/* USER CODE BEGIN 1 */ void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc) { RTC_TimeTypeDef sTime; RTC_DateTypeDef sDate; if (HAL_RTC_GetTime(hrtc, &sTime, RTC_FORMAT_BIN) == HAL_OK) { HAL_RTC_GetDate(hrtc, &sDate, RTC_FORMAT_BIN); uint8_t timeStr[20]; sprintf(timeStr, "%2d:%2d:%2d\n", sTime.Hours, sTime.Minutes, sTime.Seconds); lcd_show_str(30, 70, 16, timeStr, BLACK); if (isUploadTime) { HAL_UART_Transmit(&huart1, timeStr, strlen(timeStr), 200); } } } /* USER CODE END 1 */
在usart.h文件中编写定义
/* USER CODE BEGIN Private defines */ #define RX_CMD_LEN 5 extern uint8_t rxBuffer[]; extern uint8_t isUploadTime; /* USER CODE END Private defines */
编写usart.c
/* USER CODE BEGIN 0 */ #include "rtc.h" #include "lcd.h" #include uint8_t proBuffer[10] = "#S45;\n"; uint8_t rxBuffer[10] = "#H12;\n"; uint8_t rxCompleted = RESET; uint8_t isUploadTime = 1; /* USER CODE END 0 */
/* USER CODE BEGIN 1 */ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { if (huart->Instance == USART1) { rxCompleted = SET; for (uint16_t i = 0; i实现效果
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。