最近在编写一个stm32上面的驱动函数,就是把时:分:秒(可以计时到999999:59:59)格式的RTC转换为年-月-日-时:分:秒格式,设想的实现函数为:RTC_DateDef vRtcGetDate(RTC_DateDef rtc_date, RTC_TimeDef rtc_time)
{
RTC_DateDef date_base = {0,0,0,0,0,0};
date_base.RTC_SS = rtc_date.RTC_SS;
date_base.RTC_MM = rtc_date.RTC_MM;
date_base.RTC_HH = rtc_date.RTC_HH;
date_base.RTC_DAY = rtc_date.RTC_DAY;
date_base.RTC_MON = rtc_date.RTC_MON;
date_base.RTC_YEAR = rtc_date.RTC_YEAR;
u32 days = 0;
u16 sum = 0;
date_base.RTC_SS += (u16)(rtc_time.RTC_SS); //get the seconds
if(date_base.RTC_SS > 59)
{
date_base.RTC_SS = 0;
assign_rtc_flag = 1;
date_base.RTC_MM++;
}
date_base.RTC_MM += (u16)(rtc_time.RTC_MM); //get the minutes
if(date_base.RTC_MM > 59)
{
date_base.RTC_MM = 0;
date_base.RTC_HH++;
}
days = rtc_time.RTC_HH / 24; //get the total days
rtc_time.RTC_HH -= days * 24;
date_base.RTC_HH += (u16)(rtc_time.RTC_HH); //get the remain hours
if(date_base.RTC_HH > 23)
{
date_base.RTC_HH = 0;
date_base.RTC_DAY++;
}
//calculate how many years passed
while(1)
{
sum = 365;
if(isLeapYear(date_base.RTC_YEAR))
{
sum += 1;
}
if(days < sum) //less than a year
{
break;
}
date_base.RTC_YEAR++;
days -= sum;
}
//calculate how many months passed
while(1)
{
sum = days_of_year[date_base.RTC_MON - 1];
if(date_base.RTC_MON == 2)
{
if(isLeapYear(date_base.RTC_YEAR))
{
sum += 1; //leap year
}
}
//less than a month
if(days < sum)
{
date_base.RTC_DAY += (u16)days;
if(date_base.RTC_DAY > sum)
{
date_base.RTC_DAY -= sum;
date_base.RTC_MON++;
if(date_base.RTC_MON > 12)
{
date_base.RTC_MON -= 12;
date_base.RTC_YEAR++;
}
}
break;
}
date_base.RTC_MON++;
days -= sum;
}
return date_base;
}
rtc_date的只可以在main函数里复制,rtc_time是系统RTC计数器技术的结果,就是想把系统计数的直加上基准值,得到当前的直,然后通过串口显示,后来我发现,date_base是局部变量,函数每调用一次,就赋值一次,再加上RTC自动技术的值,假设基准值为2011-11-20-13-20-30,rtc_time.RTC_SS从0-29的时候,可以显示30-59,但是rtc_time.RTC_SS从30开始,30+30>59,清零,31同样清零,这样就有30个0了,这对分,天,月也是同样的道理,不知那位大吓能否帮帮忙啊,谢谢!
两个结构体为
typedef struct
{
__IO uint32_t RTC_HH;
__IO uint32_t RTC_MM;
__IO uint32_t RTC_SS;
} RTC_TimeDef;
//lm added
typedef struct
{
__IO uint16_t RTC_YEAR;
__IO uint16_t RTC_MON;
__IO uint16_t RTC_DAY;
__IO uint16_t RTC_HH;
__IO uint16_t RTC_MM;
__IO uint16_t RTC_SS;
}RTC_DateDef;
|