Hello I am very confused with the if else statement in my code. Running the serial monitor I have correct reading on the monitor but the opposite of what I would think should be happening on the board / output.. Serial monitor shows high with switch not depressed , low with switch pressed ( I have pin 2 tied to 10k resistor that is hooked to 5v, Pin 2 is pulled low through a switch to ground when depressed). The serial monitor shows what I belive to be correct, (PIN 2, 5v = 1 Pin 2, 0.02 V = 0 . The LED light is OFF for 2 sendonds with a quick blink with the serial monitor showing 1. I would expect the LED on most of the time with the blink off breifly according to the code. Please help me understand as I am new and probably overlooking something really easy.
int Switch1 = 2;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(Switch1, INPUT);
}
void loop() {
Switch1 = digitalRead(2);
Serial.println(Switch1);
if (digitalRead(Switch1) == HIGH) // Pin 2 is not pulled low
{
digitalWrite(LED_BUILTIN, LOW);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
delay(2000);
} else // If Pin is low begin good pattern
{
digitalWrite(LED_BUILTIN, LOW);
delay(2000); // tooth 1
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
//set up for REPEAT
}
}
Thanks for using code tags for your post. You forgot to post your schematic. You posted in the wrong sub category.
This is not a good test sketch, because it has needless features. Write a simple sketch that only turns the LED on and off in response to the switch. Test that and make it work, then worry about blinking stuff.
e.g.
int Switch1 = 2;
void setup() {
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(Switch1, INPUT);
}
void loop() {
Switch1 = digitalRead(2);
Serial.println(Switch1);
if (digitalRead(Switch1) == HIGH) // Pin 2 is not pulled low
{
digitalWrite(LED_BUILTIN, HIGH);
} else // If Pin is low begin good pattern
{
digitalWrite(LED_BUILTIN, LOW);
}
}
int Switch1 = 2;
// here you set the value to 2. So far, so good
...
// but now you assign a different value to it:
Switch1 = digitalRead(2);
// suppose input was HIGH, now Switch1 == HIGH == 1.
...
if (digitalRead(Switch1) == HIGH) // Pin 2 is not pulled low
// now you are really doing
// if (digitalRead(1) == HIGH)
Oh I think I am understanding better. I want to read the state of PIN 2 , however I was assigning a value to it. I am reworking the problem now. My goal is to be able to serial monitor the input pin 2 (high or low) and alse run the if else statement. Thank you for taking the time to try and help me.
Thank you for helping me clarify, I truly appreciate the time that you have taken. I have a weak understanding of code, but after a night's sleep and your clear explanation I see the error I made. I alsos remember from high school garbage in garbage out. such a simple and obvious mistake. I thank you once again!