Hey everyone, another question from a newbie...
The idea behind this piece of code is to give 'the user' feedback when they turn the switch off. Pressing the switch lights LED1. Turning the switch off turns off LED1 and flashes LED2 (this flash is to tell the user that they've pressed the button), then returns to a state of all LEDs being off.
I'm not sure if my logic in the code is right...once you press the button the code goes through both the 'if (val == HIGH)' and 'else' sections of the code. Surely, if the button is pressed, i.e. HIGH, it will run 'if (val == HIGH)' and skip the 'else' part...when I check with Serial Monitor it is simply running though both section....I just can't seem to figure it out!?
int switchPin = 2;
int led1Pin = 9;
int led2Pin = 10;
int val;
int buttonState;
int lightMode = 0; // initial state of the LEDs (all off)
// setup
void setup () {
pinMode(switchPin, INPUT);
pinMode(led1Pin, OUTPUT);
pinMode(led2Pin, OUTPUT);
Serial.begin(9600); // setup serial at 9600bps
buttonState = digitalRead(switchPin); // reads initial button state into variable (e.g. 0)
}
// main loop
void loop(){
val = digitalRead(switchPin); // switch value into val e.g. val = 0
if (val != buttonState) { // if button state has change carry on
if (val == HIGH) { // if button is on
lightMode = 2; // turn LEDs on
Serial.print("LEDs on ");
}
else { // if button is off
lightMode = 1; // turn LEDs off
Serial.print("LEDs off ");
}
buttonState = val; // save new buttonState to variable
}
if (lightMode == 0) { // makes sure all LEDs are off
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, LOW);
}
if (lightMode == 1) { // turns led1 off, flashes led2 for 1sec and then turns it off again
digitalWrite(led1Pin, LOW);
digitalWrite(led2Pin, HIGH);
delay(1000);
digitalWrite(led2Pin, LOW);
lightMode = 0;
}
if (lightMode == 2) { // turns led1 on
digitalWrite(led1Pin, HIGH);
}
}