在STM32G431内部配置有RTC计时器,将它与OLED屏配合即可实现一个电子时钟。
实现图1所示效果的主程序为: - int main(void)
- {
- /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
- HAL_Init();
- /* Configure the system clock */
- SystemClock_Config();
- GPIO_OLED_INIT();
- OLED_Init();
- OLED_Clear();
- OLED_ShowString(18,0,"STM32G431",16);
- OLED_ShowString(10,2,"OLED & RTC",16);
- /* Initialize all configured peripherals */
- MX_RTC_Init();
- RTCStatus = 1;
- while (1)
- {
- /* Display the updated Time and Date */
- RTC_CalendarShow(aShowTime, aShowDate);
- Delay(200);
- }
- }
复制代码 图1 RTC电子时钟
实现RTC显示的函数为: - static void RTC_CalendarShow(uint8_t *showtime, uint8_t *showdate)
- {
- RTC_DateTypeDef sdatestructureget;
- RTC_TimeTypeDef stimestructureget;
- /* Get the RTC current Time */
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
- /* Get the RTC current Date */
- HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);
- /* Display time Format : hh:mm:ss */
- sprintf((char *)showtime, "%2d:%2d:%2d", stimestructureget.Hours, stimestructureget.Minutes, stimestructureget.Seconds);
- OLED_ShowString(26,6,showtime,16);
- /* Display date Format : mm-dd-yy */
- sprintf((char *)showdate, "%2d-%2d-%2d", 2000 + sdatestructureget.Year,sdatestructureget.Month, sdatestructureget.Date);
- OLED_ShowString(10,4,showdate,16);
- }
复制代码
调用的字符串显示函数为: - void OLED_ShowString(u8 x,u8 y,u8 *chr,u8 Char_Size)
- {
- unsigned char j=0;
- while (chr[j]!='\0')
- { OLED_ShowChar(x,y,chr[j],Char_Size);
- x+=8;
- if(x>120){x=0;y+=2;}
- j++;
- }
- }
复制代码
由于例程所设置的初始时间是2018年,故需要在函数 MX_RTC_Init()中进行修改,修改后的运行效果如图2所示。
图2 校时后的显示效果
|
有空我也玩玩。
计时尚可,长时间的误差可能会明显点儿。
就是11月31日会不会自动进入12月1日,还有闰年修正等。
我给你测了下,两者都没有问题。