Linux定时器 select(微秒精度)poll(毫秒精度)

8 篇文章 1 订阅
8 篇文章 0 订阅

头文件与函数

#include <sys/select.h>

int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);

void FD_CLR(int fd, fd_set *set); //将set中第fd位清除

int FD_ISSET(int fd, fd_set *set);//判断set中第fd位是否位1,是返回1否返回1

void FD_SET(int fd, fd_set *set); //将set中第fd位设置为1

void FD_ZERO(fd_set *set);//将fd中所有位清除

fd_set可以看成一个数组,里面存着文件描述符。

readfds可读文件描述符集合

witefds可写文件描述符集合

execeptfds可执行文件描述符集合

n:所有集合中最大的文件描述符加1

struct timeval{      
                long tv_sec;   /*秒 */
                long tv_usec;  /*微秒 */   
            }
timeout表示select函数等待时间。
将select函数第一个参数设置为0,第二三四参数设置为NULL,最后一个参数设置为时间,可以当定时器用。
struct timeval tv;

tv.tv_sec = 1;

tv.tv_usec = 1000;
select(0, NULL, NULL, NULL, &tv);
实例,每0.5s执行一次函数

#include <sys/time.h>
#include <sys/select.h>
#include <stdio.h>
//mseconds: micro seconds 1s = 1000000us
void setTimer(int seconds, int useconds)
{
	struct timeval temp;

	temp.tv_sec = seconds;
	temp.tv_usec = useconds;

	select(0, NULL, NULL, NULL, &temp);
	printf("timer interval: %ds %dus\n", seconds, useconds);
	return;
}

int main()
{
	int i;
	for (i=0; i<10; i++)
	{
		setTimer(0, 500000);
	}
	return 0;
}	

使用poll()来作为毫秒精度定时器

原理与select一样,都是监视空文件描述符并等待超时。

#include <sys/time.h>
#include <stdio.h>
#include <poll.h>

//mseconds: 定时器毫秒
void setPollTimer(int mseconds)
{
	struct pollfd fds[1];
	fds[0].fd = 0;
	fds[0].events = POLLIN;
	poll(fds, 1, mseconds);
	printf("this is poll timer\n");
}

int main()
{
	int i;
	for (i=0; i<10; i++)
	{
		setPollTimer(2000);
	}
	return 0;
}	

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于STM32F103系列微控制器的滴答定时器,可以使用它来实现毫秒微秒级的延时。下面是两个简单的函数示例,用于实现延时。 首先,我们需要启用滴答定时器。可以使用下面的代码片段来初始化滴答定时器: ```c void SysTick_Init(void) { SysTick->LOAD = (uint32_t)(SystemCoreClock / 1000) - 1; // 设置滴答定时器的重装载值,实现1ms的中断一次 SysTick->VAL = 0; // 清空当前计数值 SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk; // 开启滴答定时器 } ``` 接下来,我们可以定义一个函数来实现毫秒级延时: ```c void delay_ms(uint32_t ms) { uint32_t start = SysTick->VAL; // 记录当前计数值 uint32_t target = start - (ms * (SystemCoreClock / 1000)); // 计算目标计数值 if (start < target) // 处理计数器溢出的情况 { while (SysTick->VAL > start || SysTick->VAL <= target); } else { while (SysTick->VAL > start && SysTick->VAL <= target); } } ``` 最后,我们可以定义一个函数来实现微秒级延时: ```c void delay_us(uint32_t us) { uint32_t start = SysTick->VAL; // 记录当前计数值 uint32_t target = start - (us * (SystemCoreClock / 1000000)); // 计算目标计数值 if (start < target) // 处理计数器溢出的情况 { while (SysTick->VAL > start || SysTick->VAL <= target); } else { while (SysTick->VAL > start && SysTick->VAL <= target); } } ``` 使用这两个函数,你可以在STM32F103微控制器上实现所需的毫秒微秒级延时。请注意,这些函数会阻塞程序的执行,直到延时结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值