Hello,all.
Following are codes.It 's function is to set RTC.
Code:
#include <time.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <sys/types.h>
#include <sys/stat.h>
/* Copied from linux/rtc.h to eliminate the kernel dependency */
struct linux_rtc_time {
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
#define RTC_SET_TIME _IOW('p', 0x0a, struct linux_rtc_time) /* Set RTC time */
static void write_rtc(time_t t)
{
int rtc;
struct tm tm;
if (( rtc = open ( "/dev/rtc", O_WRONLY )) < 0 ) {
if (( rtc = open ( "/dev/misc/rtc", O_WRONLY )) < 0 )
fprintf(stdout,"Could not access RTC\n" );
}
tm = *(localtime ( &t ));
tm. tm_isdst = 0;
if ( ioctl ( rtc, RTC_SET_TIME, &tm ) < 0 )
fprintf(stdout,"Could not set the RTC time.\n" );
close ( rtc );
}
int sync_time(const unsigned char *cmd)
{
time_t tma;
struct tm * tmb;
char tmp[4];
// time(&result);
// my_time = gmtime(&result);
// my_time->tm_year += 1900;
// my_time->tm_mon += 1;
tmp[0] = cmd[2] >> 4; // get the year
tmp[1] = cmd[2] & 0x0f;
tmp[2] = cmd[3] >> 4;
tmp[3] = cmd[3] &0x0f;
tmb->tm_year = (tmp[0] * 1000 + tmp[1] * 100 + tmp[2] * 10 + tmp[3]) - 1900;
tmp[0] = cmd[4] >>4; //get month
tmp[1] = cmd[4] & 0x0f;
tmb->tm_mon = (tmp[0] * 10 + tmp[1]) - 1;
tmp[0] = cmd[5] >> 4; //day
tmp[1] = cmd[5] & 0x0f;
tmb->tm_mday = tmp[0] * 10 + tmp[1];
tmp[0] = cmd[6] >> 4; //hour
tmp[1] = cmd[6] & 0x0f;
tmb->tm_hour = tmp[0] * 10 + tmp[1];
tmp[0] = cmd[7] >> 4; //minute
tmp[1] = cmd[7] & 0x0f;
tmb->tm_min = tmp[0] * 10 + tmp[1];
tmp[0] = cmd[8] >> 4; //second
tmp[1] = cmd[8] & 0x0f;
tmb->tm_sec = tmp[0] * 10 + tmp[1];
printf("%02d:%02d:%02d",tmb->tm_hour,tmb->tm_min,tmb->tm_sec);
tma = mktime(tmb); //conver tm to time_t
/* write_rtc(tma); */ // set RTC .
return 0;
}
int main(void)
{
unsigned char cmd[9]={0x00,0x00,0x20,0x06,0x09,0x26,0x11,0x23,0x11};
int re;
re=sync_time(cmd);
return 0;
}