I am trying to program my Arduino to replicate opening a door with one button and closing it with the other. When the door is opened using the first button a timer counts back from five at five seconds the light and speaker will blink and beep until the second button is pressed.
I wanted to make it so that if I press the second button before five seconds the light and speaker will not beep but I cannot figure out how to do it.
Thank you in advance to anyone who can give me a hand with this, I am not a programmer so this is all very confusing to me. Here is the code I have now, It does everything I want it to do besides not beep and blink if the second button is pressed before five seconds.
/*Dementia ward door buzzer-- When ButtonPin1 (representing opening a door) is pressed a timer counts down from 5.
After Five seconds a LED will blink and speaker(wired to the LED) will buzz until door is closed (by pressing Button Pin 2)
Written by ********* 11/18/19*/
byte LEDpin = 10;
byte ButtonPin1 = 11;
byte ButtonPin2 = 12;
byte DisplayNumbers[] = {B11111100, B01100000, B11011010, B11110010,
B01100110, B10110110, B10111110, B11100000,
B11111110, B11110110};
// The following is an array of indices to be used with the DisplayNumbers array
byte DisplayNumberIndex[] = {5, 4, 3, 2, 1};
void setup()
{
pinMode(LEDpin, OUTPUT);
pinMode(ButtonPin1, INPUT);
pinMode(ButtonPin2, INPUT);
DDRD = B11111110; /* DDRD is the direction register for
the Arduino's PORT D (Digital Pins 0 - 7). DDRD = B11111110
tells Arduino to set pin 0 for input, pins 1 through 7 for output */
}
void loop()
{
if (digitalRead(ButtonPin1) == HIGH) //Start flashing LED if 1st button is pressed
{
for (byte index = 0; index <= 4; index++)
{
PORTD = DisplayNumbers[DisplayNumberIndex[index]]; //Use the indexed array to choose the digit
delay(1000);
}
PORTD = B00000000;// turn off seven segment display
while(HIGH)
{
digitalWrite(LEDpin, HIGH);
delay(250);
if (digitalRead(ButtonPin2) == HIGH) //Checks if 2nd button is pressed.
{
digitalWrite(LEDpin, LOW); //If 2nd button is pressed, turn off LED
break; //and break out of the while loop
}
digitalWrite(LEDpin, LOW);
delay(250);
if (digitalRead(ButtonPin2) == HIGH) //Checks if 2nd button is pressed.
{
digitalWrite(LEDpin, LOW); //If 2nd button is pressed, turn off LED
break; //and break out of the while loop
}
}
}
}
Ty2012:
I wanted to make it so that if I press the second button before five seconds the light and speaker will not beep but I cannot figure out how to do it.
If you want a responsive program you should not use delay() as the Arduino is blocked until the delay() completes. And for the same reason don't use WHILE or FOR unless they complete very quickly - a small number of microseconds. Generally it is better to use IF and allow loop() to do the repetition - which is also facilitated by the State Machine concept recommended by @Blackfin.
Have a look at how millis() is used to manage timing without blocking in Several Things at a Time.