CH4-RTC

RTC原理

CubeMX配置

image-20240331235446386
下载线配置
image-20240401000353599
RTC配置
image-20240401000547320
USART配置
image-20240401000655542
USART DMA配置
image-20240401000843198
USER按键中断配置
image-20240401001127070
NVIC配置
image-20240401001317678
时钟树配置

MDK程序编写

使用BIN码

image-20240401004436323
使用BIN码配置

function.c

RTC读取时间函数

==注:时间的读取必须要在日期之前,否则发送的时候会发生错误==

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//RTC系统时间读取函数,从中读取到日期与时间,且时间是在一直增加的
unsigned char *RTC_data(void)//定义一个返回unsigned char指针函数
{
static unsigned char rtc_data_read[7];//创建一包含7个unsigned char变量的静态数组:年,月,星期,日,时,分,秒

extern RTC_HandleTypeDef hrtc;//使用外部结构体RTC

RTC_TimeTypeDef read_time_data;//定义一个结构体时间变量
RTC_DateTypeDef read_date_data;//定义一个结构体日期变量

//必须要在日期之前,否则发送的时候会发生错误
HAL_RTC_GetTime(&hrtc,&read_time_data,RTC_FORMAT_BIN);//时间的读取函数
HAL_RTC_GetDate(&hrtc,&read_date_data,RTC_FORMAT_BIN);//日期的读取函数

//读取日期
rtc_data_read[0]=read_date_data.Year;//年
rtc_data_read[1]=read_date_data.Month;//月
rtc_data_read[2]=read_date_data.WeekDay;//星期
rtc_data_read[3]=read_date_data.Date;//日
//读取时间
rtc_data_read[4]=read_time_data.Hours;//时
rtc_data_read[5]=read_time_data.Minutes;//分
rtc_data_read[6]=read_time_data.Seconds;//秒

return rtc_data_read;//需要返回一个获取的数组,所以需要将该数组定义为静态类型
}

fputc函数

==注:需要使用头文件 #include “stdio.h”==

1
2
3
4
5
6
7
8
9
int fputc(int ch,FILE *f)//重新定义一个fputc函数,就可以直接使用printf函数发送数据
{
extern UART_HandleTypeDef huart2;

HAL_UART_Transmit(&huart2,(uint8_t *)&ch,1,0xffff);//普通串口接收数据
while(__HAL_UART_GET_FLAG(&huart2, UART_FLAG_TC) == RESET){}//等待发送完成

return ch;
}

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include "function.h"
int main(void)
{
extern int flag_send;
unsigned char *receive_rtc;//定义一个数组指针进行读取时间
while(1)
{
receive_rtc=RTC_data();//读取时间函数

printf("\r\n RTC:%d-%d-%d \r\n %d:%d:%d \r\n",2000+receive_rtc[0],receive_rtc[1],receive_rtc[3],receive_rtc[4],receive_rtc[5],receive_rtc[6]);

HAL_Delay(1000);
}
}