在STM32G431内部配置有RTC计时器,将它与OLED屏配合即可实现一个电子时钟。 , z$ w% r& j8 }
实现图1所示效果的主程序为: - int main(void)
- k! }" B: w9 H% ~ - {
+ _7 L+ o: q) A* ], f - /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
7 u) g" \+ E; ? - HAL_Init();$ h; m; D" ^# j% U+ k* [7 b
- /* Configure the system clock */
* \; u* _3 H }2 C5 I - SystemClock_Config();
% C8 T5 I$ k* f3 P/ O; K - GPIO_OLED_INIT();
0 y, r* n. n" u3 I# r - OLED_Init();
$ \/ w) W2 n1 I# O - OLED_Clear();
. G, _0 Q- P0 F% r" @; _ - OLED_ShowString(18,0,"STM32G431",16);
$ i+ ]3 d$ s& r+ U: g - OLED_ShowString(10,2,"OLED & RTC",16); Y: \$ f! z; h1 A2 n' i
- /* Initialize all configured peripherals */5 R! T' j2 i5 b, H* X
- MX_RTC_Init();
# f/ V5 l& S; [6 v8 x T9 R; D1 W - RTCStatus = 1;% |$ L! |4 o Z9 N! r3 l
- while (1)
' y3 N# N& M8 L9 e% l - {8 }; d& h: ], M2 |5 p; T
- /* Display the updated Time and Date */) }3 V( s4 @+ X- Q8 v
- RTC_CalendarShow(aShowTime, aShowDate);" x( B1 J! x( Z$ O9 ?# j
- Delay(200);0 X) s9 n/ C Q! p# o) T2 D2 t
- }3 O4 q2 w6 Z1 b" {& Q# N1 y
- }
复制代码 图1 RTC电子时钟 : A- r/ m' m, p
实现RTC显示的函数为: - static void RTC_CalendarShow(uint8_t *showtime, uint8_t *showdate)
A5 t- x, D$ T - {% Y2 y Y- [; Q2 L
- RTC_DateTypeDef sdatestructureget;; W- [5 a6 |+ z# }2 W. W0 j+ T
- RTC_TimeTypeDef stimestructureget;
/ _/ ^* \- O$ V P - /* Get the RTC current Time */# s- K8 \4 f. O6 H" S0 t- q1 P
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
; S Z+ w( D8 @! C& ]& U - /* Get the RTC current Date */
+ ~+ t- j; N( j H& P3 Y, h9 ^8 | - HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);
8 d0 t8 E0 V* d4 j1 c4 P - /* Display time Format : hh:mm:ss */8 q) H2 t* n7 e+ V
- sprintf((char *)showtime, "%2d:%2d:%2d", stimestructureget.Hours, stimestructureget.Minutes, stimestructureget.Seconds);+ a1 u' Z' y! d& a2 @
- OLED_ShowString(26,6,showtime,16);4 \, w! m D$ g6 a& e9 p, y
- /* Display date Format : mm-dd-yy */
" ]: q& T& N& O6 a; G; M4 Z: c - sprintf((char *)showdate, "%2d-%2d-%2d", 2000 + sdatestructureget.Year,sdatestructureget.Month, sdatestructureget.Date);% t( z. _$ |9 ]6 T* M: {: L$ O3 O x- D
- OLED_ShowString(10,4,showdate,16);
7 f. E# ?3 Y" R - }
复制代码 / S% G' ` ~' W% b- I5 u
调用的字符串显示函数为: - void OLED_ShowString(u8 x,u8 y,u8 *chr,u8 Char_Size)
0 u- g4 V* u, F2 I - {
6 y8 b/ U: i0 d5 F2 ]* ^1 C - unsigned char j=0;6 z! }* m. G- o B7 F9 k
- while (chr[j]!='\0')4 p, E3 ^; ^8 Z) e, H, y4 O
- { OLED_ShowChar(x,y,chr[j],Char_Size);
& t& ]5 l9 }4 U5 ^8 A* n' V: H - x+=8;
5 \8 H! f6 R E( n8 z, k - if(x>120){x=0;y+=2;}- u9 l) S& d0 y) a" t
- j++;
0 a) k$ ?$ h0 U, p/ |, g) r - }& b# z: ?! u4 c* f6 q
- }
复制代码
+ h1 A8 F" c1 _3 U$ j7 r由于例程所设置的初始时间是2018年,故需要在函数 MX_RTC_Init()中进行修改,修改后的运行效果如图2所示。 " K* |, K5 s: Q! z! V2 ?1 `
图2 校时后的显示效果 : a. z/ \, A$ A+ m2 l
|
有空我也玩玩。
计时尚可,长时间的误差可能会明显点儿。
就是11月31日会不会自动进入12月1日,还有闰年修正等。
我给你测了下,两者都没有问题。