双击 "Laser On" 双击 "Laser Off" - Arduino

Double click "Laser On" Double click "Laser Off" - Arduino

谢谢大家的宝贵时间。 我有我的代码,当我一直按住按钮时,激光会打开 "HIGH" 当我从按钮上松开手指时,激光会关闭 "LOW"

但是我想要双击打开激光,再次双击关闭激光。

谢谢你,抱歉我的英语不好。

const int btn = 6;// The push button
int previousButtonStateLAZER = HIGH;   // for btn6

void setup(){
  pinMode(btn, INPUT);
  pinMode (laserPin, OUTPUT);
}

void loop(){
  int buttonStateLAZER = digitalRead(btn);

  // if the button state has changed,
  if (buttonStateLAZER != previousButtonStateLAZER){
    if( buttonStateLAZER == HIGH ) {
      digitalWrite (laserPin, HIGH);
    }else{
      digitalWrite (laserPin, LOW);
    }
  }
  previousButtonStateLAZER = buttonStateLAZER;
}```

您需要存储检测到点击的最后两次,然后进行测试以查看它们是否足够接近。试试这个代码(根据你发布的内容编辑):

const int btn = 6;// The push button
int previousButtonStateLAZER = LOW;   // for btn6

static long releaseTimes[2];
static int releaseIndex = 1;

static int laserStates[2];
static int laserIndex = 0;

void setup(){
  pinMode(btn, INPUT);
  pinMode (laserPin, OUTPUT);

  releaseTimes[0] = 0;
  releaseTimes[1] = 0;

  laserStates[0] = LOW;
  laserStates[1] = HIGH;
}

void loop(){
  int buttonStateLAZER = digitalRead(btn);

  // if the button state has changed,
  if (buttonStateLAZER != previousButtonStateLAZER){
      previousButtonStateLAZER = buttonStateLAZER;

      if (buttonStateLAZER == HIGH) {
          return;
      }

      releaseIndex = 1 - releaseIndex;
      releaseTimes[releaseIndex] = millis();

      if (abs(releaseTimes[0] - releaseTimes[1]) < 800) {
          releaseTimes[0] = 0;
          releaseTimes[1] = 0;
          laserIndex = 1 - laserIndex;
          digitalWrite(laserPin, laserStates[laserIndex]);
      }
  }

}