为什么我的防弹跳器不起作用? [英] why does my debouncer not work?

查看:95
本文介绍了为什么我的防弹跳器不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个去抖动器,如果它已被去抖动(-1个四次弹起),它将仅返回一个有效的参数(> 0). 到目前为止,我已经提出了这个问题,但是它总是返回-1,为什么我想知道:

I'm trying to write a debouncer that will only return a valid argument (>0) if it has been debounced (-1 four bouncing). I've come up with this so far but it always returns -1, why is that I'm wondering:

#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
$

推荐答案

usleep(600);是600 微秒.但是您的反跳周期为500 毫秒.

usleep(600); is 600 microseconds. But your debounce period is 500 milliseconds.

此外,tnow.tv_nsec - tset.tv_nsec是不正确的,因为tv_nsec不是完整时间值,而是仅超过秒的纳秒数.计算经过时间(以纳秒为单位)的正确方法是这样的:

Furthermore tnow.tv_nsec - tset.tv_nsec is not correct as tv_nsec is not the full time value but only the number of nanoseconds past the second. The correct way to calculate elapsed time in nanoseconds is something like this:

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

这篇关于为什么我的防弹跳器不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆