2016-10-11 4 views
1

私はデバッガを書き込もうとしています。デバウンサはデバッガがあれば有効な引数(> 0)を返すだけです(-14バウンシング)。なぜ私のデバウナーは動作しませんか?

#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)); 
} 

私が手ouputををされています:

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

答えて

3

usleep(600);は600 マイクロ秒である 私がこれまでに作ってみたが、それは常に-1を返し、なぜ私は思ったんだけどということです。しかし、デバウンスの期間は、ミリ秒です。

tnow.tv_nsec - tset.tv_nsecは正確ではありません。tv_nsecはフルタイム値ではなく、秒を超えたナノ秒数です。 tv_nsecがちょうど数であることから,, tset.tv_nsecが正常に動作するつもりはない - ちょうどtnow.tv_nsec減算、

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

があまりにも別の問題をtheresの:ナノ秒単位で経過時間を計算するための正しい方法は、このようなものです1秒を超えるナノ秒。 – nos

+1

@nosはい、今すぐ回答を更新してください(ちょっと気を散らしてしまいました)。 – kaylum

+0

@kaylumはい、したがって、最後の議論は受け入れられるべきであり、デバウンスされるべきではありませんが、それはデバウンします。 – cerr

関連する問題