linux에서 rtc를 이용하여 정확한 타이머를 실현
선상 부호
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/rtc.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#define FREQ 2048
#define USEC_PER_SECOND 1000000
typedef int MILLSEC;
int g_fd = 0;
 
int calc_cnt(MILLSEC millseconds )
{
    return (int)(millseconds * 1000.0 / USEC_PER_SECOND * FREQ + 0.5); //add 0.5 to meet precision in common
}
void rtc_open()
{
	g_fd = open ("/dev/rtc", O_RDONLY);
	if(g_fd < 0)
	{   
		perror("open");
		exit(errno);
	}
	printf("opened.
");
}
 
void set_freq()
{
	/*Set the freq*/
    if(ioctl(g_fd, RTC_IRQP_SET, FREQ ) < 0)
    {
        perror("ioctl(RTC_IRQP_SET)");
        close(g_fd);
        exit(errno);
    }
    /* Enable periodic interrupts */
    if(ioctl(g_fd, RTC_PIE_ON, 0) < 0)
    {
        perror("ioctl(RTC_PIE_ON)");
        close(g_fd);
        exit(errno);
    }
}
void rtc_task()
{
	printf("start counting...
");
    struct timeval tvs,tve;
    unsigned long i = 0;
    unsigned long data = 0;
	while(true)
	{
		int time_to_wait;
		printf("please input time to wait in millsecond, -1 to break
");
		scanf("%d",&time_to_wait);
		if(time_to_wait < 0)
			break;
		//calc how many times to loop
		int cnt = calc_cnt(time_to_wait);
		gettimeofday( &tvs , 0 );
		for(i = 0; i < cnt; i++)
		{
			if(read(g_fd, &data, sizeof(unsigned long)) < 0)
			{
				perror("read");
				ioctl(g_fd, RTC_PIE_OFF, 0);
				close(g_fd);
				exit(errno);
			}
		}
		gettimeofday(&tve,0);
		printf("[%ld]timer usec
" , (tve.tv_sec - tvs.tv_sec) * 1000000LL + (tve.tv_usec-tvs.tv_usec));
	}
    /* Disable periodic interrupts */
    ioctl(g_fd, RTC_PIE_OFF, 0);
    close(g_fd);
}
int main(int argc, char* argv[])
{
    rtc_open();
    set_freq();
    rtc_task();
	return 0;
}예에서 사용한 주파수는 2048이고 주파수의 사용 가능한 범위는 2~8192이다. 반드시 2의 n차원이어야 한다. 그렇지 않으면 실행할 때 오류가 발생한다. 주파수는 1초에 몇 번을 실행할 수 있는지를 나타낸다. 만약에 2048번이라면 한 번의 시간은 1.0/2048(초)이다. 이로써time to wait를 실행할 때 몇 번을 실행해야 하는지를 확정한다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.