Need help with the logic in code to pulse a light on button press

I am trying to make a light bulb stay on for a set amount of time and then return to the off default position of the device. having issues of wither blinking the device and staying on or just using th button as a toggle.

const int BUTTON_PIN = 2; // Arduino pin connected to button's pin
const int LED_PIN    = 8; // Arduino pin connected to LED's pin

// variables will change:
int lightState = LOW;     // the current state of LED
int lastButtonState;    // the previous state of button
int currentButtonState; // the current state of button

void setup() {
  //Serial.begin(9600);                // initialize serial
  pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
  pinMode(LED_PIN, OUTPUT);          // set arduino pin to output mode

  currentButtonState = digitalRead(BUTTON_PIN);
}

void loop() {
  lastButtonState    = currentButtonState;      // save the last state
  currentButtonState = digitalRead(BUTTON_PIN); // read new state

  if(lastButtonState == HIGH && currentButtonState == LOW) {
    Serial.println("The button is pressed");

    // toggle state of LED
    //lightState = !lightState;
    digitalWrite(LED_PIN, lightState);
    delay (100);
    lightState = !lightState;
    digitalWrite(LED_PIN, lightState);
    delay (100);
    //lightState = !lightState;
    digitalWrite(LED_PIN, lightState);
    delay (100);
    //lightState = !lightState;

    // control LED arccoding to the toggled state
    
  }
}

any help would be appreciated, in the current configuration it just acts as a toggle.

1 Like

Cool, first post using code tags, +1.

Is the button a toggle or a push button?

For at least 300ms the micro controller is doing nothing. Which means for 1/3 of a second the button cannot be detected. Not such a issue but this is also a good time to checkout the doing multiple things at the same time with millis(); look it up using the search box.

What do you mean by

?

Hi thank you for the response, the button I am using for the application is a push button, meant to cycle between states.
the code I have submitted will make the button act as a toggle for the light only. push to turn on push to turn off.

Here is some code that toggles a LED.

it does not use delay( ).

Can you figure out how the fragment works ?


void loop()
{
  //*************************************                          h e a r t b e a t   T I M E R
  //to see if the sketch is blocking,
  //toggle the heartbeat LED every 500ms
  if (millis() - heartbeatMillis >= 500)
  {
    //restart the TIMER
    heartbeatMillis = millis();

    //toggle the LED
    digitalWrite(heartbeatLED, !digitalRead(heartbeatLED));
  }
}
1 Like

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