如何用c 语言写一个 定时器

1.代码分析

在这里插入图片描述

2.代码

#include <stdio.h>
#include <time.h>
#include <conio.h>

#ifndef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC 1000
#endif

int main( void )
{
	clock_t start;
	long count = 1;
	start = clock();
	while(1)
	{
		if((clock() - start) == CLOCKS_PER_SEC)
		{
			printf("%ld\n",count++);
			start = clock();
			//break;
		}
	}
	getch();
}

3. 代码抽象出一个定时器函数 void timer(long time)

void timer(long time){

    clock_t start;
	long count = 1;
	start = clock();
	while(1)
	{
		if((clock() - start) != (time*CLOCKS_PER_SEC))
		{
			//时间没有到,啥也不做,空循环
		}else {
            //时间到了退出循环
            // printf("%s","hello");
            break;
        }
        
	}
}

完整代码

#include <stdio.h>
#include <time.h>
#include <conio.h>

#ifndef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC 1000
#endif
/**
 * time 的单位为s
 */
void timer(long time){

    clock_t start;
	long count = 1;
	start = clock();
	while(1)
	{
		if((clock() - start) != (time*CLOCKS_PER_SEC))
		{
			//时间没有到,啥也不做,空循环
		}else {
            //时间到了退出循环
            // printf("%s","hello");
            break;
        }
        
	}
}
int main( void )
{
   
    for(int i=0;i<10;i++){
        timer(1);
        printf("%d\n",i);
    }
	getch();
}

在这里插入图片描述

很抱歉,作为AI语言模型,我无法提供完整的C语言程序。但是,我可以提供一个基本的程序框架,帮助你了解如何编一个定时器中断系统的数字秒表显示器。 1. 头文件包含 在程序开始时,需要包含一些头文件,以便使用所需的函数和数据类型。以下是一些可能需要的头文件: ```c #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/time.h> ``` 2. 全局变量 在程序中需要声明一些全局变量,以便在各个函数之间共享和使用。以下是一些可能需要的全局变量: ```c int seconds = 0; int minutes = 0; int hours = 0; ``` 3. 计时器中断处理函数 为了实现定时器中断,需要编一个中断处理函数,用于更新计时器的值。以下是一个示例函数: ```c void timer_handler(int signum) { seconds++; if (seconds == 60) { minutes++; seconds = 0; } if (minutes == 60) { hours++; minutes = 0; } } ``` 4. 注册计时器中断 在程序中需要注册计时器中断,以便在规定的时间间隔内调用中断处理函数。以下是一个示例函数: ```c void register_timer() { struct sigaction sa; struct itimerval timer; // 安装计时器中断处理函数 sa.sa_handler = &timer_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGALRM, &sa, NULL); // 设置计时器时间间隔 timer.it_value.tv_sec = 1; timer.it_value.tv_usec = 0; timer.it_interval.tv_sec = 1; timer.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &timer, NULL); } ``` 5. 显示器函数 在程序中需要编一个函数,将计时器值显示在屏幕上。以下是一个示例函数: ```c void display_timer() { printf("\r%02d:%02d:%02d", hours, minutes, seconds); fflush(stdout); } ``` 6. 主函数 在程序中需要编一个主函数,用于初始化全局变量、注册计时器中断和显示计时器值。以下是一个示例函数: ```c int main() { register_timer(); while (1) { display_timer(); } return 0; } ``` 这是一个基本的程序框架,可以根据需要进行修改和扩展。请注意,由于涉及到底层的系统调用和中断处理,可能需要在特定的操作系统和硬件平台上进行调试和优化。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值