多个计时器Arduino

时间:2015-02-26 01:36:47

标签: c timer arduino

您好我对Arduino上的计时器有疑问。

我有5个物理按钮(压电),我从中获取模拟输入。然后我让他们写出键盘键。我的问题是当一个人被击中时我希望它无法击中" x"多少时间。我尝试使用延迟,但最终延迟了整个程序,因此无法同时击中2个按钮。有人可以向我解释如何使用计时器吗?我想为控制布尔值的每个按钮分别设置5个单独的定时器,我需要为5个单独的if语句分别设置5个定时器。 (见代码)。

//SNARE LOOP2  
if(sensorValueA0 == 0)
{
  if(SnareHit == false)
  {

  Keyboard.write(115);
  SnareHit = true;
  //Use timer here to delay this part of the system
  SnareHit = false;
  }
}
//BASS DRUM LOOP
if(sensorValueA1 == 0)
{
  if(BassHit == false)
  {

  Keyboard.write(98);
  BassHit = true;
  //Use timer here to delay this part of the system
  BassHit = false;
  }
}

感谢。

2 个答案:

答案 0 :(得分:0)

您可以使用millis()函数,类似于以下代码:

if(ButtonPress==true){
 time=millis() //time was previously declared as unsigned long
    if(time>=5000){ //5000 = 5 sec
     ButtonPress==false
    }
}

它不会像dealy()那样停止arduino循环。 更多信息:http://playground.arduino.cc/Code/AvoidDelay

答案 1 :(得分:0)

也许您正试图取消按钮。我通常在主循环中执行此操作,并期望连续5次"按下"在我说按钮真的被按下之前读取,如下所示:

int  button1PressedCount = 0;
int  debounceCounter = 5; // Number of successive reads before we say the switch is pressed
boolean buttonPressed = false;
int inputPin1 = 7;

void setup() {
  // Grounding the input pin causes it to actuate
  pinMode(inputPin1, INPUT ); // set the input pin 1
  digitalWrite(inputPin1, HIGH); // set pin 1 as a pull up resistor.
}

void loop()     
{
  // Some code

  // Check button, we evaluate below
  checkButton();

  // Some more code
}

void checkButton() {
  if (digitalRead(inputPin) == 0) {
    // We need consecutive pressed counts to treat this is pressed    
    if (button1PressedCount < debounceCounter) {
      button1PressedCount += 1;
      // If we reach the debounce point, mark the start time
      if (button1PressedCount == debounceCounter) {
        // Button is detected as pressed!
        buttonPressed = true;
      }
    }
  } else {
    if (button1PressedCount == debounceCounter) {
        // We were pressed, but are not any more 
        buttonPressed = false;
    }

    button1PressedCount = 0;
  }
}

此外,似乎使用模拟输入检查模拟值是否恰好等于0可能在嘈杂环境中有点敏感。这就是我使用数字输入和内部上拉电阻的原因。