I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.
#define led1 10 //10th,
#define led2 11 //11th
#define led3 12 //12th
#define led4 13 //13th
#define ButtonA 9
int ButtonState;
int ButtonState2;
int state;
int StateNow;
int PreviousState = HIGH;
void setup(){
pinMode(led1,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(led3,OUTPUT);
pinMode(led4,OUTPUT);
pinMode(ButtonA,INPUT_PULLUP);
Serial.begin(9600);
Serial.println("Enter ch a, b, c, or d:");
}
void loop() {
if (Serial.available())
{
ButtonState = digitalRead(ButtonA);
delay(10);
ButtonState2 = digitalRead(ButtonA); //debounce
if (ButtonState != ButtonState2)
{
StateNow = ButtonState2;
}
else
{
StateNow = ButtonState;
}
if(StateNow == LOW && PreviousState == HIGH)
{
digitalWrite(led1,LOW);
digitalWrite(led2,LOW);
digitalWrite(led3,LOW);
digitalWrite(led4,LOW);
Serial.println("Turned off all LEDs");
PreviousState = LOW;
}
else if(StateNow == HIGH && PreviousState == LOW)
{
PreviousState = HIGH;
}
state = Serial.read();
if (state == 'a' || state == 'A')
{
digitalWrite(led1,HIGH);
Serial.println("Turned on led 1");
}
else if (state == 'b' || state == 'B')
{
digitalWrite(led2,HIGH);
Serial.println("Turned on led 2");
}
else if (state == 'c' || state == 'C')
{
digitalWrite(led3,HIGH);
Serial.println("Turned on led 3");
}
else if (state == 'd' || state == 'D')
{
digitalWrite(led4,HIGH);
Serial.println("Turned on led 4");
}
}
}
The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software