1

I am just learning the Arduino, it is a learning curve that's for sure.

Using the onboard Led I want to use two buttons to make the Led blink for different times.

I am not sure what is missing from the code, as pressing BUTTON2 gives the same time as BUTTON.

Any help would be greatly appreciated.

 const byte BUTTON = 2;
const byte BUTTON2 = 3;
const byte LED = 13;

unsigned long buttonPushedMillis;
unsigned long ledTurnedOnAt;
unsigned long turnOnDelay = 500;
unsigned long turnOffDelay = 500;
unsigned long turnOnDelay2 = 1000;
unsigned long turnOffDelay2 = 1000;
bool ledReady = false;
bool ledState = false;

void setup() {
  pinMode(BUTTON, INPUT_PULLUP);
  pinMode(BUTTON2, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  unsigned long currentMillis = millis();
  if (digitalRead(BUTTON) == LOW) {
    delay(50);
    buttonPushedMillis = currentMillis;
    ledReady = true;
  }
  if (ledReady) {
    if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay) {
      digitalWrite(LED, HIGH);
      ledState = true;
      ledTurnedOnAt = currentMillis;
      ledReady = false;
    }
  }
  if (ledState) {
    if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay) {
      ledState = false;
      digitalWrite(LED, LOW);
    }
  }
  {
    unsigned long currentMillis = millis();
    if (digitalRead(BUTTON2) == LOW) {
      delay(50);
      buttonPushedMillis = currentMillis;
      ledReady = true;
    }
    if (ledReady) {
      if ((unsigned long)(currentMillis - buttonPushedMillis) >= turnOnDelay2) {
        digitalWrite(LED, HIGH);
        ledState = true;
        ledTurnedOnAt = currentMillis;
        ledReady = false;
      }
    }
    if (ledState) {
      if ((unsigned long)(currentMillis - ledTurnedOnAt) >= turnOffDelay2) {
        ledState = false;
        digitalWrite(LED, LOW);
      }
    }
  }
}

\\

1
  • Please format your code properly (indent it all 4 characters of start and end it with three back-ticks on a line of their own).
    – Majenko
    Jun 7 '20 at 13:09
1

You're making your program too complex for its own good.

Instead of changing your blink code depending on which button is pressed, just make the button change the blink code's parameters, and stick to just one blink code.

That means having just one set of blink variables which your blink code uses, and your button code then just changes what values those variables contain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.