If statement is being ignored

Here is some simple code:

int switchVal = 0;
void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(4,OUTPUT);
}

void loop() {
if (switchVal = 46){
  digitalWrite(2, HIGH);
  digitalWrite(4, HIGH);
}
else{
  digitalWrite(2,LOW);
  digitalWrite(4,LOW);
}
}

Pins 2 and 4 are connected to different sets of LEDs. Because of the if statement, they shouldn't be on. Why are they?

Ooooops!!!

Oh.

Happens to all of us sooner or later!

Also how does switchVal ever change ?

And = is not the same as ==

What is switchVal ?


If switchVal is an input pin connected to a switch, use S3 as the way to wire your switch.
Look for a low for a switch closed, turn on the internal pull-up resistor.

1 Like

LarryD, so external pulldown with a switch is risky? So, for example, the way this project is wired up is not recommended?
See here: https://create.arduino.cc/projecthub/i-and-myself/arduino-kitchen-timer-db8ba6?f=1

S1 circuit is not recommended as there is the chance of 5v shorting to other components in the project.


If you wire your switches as S3 is wired, you can use the built in pull-up resistors on the input pins. i.e. you do not need to wire external resistors.

When you look for a switch closed condition, look for a LOW.

//is the switch closed ?
if(digitalRead(mySwitch) == LOW)
{
  //do something
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.