为什么我的去抖不起作用?

时间:2016-10-11 22:29:58

标签: c debouncing

我试图写一个debouncer,它只会返回一个有效的参数(> 0),如果它已被去抖(-1四次弹跳)。 到目前为止,我已经提出了这个问题,但它总是返回-1,为什么我不知道:

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

#define BOUNCETIME  500000000 //(500ms)

#define SetTime(x)     clock_gettime(CLOCK_REALTIME, (x));  // set time

static struct timespec tset;
struct timespec tnow;

int DeBounce(unsigned int arg)
{  
  static int val = -1;
  long long nsec = 0;
  if (val < 0) {
    val = arg;
    SetTime(&tset);  
    return arg;    
  } else {
    SetTime(&tnow);
    if (tnow.tv_nsec < tset.tv_nsec)
      nsec = tnow.tv_nsec + 1000000000;
    else
      nsec = tnow.tv_nsec;
    if (tnow.tv_nsec - tset.tv_nsec > BOUNCETIME) {
      printf("arg okay\n"); 
      val = -1;
      return arg;
    }
    else 
      printf("bounce, ignore!\n");
      return -1;
  }

}

int main (void) 
{
  printf("#1 %d\n",DeBounce(0));
  usleep(1);
  printf("#2 %d\n",DeBounce(1));
  usleep(200);
  printf("#3 %d\n",DeBounce(1));
  sleep(1);
  printf("#4 %d\n",DeBounce(1));
}

我得到的输出是:

$ ./debounce 
#1 0
bounce, ignore!
#2 -1
bounce, ignore!
#3 -1
bounce, ignore!
#4 -1
$

1 个答案:

答案 0 :(得分:3)

usleep(600);为600 微秒。但你的去抖时间是500 毫秒

此外tnow.tv_nsec - tset.tv_nsec不正确,因为tv_nsec不是全时值,而只是超过秒的纳秒数。以纳秒为单位计算经过时间的正确方法如下:

(tnow.tv_sec * 1.0e-9 + tnow.tv_nsec) - (tset.tv_sec * 1.0e-9 + tset.tv_nsec)