Hi All,
Could I please get assistance on the following.
There are 3 leds, a buzzer and 3 push-buttons,
button 1, increment leds from left to right and wrap around
button 2, decrement leds from right to left and wrap from last high led
button 3, reset and sound buzzer for long
buzzer, sound everytime button 1 and 2 are pressed.
Challenge: I am not sure as to how I can decrement using button 2 from the last high led.
Code + Format:
// constants won’t change. They’re used here to
// set pin numbers:
const int buttonPin1 = 6; // the number of the pushbutton pin
const int buttonPin2 = 5;
const int buttonPin3 = 2;
const int ledRED = 12;
const int ledBLUE = 10;
const int ledGREEN = 8; // the number of the LED pin
const int buzzer = 4;
int index = -1; // to indicate which led should be turned on
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
// To save the last logic state of the button
int buttonState2 = 0;
void setup() {
pinMode(ledRED, OUTPUT); // initialize the LEDRED pin as an output
pinMode(ledBLUE, OUTPUT);
pinMode(ledGREEN, OUTPUT);
pinMode(buzzer, OUTPUT); // Set buzzer - pin 4 as an output
pinMode(buttonPin1, INPUT); // initialize the pushbutton pin as an input:
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
noTone(buzzer); // Stop sound…
digitalWrite(ledRED, HIGH); // On startup led 1, on
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin1);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
if (index != -1) { // if index is not the initial value
switch (index) {
case 0:
digitalWrite(ledBLUE, LOW);
digitalWrite(ledRED, LOW);
digitalWrite(buzzer, 0); // Switch pressed, buzzer on
tone(buzzer, 100); // Send 1KHz sound signal…
delay(100); // …for 1 sec
noTone(buzzer); // Stop sound…
break;
case 1:
digitalWrite(ledGREEN, LOW);
digitalWrite(buzzer, 0); // Switch pressed, buzzer on
tone(buzzer, 100); // Send 1KHz sound signal…
delay(100); // …for 1 sec
noTone(buzzer); // Stop sound…
break;
case 2:
digitalWrite(ledRED, LOW);
digitalWrite(buzzer, 0); // Switch pressed, buzzer on
tone(buzzer, 100); // Send 1KHz sound signal…
delay(100); // …for 1 sec
noTone(buzzer); // Stop sound…
break;
}
}
index++; // turn on the next LED
index = index % 3;
switch (index) {
case 0:
digitalWrite(ledBLUE, HIGH); // turn the LED on (HIGH is the voltage level)
digitalWrite(ledRED, LOW);
digitalWrite(buzzer, 0); // Switch pressed, buzzer on
tone(buzzer, 100); // Send 1KHz sound signal…
delay(100); // …for 1 sec
noTone(buzzer); // Stop sound…
break;
case 1:
digitalWrite(ledGREEN, HIGH);
digitalWrite(buzzer, 0); // Switch pressed, buzzer on
tone(buzzer, 100); // Send 1KHz sound signal…
delay(100); // …for 1 sec
noTone(buzzer); // Stop sound…
break;
case 2:
digitalWrite(ledRED, HIGH); // Switch pressed, buzzer on
tone(buzzer, 100); // Send 1KHz sound signal…
delay(100); // …for 1 sec
noTone(buzzer); // Stop sound…
break;
}
}