For an orientation course at school we get taught to work with Arduino. I have the following issue with a challenge.
This is the simulation:
This is the code:
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4; // the number of the pushbutton pin
const int buttonPin2 = 2;
const int GreenLed = 13; // the number of the LED pin
const int YellowLed = 12;
const int RedLed = 8;
// variables will change:
int initial = 0; //hold current initial
int oldstate = 0; //hold last initial
int buttonstate = 0; // variable for reading the pushbutton status
void setup() {
pinMode(GreenLed, OUTPUT); // initialize the LED pin as an output:
pinMode(YellowLed, OUTPUT);
pinMode(RedLed, OUTPUT);
pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
//debouncing routline to read button
buttonstate = digitalRead(buttonPin); //state the initial of button
buttonstate = digitalRead(buttonPin2);
if (buttonstate == HIGH) { //check if it has been pressed
delay(50);
buttonstate = digitalRead(buttonPin);//state button again
if (buttonstate == LOW) { //if it is 0 considered one press
initial = oldstate + 1; //increase initial by 1
if (buttonstate == HIGH) { //check if it has been pressed
delay(50);
buttonstate = digitalRead(buttonPin2);//state button again
if (buttonstate == LOW) { //if it is 0 considered one press
initial = oldstate - 1; //decrease initial by 1
}
} else { //check if it has been NOT pressed
delay(100);
}
switch (initial) { //react to button press a initial
case 1: //if initial is 1
digitalWrite(GreenLed, HIGH);//on
digitalWrite(YellowLed, LOW);//off
digitalWrite(RedLed, LOW);//off
oldstate = initial; //set oldstate initial as current initial
break;
case 2:
digitalWrite(GreenLed, LOW);
digitalWrite(YellowLed, HIGH);
digitalWrite(RedLed, LOW);
oldstate = initial;
break;
case 3:
digitalWrite(GreenLed, LOW);
digitalWrite(YellowLed, LOW);
digitalWrite(RedLed, HIGH);
oldstate = initial;
break;
default: //if initial is not 1 2 3
digitalWrite(GreenLed, LOW); //off
digitalWrite(YellowLed, LOW);
digitalWrite(RedLed, LOW);
oldstate = 0; //reset to all off/initial 0
break;
}
}
This is what i need to do as an extra: i have no idea how.
Extension of the previous challenge:
add another button and make sure that at
pressing this button always reverses the direction of lighting of the LEDs.
After the first press on the 'reverse' button, the sequence thus becomes 3 β 2 β 1 β 3 β 2, etc.
After another press on the 'reverse' button, the sequence is again 1 β 2 β 3 β 1 β 2, etc.
Tip:
Use an extra variable in which you store the direction.
Please help
