CubeMX配置
这里只点了屏幕需要的三个脚。
引脚
激活时钟源和日历
RTC实时时钟相关的结构体
stm32l0xx_hal_rtc.h:
/**
* @brief RTC_TimeTypeDef 结构体
*/
typedef struct
{
uint8_t Hours;
uint8_t Minutes;
uint8_t Seconds;
uint8_t TimeFormat;
uint32_t SubSeconds;
uint32_t SecondFraction;
uint32_t DayLightSaving;
uint32_t StoreOperation;
} RTC_TimeTypeDef;
/**
* @brief RTC_DateTypeDef 结构体
*/
typedef struct
{
uint8_t WeekDay;
uint8_t Month;
uint8_t Date;
uint8_t Year;
} RTC_DateTypeDef;
用户代码
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_RTC_Init();
/* USER CODE BEGIN 2 */
OLED_PowerControl(ENABLE);
HAL_Delay(200);
OLED_Init();
OLED_Clear();
OLED_ShowString(0, 0, (unsigned char *)" ", 16);
OLED_ShowString(0, 2, (unsigned char *)" ", 16);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
RTC_TimeTypeDef NowTime;//时间类型的结构体定义
RTC_DateTypeDef NowDate;//日期类型的结构体定义
char lcdLine_1st_line[16];
char lcdLine_2nd_line[16];
//获取预设的时间
HAL_RTC_GetTime(&hrtc, &NowTime, RTC_FORMAT_BIN);
//获取预设的日期
HAL_RTC_GetDate(&hrtc, &NowDate, RTC_FORMAT_BIN);
//格式化并显示在OLED上。
sprintf(lcdLine_1st_line, "%d - %d - %d ", NowDate.Year, NowDate.Month, NowDate.Date);
sprintf(lcdLine_2nd_line, "%d : %d : %d ", NowTime.Hours, NowTime.Minutes, NowTime.Seconds);
OLED_ShowString(0, 0, (unsigned char *)lcdLine_1st_line, 16);
OLED_ShowString(0, 2, (unsigned char *)lcdLine_2nd_line, 16);
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}