Arduino读取点击俯卧撑开关的次数

时间:2016-05-25 18:12:31

标签: arduino arduino-uno

我正在尝试读取arduino在60秒内点击一次开关的次数。参考文档,我已经实现了一个倒数计时器,从60秒到0倒计时。按钮状态仅每秒检查一次。如果我每秒按下按钮超过一次,它只会注册一个。我做错了什么?

以下是代码:

const int  buttonPin = 2;   
unsigned int Clock = 0, R_clock;
boolean Reset = false, Stop = false, Paused = false;
volatile boolean timeFlag = false;
int buttonPushCounter = 0;   // counter for the number of button    presses
int buttonState = 0;         // current state of the button  
int lastButtonState = 0;     // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);

 Serial.begin(9600);
 SetTimer(0,0,60); // 10 seconds
 StartTimer();
}

void loop() {
CountDownTimer(); // run the timer
if (TimeHasChanged() ) 
{
Serial.print(ShowSeconds());
Serial.println();
}

}
void StartTimer()
{
Watch = micros(); // get the initial microseconds at the start of the timer
Stop = false;
}

boolean CountDownTimer()
{
static unsigned long duration = 1000000; // 1 second
timeFlag = false;

if (!Stop && !Paused) // if not Stopped or Paused, run timer
{
if ((_micro = micros()) - time > duration ) 
{
  Clock--;
  timeFlag = true;

  if (Clock == 0) // check to see if the clock is 0
    Stop = true; // If so, stop the timer

  if(ShowSeconds()>0 && ShowSeconds() <= 60){
     buttonState = digitalRead(buttonPin);
   // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
  // if the state has changed, increment the counter
  if (buttonState == HIGH) {
  // if the current state is HIGH then the button
  // wend from off to on:
  buttonPushCounter++;
  Serial.println("on");
  Serial.print("number of button pushes:  ");
  Serial.println(buttonPushCounter);
  } else {
  // if the current state is LOW then the button
  // wend from on to off:
  Serial.println("off");
  }
  }
  }
  }}
  }
  return !Stop; // return the state of the timer
  }

  void SetTimer(unsigned int hours, unsigned int minutes, unsigned int seconds)
 {
  // This handles invalid time overflow ie 1(H), 0(M), 120(S) -> 1, 2, 0
  unsigned int _S = (seconds / 60), _M = (minutes / 60);
  if(_S) minutes += _S;
  if(_M) hours += _M;

  Clock = (hours * 3600) + (minutes * 60) + (seconds % 60);
  R_clock = Clock;
  Stop = false;
}

void SetTimer(unsigned int seconds)
{
// StartTimer(seconds / 3600, (seconds / 3600) / 60, seconds % 60);
Clock = seconds;
R_clock = Clock;
Stop = false;
}
int ShowSeconds()
{
return Clock % 60;
}
boolean TimeHasChanged()
{
return timeFlag;
}

1 个答案:

答案 0 :(得分:1)

编写的代码基本上用于边缘状态检测。这是在其他时间间隔内没有读取按钮状态的主要原因。