Go Down

Topic: Arduino Countdown.  (Read 1 time) previous topic - next topic

blomcrestlight

This "bips" led 13....

Code: [Select]
// https://forum.arduino.cc/index.php?topic=672112
// ir sensor with countdown
// led on during countdown

/*
  BASED ON State change detection (edge detection) changed for INPUT PULLUP
               (button wired from pin to ground)
  https://www.arduino.cc/en/Tutorial/StateChangeDetection
*/

// this constant won't change:
const int  button = 14;

// Variables will change:
bool buttonState;         // current state of the button
bool lastButtonState;     // previous state of the button
bool timing = false;
unsigned long timingStartedAt;
int timeFor = 5000;
unsigned long lastBip;
int bipInterval = 100;
bool bipState;

void setup()
{
  // initialize serial communication:
  Serial.begin(9600);
  Serial.println(" ir sensor with countdown");
  pinMode(button, INPUT_PULLUP);

  //initialize button states
  buttonState = digitalRead(button);
  lastButtonState = buttonState;

  //turn bulitin led off
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  Serial.println(" ");
  Serial.println("setup() done... interrupt the sensor");
  Serial.println(" ");
}

void loop()
{
  checkSensor();

  if (timing && millis() - lastBip >= bipInterval)
  {
    lastBip = millis();
    digitalWrite(LED_BUILTIN, bipState);
    bipState=!bipState;
  }

  if (timing && millis() - timingStartedAt >= timeFor)
  {
    timing = false;
    Serial.println("... done");
    digitalWrite(LED_BUILTIN, LOW);
  }

} //loop

void checkSensor()
{
  // read the button:
  buttonState = digitalRead(button);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) // != means not equal, so it changed one way or the other
  {
    if (!timing && buttonState == LOW) //... and if it's now low, that's a press, but not already busy
    {
      Serial.print("Started");
      timingStartedAt = millis();
      timing = true;
      digitalWrite(LED_BUILTIN, HIGH);
    }// change to low
    else
    {
      //Serial.println(", new absence");
    }//change to high

    // Delay a little bit to avoid bouncing
    delay(50);
  }//change
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;
}//checkSensor



Go Up