1
votes

Ok, so I have started my Project 2 on Arduino Uno. It involves 3 blinking leds. The original idea is that the green led will be lit until a switch is pressed which will make the other two leds blink consecutively. However, I have tried to make the green led keep blinking until I press the switch (instead of it just being lit passively prior to the pressing of the switch). So I made one small adjustment to the if statement, however this didn't work (the led blinked once and then continued being lit).

    int switchState=0;

void setup() {
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(2, INPUT);

// put your setup code here, to run once:

}

void loop() {

switchState= digitalRead(2);

if (switchState==LOW) {

digitalWrite(3, HIGH);
delay(1000);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
}

else {

digitalWrite(3,LOW);
digitalWrite(4,LOW);
digitalWrite(5, HIGH);

delay(250);

digitalWrite(4, HIGH);
digitalWrite(5, LOW);

delay(250);

}


// put your main code here, to run repeatedly:

}

The green LED is assigned to pd3 and the two other leds to pd4 and pd5.

So why, upon the verification of the condition, (whether the switch was pressed or not), does the led blink only once- shouldn't it continue blinking? However when I inserted another delay after the 2nd digitalWrite(3, LOW), it worked. Whats the explanation for this? I'm new to this so please make your explanation clear.

1

1 Answers

0
votes

Case 1: The user does not press switch the switch for at least > delay(1000); to run again. In this section:

switchState= digitalRead(2);
if (switchState==LOW)       // <----  User is not pressing switch so we 
{                           //        enter the if.
    digitalWrite(3, HIGH);
    delay(1000);
    digitalWrite(3, LOW);
    // Adding delay here makes it blink.
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
}

Once you have done the digitalWrite(3, LOW); , it is in micro/miliseconds before the loop is repeated and you enter the if again. The LED actually did blink, but it is so fast you can't see it. The LED would stay on as long as the user didn't press the the button.

Case 2: User pressed button and after running through the if statement at least once. The LED is left OFF as it enters the else.

else
{
   digitalWrite(3,LOW);
   digitalWrite(4,LOW);
   digitalWrite(5, HIGH);
   delay(250);
   digitalWrite(4, HIGH);
   digitalWrite(5, LOW);
   delay(250);
}

The LED is set again to LOW and then remains OFF.

Does that help?