有些MCU没有RTC,可以通过此方法,用定时器实现RTC。
=========================================================================
1.mktime函数实现北京时间转UNIX时间戳
volatile time_t g_uiUNIX_TimeStamp; //定时器中断每1秒加1
/** CLOCK initialization structure. */
typedef struct
{
struct tm startDate; /**< Date when RTC was started */ //tm定义参考“time.h”
uint32_t rtcCountsPerSec; /**< RTC count frequency [Hz]*/
} Clock_Init_TypeDef;
/** Suggested default config for Clock init structure. */
#define CLOCK_INIT_DEFAULT \
{ \
CLOCK_DEFAULT_START_DATE, /* Use default start date */ \
32768 /* RTC frequency is 32.768 kHz */ \
}
bool RTC_Time_Updata(void)
{
Clock_Init_TypeDef initialCalendar = CLOCK_INIT_DEFAULT;
initialCalendar.startDate.tm_sec = 50; //50秒
initialCalendar.startDate.tm_min = 59; //59分
initialCalendar.startDate.tm_hour = 23; //23点
initialCalendar.startDate.tm_mday = 9; //9日
initialCalendar.startDate.tm_mon = 2 - 1; //2月
initialCalendar.startDate.tm_year = 2022-1900; //2022年
clockInit(&initialCalendar);
g_uiUNIX_TimeStamp -= 28800;
return true;
}
void clockInit(Clock_Init_TypeDef *init)
{
clockSetStartCalendar(&init->startDate);
}
void clockSetStartCalendar(struct tm *timeptr)
{
g_uiUNIX_TimeStamp = mktime(timeptr);
}
=========================================================================
2.localtime函数实现UNIX时间戳转北京时间
volatile struct tm g_tmCalendar;
void IR_Tx_Time(void)
{
time_t timeStamp = g_uiUNIX_TimeStamp + 28800;
RTC_Calendar_Get( &timeStamp );
IR_Tx_Unix_TimeStamp();
}
void RTC_Calendar_Get(time_t *t)
{
/* Read out system time if input parameter = NULL */
if( t == NULL )
{
time_t currentTime = time( NULL );
t = ¤tTime;
}
/* Make calendar from unix time */
g_tmCalendar = * localtime( t );
}
void IR_Tx_Unix_TimeStamp(void)
{//红外头打印输出北京时间
IR_Init();
IR_Tx_Add_S("20,");
IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_year-100)));
IR_Tx_Add_S("-");
IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_mon+1)));
IR_Tx_Add_S("-");
IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_mday)));
IR_Tx_Add_S(" ");
//IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_hour+8)));
IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_hour)));
IR_Tx_Add_S(":");
IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_min)));
IR_Tx_Add_S(":");
IR_Tx_Byte_Hex2Asc(Dec2bit_Add_0x_To_Hex((uint8)(g_tmCalendar.tm_sec)));
IR_Tx_Add_S("\r\n\r\n");
IR_Tx_Wait_Dn();
}
=========================================================================
另外,可以自己写代码实现UNIX和北京时间的转换,我没有试过,有兴趣可参考以下网页。
Unix时间戳和北京时间的相互转换(C语言实现 )https://blog.csdn.net/u012183892/article/details/90451671C实现Unix时间戳和本地时间转化
https://blog.csdn.net/mill_li/article/details/54599927
参考资料:
KEIL MDK 中localtime函数使用方法https://www.cnblogs.com/hello-myworld/p/14746331.html