If/else/else if function

Using PIR sensor to light up two LED's depending on if sensor is activated or not. I want a green LED if the sensor is not activated and a red LED if it is activated. When I run my code the green LED is lit (sensor deactivated) which is correct. I then activated the sensor and the green LED goes off and the red LED comes on (correct). However, the red LED then remains on and does not go off even though the sensor is de activated. The green LED also does not come back on.

My code:

int sensorState = 0;

void setup()
{
pinMode(2, INPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}

void loop()
{

sensorState = digitalRead(2);

if (sensorState == HIGH) {
digitalWrite(13, HIGH);
Serial.println("Sensor activated!");
}
else if (sensorState == LOW){
digitalWrite(12, HIGH);
//Serial.println("Sensor deactivated");
}

else {
// Do nothing
}

delay(10); // Delay a little bit to improve simulation performance
}


int sensorState = 0;

void setup()
{
pinMode(2, INPUT);
pinMode(13, OUTPUT);
Serial.begin(9600);
}

void loop()
{
sensorState = digitalRead(2);

if (sensorState == HIGH) 
{
digitalWrite(12, LOW);
digitalWrite(13, HIGH);
Serial.println("Sensor activated!");
}
else
{
digitalWrite(13, LOW);
digitalWrite(12, HIGH);
Serial.println("Sensor deactivated");
}

delay(10); // Delay a little bit to improve simulation performance

} //END of    loop()

1 Like

FYI

Hello arduino10134
Use names for the port pins, avoid magic numbers.
I guess the pinMode for the second unknown LED is missing.
Have a nice day and enjoy coding in C++.

2 Likes

Was going to walk the OP through that, you spoiled the fun. :nerd_face:

ohhhhhhhh, I´m so sorry :rofl: :joy::nerd_face:

if (sensorState == HIGH) {
digitalWrite(13, HIGH);
Serial.println("Sensor activated!");
}
else if (sensorState == LOW){
digitalWrite(12, HIGH);
//Serial.println("Sensor deactivated");
}

else {
// Do nothing
}

Please look at this. The pin can only be HIGH or LOW, there is no other state to else be!

If it's LOW, that's the else to HIGH.

I do this to my own code, review it critically, look for more logic than there should be and trim where possible.

The thing is that the compiler likely optimizes the unnecessary operations like that second if the do-nothing else out of the compiled code.

@arduino10134
What has this to do with installation and troubleshooting?

I have moved this to a more appropriate place on the forum. I note that in your other question the forum instructions were brought to your attention but it seems that so far you have not read them. Please read them before posting anything else.

Thank you.

Pin 12 defaults to INPUT LOW. Changing it to HIGH gets very low current 5V.
Maybe enough to open a BJT and switch external power?

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