Different LED blinking rates toggled by debounce switch

Hi,
I am new to Arduino and I was wondering if you could help me with my first project. My goal for this project is to have a LED light blink between two different rates when a debounce switch is pressed. If you could please look over my sketch and help me out on how to understand this problem at a coding level, I would greatly appreciate it. I am using an Arduino Uno board along with two resistors, a LED light and a debounce switch, which is shown in the attached image. Thank you!

const int buttonPin = 2;
const int ledPin = 13;
int ledState = HIGH;
int buttonState;
int lastButtonState = LOW;

unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, ledState);
}

void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
ledState = !ledState;
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
if (buttonState == LOW) {
ledState = !ledState;
digitalWrite(ledPin, HIGH);
delay(200);
digitalWrite(ledPin, LOW);
delay(200);
}
}
}
}
digitalWrite(ledPin, ledState);
lastButtonState = reading;
}

test.ino (1.03 KB)

If You select the code, press Ctrl C, click on the upper left symbol in this window, </> and then Ctrl v code will be visible here. You will get more helpers answering.

I would change the 10 k resistor into the switch and remove the cable to +5. In the code You set the mode ofD2 to INPUT_PULLUP and uses the built in resistor.

Hello,
you have to split your sketch into two parts:

  1. debouncing
  2. LED blinking
    You need an extra timer on the base the IDE example BLINKWITHOUTDELAY.
    The button pin reading will than control the different blink rates.

You don´t need an extra LED if you use PIN13, this PIN is connected to the onbord LED.

Railroader:
I would change the 10 k resistor into the switch and remove the cable to +5. In the code You set the mode ofD2 to INPUT_PULLUP and uses the built in resistor.

Why ?? Will it solve OP's problem ?

sterretje:
Why ?? Will it solve OP's problem ?

Simplifying typically goes a long way towards solving.

-jim lee

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.