利用了 attachInterrupt()函数 捕获电平变化的信号 拿到了高电平的维持时间(微秒,下同)和低电平的维持时间,再滤掉低电平的维持时间,拿到了我们想要的pwm信号频率。
网上的很多检测频率的方法要么过于复杂 要么获取的频率太低 或者不能用于检测舵机pwm频率。
下面的代码解决了上述问题 简单易理解,易移植。
#define ACT_CTR 5
uint16_t act_ctr_monitor1;
uint16_t act_ctr_monitor2=0;
unsigned long act_ctr_pwm1;
unsigned long act_ctr_pwm2;
void setup() {
// put your setup code here, to run once:
attachInterrupt(ACT_CTR, act_ctr_timer, CHANGE);
act_ctr_pwm1=micros ();
}
void loop() {
// put your main code here, to run repeatedly:
if(act_ctr_monitor2!=act_ctr_monitor1)
{ if(micros ()-act_ctr_pwm1<2200)
{act_ctr_pwm2=micros ()-act_ctr_pwm1;}
printf("%d\n",act_ctr_pwm2);
act_ctr_pwm1=micros ();
act_ctr_monitor2=act_ctr_monitor1=0;
}
}
void act_ctr_timer()
{
act_ctr_monitor1++;
}