프로그래밍/리눅스
리눅스 어플리케이션에서 RTC 사용하기
kyudoc
2021. 3. 26. 15:58
728x90
제품을 만들어보면 시간이 꽤나 틀어지는 경우가 많이 있습니다. 그나마 네트워크나 GPS 등의 장치가 있으면 시간 동기화라도 할 수 있지만 단독 제품인 경우는 그럴 수가 없습니다. 그래도 시간에 민감한 제품이 아니라고 생각해서 그냥 시장에 내보냈다가 바이어나 소비자로 부터 시간이 자꾸 틀어진다는 컴플레인이 발생하지요.
(하지만 요즘에는 원칩에 있는 RTC도 꽤 정확하더라구요. 모든 경우에 다그런 것은 아닙니다.)
그래서 외부 RTC를 사용해서 시간 오차가 적도록 설계하곤 하는데요. 외부 RTC가 잘 동작하는지 확인 할 수 있는 예제 코드입니다.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <linux/rtc.h>
#include <errno.h>
int idx = 1;
int main()
{
int fd;
int rval;
char path[20];
struct rtc_time time;
sprintf(path, "/dev/rtc%d", idx);
if ((fd = open(path, O_RDWR)) < 0) {
fprintf(stderr, "Can't open file '%s'\r\n", path);
exit(EXIT_FAILURE);
}
// Set Time
time.tm_sec = 0;
time.tm_min = 0;
time.tm_hour = 0;
time.tm_mday = 1;
time.tm_mon = 1;
time.tm_year = 2021;
time.tm_wday = 0; // not use
time.tm_yday = 0; // not use
time.tm_isdst = 0; // not use
if ((rval = ioctl(fd, RTC_SET_TIME, &time)) < 0) {
fprintf(stderr, "%s\r\n", strerror(errno));
exit(EXIT_FAILURE);
}
// Read time
if ((rval = ioctl(fd, RTC_RD_TIME, &time)) < 0) {
fprintf(stderr, "%s\r\n", strerror(errno));
exit(EXIT_FAILURE);
}
fprintf(stdout, "%04d/%02d/%02d %02d:%02d:%02d\r\n",
1900+time.tm_year, time.tm_mon+1, time.tm_mday,
time.tm_hour, time.tm_min, time.tm_sec);
close(fd);
return 0;
}
728x90