The purpose of this code is for a green LED (led1) to be HIGH when the program starts and for a red LED (led2) to be HIGH when a button is pressed. When either LED is HIGH, the other should be LOW.
When the Red LED is HIGH, I require a two second delay, followed by a buzzer sound for 1 second.
I would then like the RED to stay HIGH and the Buzzer to be LOW (or the equivalent in audio terms) when I complete the next lot of code.
My code
const int led1= 12;
const int led2 = 13;
const int button = 2;
const int buzzer = 7;
int previous = LOW;
int initial = HIGH;
long time =0;
long debounce = 200;
int buttonState = 0;
int buzzerState = 0;
int lastBuzzerState =0;
void setup() {
pinMode (led1, OUTPUT);
pinMode (led2, OUTPUT);
pinMode (button, INPUT);
pinMode (buzzer, OUTPUT);
Serial.begin (9600);
}
void loop() {
buttonState = digitalRead(button);
if (buttonState == HIGH && previous == LOW && millis() - time > debounce) {
if (initial == HIGH)
initial = LOW;
else
initial = HIGH;
time = millis();
}
digitalWrite(led1, initial);
digitalWrite (led2, !initial);
previous = buttonState;
buzzerState = digitalRead (led2);
if (buzzerState == HIGH){
Serial.print ("Stand back shock coming in...");
delay (2000);
tone (buzzer, 100);
delay (1000);
noTone (buzzer);
lastBuzzerState = buzzerState;
}
}
I have two issues,
a) The buzzer currently loops, I have tried creating a new function, but the buzzer would not sound at all. I also created a new variable LastBuzzerState and set buzzerState to equal that after the buzzer sounded.
b) Re pressing the button does not revert the program back to the Green LED HIGH and RED LED LOW, how would I go about this?
Many Thanks