This week we’re working on digital and analog. While working on digital sensors in the lab (see below), I had a switch (button) and 2 bulbs, where the the first bulb is lit up, and when you press the button the second one gets lit up. When button released it’s again just the first bulb lit up.

img_0664

So I decided to improvise on this idea and see if I can change the code a little. What I wanted to make is when you click the button the 2nd bulb lights up, and then when you click again it goes to the 1st bulb and 2nd goes off. And then once clicked and it lights up 2nd bulb again and 1st one goes off. And so on.

Here is the code that I used to make this work.

bool threeOn = true;

void setup() {
pinMode(2, INPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
Serial.begin(9600);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);

}

void loop() {
if(digitalRead(2) == HIGH) {
if (threeOn == true) {
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
threeOn = false;
} else {
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
threeOn = true;
}
Serial.println(“pressed”);
delay(150);
}
}

Advertisements