Hi there, I am currently trying to write a program to blink the onboard LED of an Arduino UNO at a rate of 2hz.
I am using tinkercad. I have a breadboard wired to the Arduino with a pull-down resistor switch circuit. With a press of the button, the LED should go from OFF to flashing, then with another button press, the LED should go from flashing to OFF.
My issues with my current program are that the LED starts out flashing and on the second button press the LED sticks in whatever state it was in when the button was pressed. ie if the LED is on when the button is pressed for the second time it remains on.
I am unsure how to go about correcting this, any help would be very much appreciated!
const int ledPin = LED_BUILTIN;
const int buttonPin = 2;
int ledState = LOW;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
unsigned long previousMillis = 0;
const long interval = 250;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop(){
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
}
delay(50);
}
lastButtonState = buttonState;
if (buttonPushCounter % 2 == 0) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}
}
Thank you all for your help! I have made the adjustments that blh64 set out in post #2 and the script is now working as desired.
If I wanted to add another setting for the LED, flashing at 5 hz, after the third button press. So the sequence would be off, 2hz flashing, 5hz flashing, off. Could I still use the button counter to do that? Or would there be a better way to do that?