Reputation: 13
Hi I am having a little trouble understanding the behaviour of what would seem a very simple issue.
I have 4 LED's and resistors linked up, with a push button. The idea is that I press the button and the LEDS light up sequentially, turning the previous one off.
This works fine, until it is time to restart the loop from the beginning where everything is ok in serial monitor, but the LEDS barely light up except number 4 which lights up normally.
Here is my code:
const int buttonPin = 6;
const int ledPin1 = 2;
const int ledPin2 = 3;
const int ledPin3 = 4;
const int ledPin4 = 5;
int buttonState = 0;
int pressed = 0;
void setup() {
{
Serial.begin (115200);
Serial.println ();
Serial.println ("Starting up");
}
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
pinMode(ledPin4, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop()
{
if(digitalRead(buttonPin)==HIGH)
{
if(pressed==0)
{
pressed=1;
switch(buttonState)
{
case 0:
digitalWrite(ledPin1, LOW);
buttonState++;
break;
case 1:
digitalWrite(ledPin1, HIGH);
Serial.println ("1");
buttonState++;
break;
case 2:
digitalWrite(ledPin2, HIGH);
pinMode(ledPin1, LOW);
Serial.println ("2");
buttonState++;
break;
case 3:
digitalWrite(ledPin3, HIGH);
pinMode(ledPin2, LOW);
Serial.println ("3");
buttonState++;
break;
case 4:
digitalWrite(ledPin4, HIGH);
pinMode(ledPin3, LOW);
Serial.println ("4");
buttonState++;
break;
case 5:
digitalWrite(ledPin4, LOW);
Serial.println ("off");
buttonState=0;
return;
}
}
}
else
{
pressed=0;
}
}
Hope some of you more intelligent folks can shed some light on this unusual behaviour.
BTW I am VERY new to arduino programming so please take it easy.
Upvotes: 0
Views: 149
Reputation: 1582
You want to understand the difference between pinMode()
and digitalWrite()
functions.
pinMode(pin, mode)
configures the specified pin to behave either as an input or an output. (doc)
digitalWrite(pin, value)
writes a HIGH or a LOW value to a digital pin. (doc)
In your switch statement, you are changing pinMode
from OUTPUT
to INPUT
.
pinMode(ledPin1, LOW)
is the same as
pinMode(ledPin1, INPUT)
because LOW
and INPUT
are both defined as 0x00
.
When you change the pin mode to INPUT
, you can no longer turn on your LED by calling digitalWrite(ledPin1, HIGH)
.
LED 4 works because you don't call pinMode(ledPin4, LOW)
anywhere.
I think you wanted to call digitalWrite(ledPin1, LOW)
instead of pinMode(ledPin1, LOW)
in the switch statement.
Upvotes: 2