|
在STM32G431内部配置有RTC计时器,将它与OLED屏配合即可实现一个电子时钟。 % J7 Z2 O% a y l1 L
实现图1所示效果的主程序为: - int main(void)5 [2 W) r, }2 k% |/ S" l8 H' w
- {
v0 h% c. |& j. b: E' | - /* Reset of all peripherals, Initializes the Flash interface and the Systick. */. _/ Q9 N" ^( ~6 S8 c
- HAL_Init();3 U: D# C4 Z2 b0 M( q! J' [) v
- /* Configure the system clock */ l6 ?9 \- G% D5 Z
- SystemClock_Config();
D3 N8 u! M2 u8 [# D+ a0 N5 N9 i - GPIO_OLED_INIT();
5 x: S7 G7 R5 q$ ? - OLED_Init();# H: U% g7 X! c. O. d
- OLED_Clear();
4 w8 \/ Y% y" J$ I* @: o, e - OLED_ShowString(18,0,"STM32G431",16);; c% a& g6 C) S7 K
- OLED_ShowString(10,2,"OLED & RTC",16);
* o0 W- f& A) \* a+ X - /* Initialize all configured peripherals */
2 o9 R. H. J1 C) } - MX_RTC_Init();3 N5 X+ m3 f! {0 T( x
- RTCStatus = 1;4 s; d- D6 e+ J& Y5 Y6 }
- while (1)
0 ]4 G3 {' ~0 c* b4 ^2 e - {; o% z% Y" p, t6 Q; |
- /* Display the updated Time and Date */
3 X+ t7 {$ [* v9 a8 ~( z% D - RTC_CalendarShow(aShowTime, aShowDate);
3 M& I+ A- v: a/ E9 f v) j. L - Delay(200);! t2 Y" z$ v4 I! o0 ^" I
- }' x) p- Q) O! K
- }
复制代码 图1 RTC电子时钟
& m2 z6 h$ S, Y( H, ^4 y实现RTC显示的函数为: - static void RTC_CalendarShow(uint8_t *showtime, uint8_t *showdate)
% k/ l4 I% M7 O! y# v( g0 P - {! f. T! K5 Y7 E. [' B
- RTC_DateTypeDef sdatestructureget;5 m; A, c+ c% W' T
- RTC_TimeTypeDef stimestructureget;
. c! {' ?! K' K3 k1 ^1 }8 B+ a' x - /* Get the RTC current Time */+ B Y" E' j4 E# h; P
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN);
( |" M# D# K4 O; s' n0 n - /* Get the RTC current Date */
9 n% R$ C3 [* Z0 K+ m( ]% h - HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);% v6 U1 ]/ e$ v: C
- /* Display time Format : hh:mm:ss */1 Q q6 e2 F( y6 T0 b
- sprintf((char *)showtime, "%2d:%2d:%2d", stimestructureget.Hours, stimestructureget.Minutes, stimestructureget.Seconds);
: }8 P" t4 d1 }% B: G/ Q" ~ - OLED_ShowString(26,6,showtime,16);
- M, c( g" C9 b! a: ? - /* Display date Format : mm-dd-yy */' b( D* s* l; V$ F; N
- sprintf((char *)showdate, "%2d-%2d-%2d", 2000 + sdatestructureget.Year,sdatestructureget.Month, sdatestructureget.Date);
% T1 H* [' M7 _+ [ - OLED_ShowString(10,4,showdate,16);
& `7 T8 G9 ]2 A - }
复制代码
4 A( y' Y/ T4 X1 u* D: _调用的字符串显示函数为: - void OLED_ShowString(u8 x,u8 y,u8 *chr,u8 Char_Size)/ X& I. {+ A* j/ W
- {
" G/ b# U8 t% Q& Z! U/ p - unsigned char j=0;' |( }" b; Y# q
- while (chr[j]!='\0'): t1 I0 ]3 l: Q+ i
- { OLED_ShowChar(x,y,chr[j],Char_Size);7 P7 E" O) r4 h$ H5 t2 x$ a
- x+=8;
/ m$ F C- s7 J" u0 z6 r6 F - if(x>120){x=0;y+=2;}* m0 d$ N+ C5 W, l1 s" s1 U3 X2 v
- j++;
3 K% S6 z/ I4 W3 ^2 v - }+ K0 w+ P; f/ O0 j6 } K* J: ]2 Y
- }
复制代码 7 P, j6 t! \6 T) l1 x
由于例程所设置的初始时间是2018年,故需要在函数 MX_RTC_Init()中进行修改,修改后的运行效果如图2所示。
# o& v% N% ?# ` O c图2 校时后的显示效果 * n0 J8 }' \% y5 |, s
|
有空我也玩玩。
计时尚可,长时间的误差可能会明显点儿。
就是11月31日会不会自动进入12月1日,还有闰年修正等。
我给你测了下,两者都没有问题。