Linux定时器(signal、setitimer),软件PWM驱动舵机(SG90)
- signal
- setitimer
- 示例
- 软件PWM驱动舵机(SG90)
signal
详情请看Linux 3.进程间通信(shmget shmat shmdt shmctl 共享内存、signal signaction sigqueue 信号、semget semctl semop 信号量)
setitimer
setitimer
允许你设置定时器的初始值和重复间隔。一旦定时器启动,它将在到期时触发一个信号,通常是 SIGALRM
信号。你可以捕获这个信号并执行相应的操作。
#include <sys/time.h>int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);
参数说明
which
:指定要设置的定时器类型,可以是 ITIMER_REAL
、ITIMER_VIRTUAL
或 ITIMER_PROF
中的一个。
ITIMER_REAL
:以实际时间计时,通常用于实现定时器功能。
ITIMER_VIRTUAL
:以进程的虚拟时间(CPU时间)计时。
ITIMER_PROF
:以进程的虚拟时间和系统时间(CPU和墙钟时间)计时。
new_value
:一个 struct itimerval
结构,用于指定新的定时器值。
old_value
:一个 struct itimerval
结构,用于存储旧的定时器值(可选参数)。
Timer values are defined by the following structures:
struct itimerval {struct timeval it_interval; /* Interval for periodic timer */struct timeval it_value; /* Time until next expiration */};struct timeval {time_t tv_sec; /* seconds */suseconds_t tv_usec; /* microseconds */};
示例
#include <stdio.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>void signal_handler(int signum)
{printf("Hello!\n");
}int main()
{struct itimerval timer;timer.it_interval.tv_sec = 1; /* Interval for periodic timer */timer.it_interval.tv_usec = 0;timer.it_value.tv_sec = 5; /* Time until next expiration */timer.it_value.tv_usec = 0;signal(SIGALRM, signal_handler);setitimer(ITIMER_REAL, &timer, NULL);while(1);return 0;
}
运行程序 5s 后开始输出 Hello! ,然后每隔 1s 输出 Hello!
软件PWM驱动舵机(SG90)
#include <stdio.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <wiringPi.h>#define STEER 5int angle = 0;
static int cnt = 0;void signal_handler(int signum)
{if(cnt <= angle){digitalWrite(STEER, HIGH);}else{digitalWrite(STEER, LOW);}if(cnt == 40){cnt = 0;}cnt++;
}int main()
{delay(1);struct itimerval timer;timer.it_interval.tv_sec = 0; /* Interval for periodic timer */timer.it_interval.tv_usec = 500;timer.it_value.tv_sec = 1; /* Time until next expiration */timer.it_value.tv_usec = 0;signal(SIGALRM, signal_handler);setitimer(ITIMER_REAL, &timer, NULL);wiringPiSetup();pinMode(STEER, OUTPUT);while(1){printf("please input 1-0 2-45 3-90 4-135 5-180\n");scanf("%d",&angle);}return 0;
}