1.查看系统时间
date
2.查看RTC时间
由于不同的RTC驱动读取时间的方法不一样。我这边使用的是hi_rtc。是使用海思中自动的测试程序。
./tim -g time
3.系统时间同步成RTC时间
hwclock –r 显示硬件时钟与日期
hwclock –s 将系统时钟调整为与目前的硬件时钟一致。
hwclock –w 将硬件时钟调整为与目前的系统时钟一致。
但是我使用相关命令会出现:
提示找不到相对应的设备节点。
因为我的设备节点是加载在/dev/hi_rtc中,所以通用的这个是不行了。(海思的RTC不能使用通过的系统时间同步命令)
利用mktime和settimeofday的直接在读取RTC时间时,将RTC时间再通过这两个函数再写入到系统时间中。
mktime函数:
C 库函数 time_t mktime(struct tm *timeptr) 把 timeptr 所指向的结构转换为一个依据本地时区的 time_t 值。
#include <time.h> time_t mktime(struct tm *timeptr)
参数:
struct tm {
int tm_sec; /* 秒,范围从 0 到 59 */ int tm_min; /* 分,范围从 0 到 59 */ int tm_hour; /* 小时,范围从 0 到 23 */ int tm_mday; /* 一月中的第几天,范围从 1 到 31 */ int tm_mon; /* 月份,范围从 0 到 11 */ int tm_year; /* 自 1900 起的年数 */ int tm_wday; /* 一周中的第几天,范围从 0 到 6 */ int tm_yday; /* 一年中的第几天,范围从 0 到 365 */ int tm_isdst; /* 夏令时 */ };
返回值:
该函数返回一个 time_t 值,该值对应于以参数传递的日历时间。如果发生错误,则返回 -1 值。
作用是,将时间转换为自1900年1月1日以来持续时间的秒数,发生错误时返回-1。(注意这边是自1900的1月份)
settimeofday函数:
#include<sys/time.h> #include<unistd.h> int settimeofday ( const struct timeval *tv,const struct timezone *tz); 参数: struct timeval{ long tv_sec;/*秒*/ long tv_usec;/*微妙*/ }; struct timezone{ int tz_minuteswest;/*和greenwich 时间差了多少分钟*/ int tz_dsttime;/*type of DST correction*/ } 返回值:函数执行成功后返回0,失败后返回-1,错误代码存于errno中。
4.实例
/* * RTC sample&test code. */ #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <string.h> #include <sys/time.h> #include <time.h> #include "hi_rtc.h" void usage(void) { printf( " " "Usage: ./test [options] [parameter1] ... " "Options: " " -s(set) Set time/alarm, e.g '-s time 2012/7/15/13/37/59' " " -g(get) Get time/alarm, e.g '-g alarm' " " -w(write) Write RTC register, e.g '-w <reg> <val>' " " -r(ead) Read RTC register, e.g '-r <reg>' " " -a(alarm) Alarm ON/OFF', e.g '-a ON' " " -reset RTC reset " " -b(battery monitor) battery ON/OFF, e.g '-b ON' " " -f(requency) frequency precise adjustment, e.g '-f <val>' " " "); exit(1); } static int _atoul(const char *str, unsigned char *pvalue) { unsigned int result=0; while (*str) { if (isdigit((int)*str)) { if ((result<429496729) || ((result==429496729) && (*str<'6'))) { result = result*10 + (*str)-48; } else { *pvalue = result; return -1; } } else { *pvalue=result; return -1; } str++; } *pvalue=result; return 0; } #define ASC2NUM(ch) (ch - '0') #define HEXASC2NUM(ch) (ch - 'A' + 10) static int _atoulx(const char *str, unsigned char *pvalue) { unsigned int result=0; unsigned char ch; while (*str) { ch=toupper(*str); if (isdigit(ch) || ((ch >= 'A') && (ch <= 'F' ))) { if (result < 0x10000000) { result = (result << 4) + ((ch<='9')?(ASC2NUM(ch)):(HEXASC2NUM(ch))); } else { *pvalue=result; return -1; } } else { *pvalue=result; return -1; } str++; } *pvalue=result; return 0; } /*used for convert hex value from string to int*/ static int str_to_num(const char *str, unsigned char *pvalue) { if ( *str == '0' && (*(str+1) == 'x' || *(str+1) == 'X') ){ if (*(str+2) == '