Total newby here starting out with Arduino and programming.
Using Arduino Uno
I do teach Automotive engineering and understand the principles of circuits and wiring etc.
I have build a sketch with three LED's as outputs and one mom pushbutton. The idea is to get the outputs to change each time the button is pressed and then reset.
push 1 = Red Led on
Push 2 = Blue LED on, rest off
Push 3 = Green LED on, rest off.
Push 4 = all off, reset.
So far I have this working, but.... When I switch to Green LED, the other two flash. I assume this is the sketch picking up the switch going from high back to low when I release it. Can I stop this flash?
Hope I have uploaded code right,
Thank you
```cpp
// this constant won't change:
const int buttonPin = 8; // the pin that the pushbutton is attached to
const int ledPin1 = 7; // the pin that the LED is attached to
const int ledPin2 = 6; //second led pin number
const int ledPin3 = 5; //Third led pin number
// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH)
{
// if the current state is HIGH then the button went from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
if (buttonPushCounter >= 4) // max number of pushes before reset
{
Serial.println("The button has been pressed four times");
Serial.println("resetting the counter");
buttonPushCounter = 0;
} else {
// if the current state is LOW then the button went from on to off:
Serial.println("off");
}
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
//after one push, turns on red led
if (buttonPushCounter < 1 == 0) {
digitalWrite(ledPin1, HIGH);
} else {
digitalWrite(ledPin1, LOW);
}
//after two pushes, turns on blue led and turn off red
if (buttonPushCounter < 2 == 0) {
digitalWrite(ledPin2, HIGH);
digitalWrite(ledPin1, LOW);
} else {
digitalWrite(ledPin2, LOW);
}
//after 3 pushes turns on green led and turn off blue.
if (buttonPushCounter < 3 == 0) {
digitalWrite(ledPin3, HIGH);
digitalWrite(ledPin2, LOW);
} else {
digitalWrite(ledPin3, LOW);
}
}
}