【stm32】hal库学习笔记-UART/USART串口通信
hal库驱动函数
CubeMX图形化配置
导入LCD.ioc
RTC设置
时钟树配置
设置LSE为RTC时钟源
USART设置
中断设置
程序编写
编写主函数
c
/* 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中重写回调函数
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文件中编写定义
c
/* 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
c
/* USER CODE BEGIN 0 */
#include "rtc.h"
#include "lcd.h"
#include <string.h>
uint8_t proBuffer[10] = "#S45;\n";
uint8_t rxBuffer[10] = "#H12;\n";
uint8_t rxCompleted = RESET;
uint8_t isUploadTime = 1;
/* USER CODE END 0 */
c
/* USER CODE BEGIN 1 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
if (huart->Instance == USART1) {
rxCompleted = SET;
for (uint16_t i = 0; i < RX_CMD_LEN; i++) {
proBuffer[i] = rxBuffer[i];
__HAL_UART_ENABLE_IT(huart, UART_IT_IDLE);
}
}
}
void on_UART_IDLE(UART_HandleTypeDef *huart) {
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_IDLE) == RESET) {
return;
}
__HAL_UART_CLEAR_IDLEFLAG(huart);
__HAL_UART_DISABLE_IT(huart, UART_IT_IDLE);
if (rxCompleted) {
HAL_UART_Transmit(huart, proBuffer, strlen(proBuffer), 100);
HAL_Delay(10);
updateRTCTime();
lcd_show_str(30, 110, 16, proBuffer, BLACK);
rxCompleted = RESET;
HAL_UART_Receive_IT(huart, rxBuffer, RX_CMD_LEN);
}
}
void updateRTCTime() {
if (proBuffer[0] != '#') {
return;
}
uint8_t timeSection = proBuffer[1];
uint8_t temp10 = proBuffer[2] - '0';
uint8_t temp1 = proBuffer[3] - '0';
uint8_t value = 10 * temp10 + temp1;
if (timeSection == 'U') {
isUploadTime = value;
return;
}
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);
sTime.DayLightSaving = 0;
sTime.StoreOperation = 0;
if (timeSection == 'H') {
sTime.Hours = value;
} else if (timeSection == 'M') {
sTime.Minutes = value;
} else if (timeSection == 'S') {
sTime.Seconds = value;
}
HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN);
}
}
/* USER CODE END 1 */
实现效果