【问题标题】:why does my debouncer not work?为什么我的去抖动器不起作用?
【发布时间】:2017-02-20 14:47:25
【问题描述】:

我正在尝试编写一个 debouncer,如果它已经被 debounce(-1 四次反弹),它将只返回一个有效的参数 (>0)。 到目前为止我已经想出了这个,但它总是返回-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
$

【问题讨论】:

    标签: c debouncing


    【解决方案1】:

    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)
    

    【讨论】:

    • 还有另一个问题,只是减去 tnow.tv_nsec - tset.tv_nsec 无法正常工作,因为 tv_nsec 只是一秒后的纳秒数。
    • @nos 是的,现在更新答案(只是分心了几分钟)。
    • @kaylum 是的,因此最后一个参数应该被接受并且不会去抖动,但它也会去抖动......
    • @cerr 为什么要接受最后一个值? usleep 不够长,因此去抖动期尚未到期。
    • @cerr 您没有考虑秒部分,tv_sec。您假设tnow.tv_nsec &lt; tset.tv_nsec 的情况等于翻转的秒数。但这是不正确的,因为即使在另一种情况下,秒数也可能会翻转。您必须以某种方式查看tv_sec
    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2014-06-11
    相关资源
    最近更新 更多