|
在STM32G431内部配置有RTC计时器,将它与OLED屏配合即可实现一个电子时钟。 ; a, ?* ]! \0 u R* V
实现图1所示效果的主程序为: - int main(void)
0 Y* Q, F' {& z9 H - {
; L1 t* F# r8 T) R" y" e' p; L% z( e - /* Reset of all peripherals, Initializes the Flash interface and the Systick. */! N* |; k/ h$ R. X! {, U* ?8 B) g
- HAL_Init();
6 F8 w9 T& h( o( { - /* Configure the system clock */5 s; ^8 M, z7 e8 ~2 ^& i
- SystemClock_Config();+ D9 t3 {! }+ S3 f+ }: N
- GPIO_OLED_INIT();
5 t, ~7 f, N! l7 Q, }; C1 r - OLED_Init();; Q1 p: o0 z# O0 G* ?& D9 b
- OLED_Clear();
2 R' V2 R4 ]9 c - OLED_ShowString(18,0,"STM32G431",16);
- l2 [4 ?7 }) _" q J/ j0 q - OLED_ShowString(10,2,"OLED & RTC",16);3 B" q6 }* }) U! ~, f
- /* Initialize all configured peripherals */8 O4 I; @2 l' B0 t8 ]. [3 w
- MX_RTC_Init();( i# K) A4 Y. j
- RTCStatus = 1;1 U) v8 o% e: Z1 }
- while (1)
' R/ Z# ~; {7 a6 R- \5 b7 ~) i - {
5 `* n7 q& K; }' o M, ? - /* Display the updated Time and Date */6 D* r2 ?7 L Y0 Y1 }
- RTC_CalendarShow(aShowTime, aShowDate);
2 n( k" _( F. p/ e8 a( L# ] - Delay(200);
6 m- W* R% k4 z6 q) q - }
* K3 i+ k2 L* B9 a2 M - }
复制代码 图1 RTC电子时钟
0 ^" {1 e$ y+ p3 W实现RTC显示的函数为: - static void RTC_CalendarShow(uint8_t *showtime, uint8_t *showdate)
1 M% X. Q9 `$ y* _9 P6 m7 s* [ - {; M( { c* q7 `' R
- RTC_DateTypeDef sdatestructureget;
' V6 t* N" v u. C - RTC_TimeTypeDef stimestructureget;+ p4 T% u7 ^% W9 E. _& g
- /* Get the RTC current Time */# e* h; l& W/ m; _# b# k
- HAL_RTC_GetTime(&hrtc, &stimestructureget, RTC_FORMAT_BIN); d7 Y- B( _7 |! U3 ]4 L$ q1 y
- /* Get the RTC current Date *// R2 S1 e0 Q4 V9 ]3 q! ~3 L
- HAL_RTC_GetDate(&hrtc, &sdatestructureget, RTC_FORMAT_BIN);
6 T5 b6 _7 K; V$ p- |3 Y. I. } - /* Display time Format : hh:mm:ss */
: R$ o) {6 x8 W' g - sprintf((char *)showtime, "%2d:%2d:%2d", stimestructureget.Hours, stimestructureget.Minutes, stimestructureget.Seconds);
; a) F$ ]! K- O8 Q; b& D - OLED_ShowString(26,6,showtime,16);: J( b. x$ p1 @
- /* Display date Format : mm-dd-yy *// g: R2 h- ^) i! ~/ C
- sprintf((char *)showdate, "%2d-%2d-%2d", 2000 + sdatestructureget.Year,sdatestructureget.Month, sdatestructureget.Date);& D8 @! u4 m- d
- OLED_ShowString(10,4,showdate,16);
' D1 A8 z6 c) M - }
复制代码
) H- H2 r W/ p( J调用的字符串显示函数为: - void OLED_ShowString(u8 x,u8 y,u8 *chr,u8 Char_Size)
3 X- C3 d- }' T* z - { X2 _* b+ @& g1 f
- unsigned char j=0;
; T. i3 H, l8 x6 {! o0 _ - while (chr[j]!='\0')3 _7 e* f9 H1 ^/ y) q. z
- { OLED_ShowChar(x,y,chr[j],Char_Size);0 ~- B& B% A- C
- x+=8;1 ~3 z4 ]0 V' O+ h$ b2 y; G
- if(x>120){x=0;y+=2;}
( L( H0 Q4 q/ B$ S. L+ s Z1 v" q - j++;
) x2 z7 ^; }9 h - }
- L2 |' ~8 E; \: e - }
复制代码 1 }) q( J6 V( Y, l4 v5 G* v4 v/ t
由于例程所设置的初始时间是2018年,故需要在函数 MX_RTC_Init()中进行修改,修改后的运行效果如图2所示。 4 w5 t; t* e+ G; k6 v: ` `. {+ r! i; c
图2 校时后的显示效果
. C& y" J, w5 A% \) U |
有空我也玩玩。
计时尚可,长时间的误差可能会明显点儿。
就是11月31日会不会自动进入12月1日,还有闰年修正等。9 c, b6 h! U' {+ \5 C6 [
我给你测了下,两者都没有问题。