Pulse Every 45 Seconds - Solid On When Button Pressed

Been working on a pet-project the last day and no further ahead now than I was yesterday at this time. I am very new to programming and this one is getting to me.

Looking for a way to turn on an LED on Pin 0 every 30 seconds for 2 seconds, and repeat. This I have working just fine. The second part I am trying to figure out is to sense a pushbutton on Pin 2 and if active, turn the LED on for as long as the button is pressed. After releasing the button, we can go back to the 30 second on/off sequence.

I have tried so many things, I cannot seem to get it.
Anyone share some thoughts on how to do this??

Appreciate it.. Eric

If this is an UNO, do not use pin D0 as it is for Serial communications.

Show us your current sketch.

Show us your circuit schematic.

First things first…. do not use delay() in your code.

You need the program to be aware of the button at all times. delay() will block that.

Pulse Every 45 Seconds
vs.

The choice of pin 2 (Uno) could imply that this exercise was intended to demonstrate interrupt handling.

const byte LEDPin = 0;  // It's OK to use Pin 0 if you don't use Serial
const byte ButtonPin = 2;

const unsigned long BlinkInterval = 30000; // Thirty Seconds
const unsigned long BlinkLength = 2000; // Two Seconds

unsigned long StartOfInterval;

void setup()
{
  digitalWrite(LEDPin, LOW);
  pinMode(LEDPin, OUTPUT);
  pinMode(ButtonPin, INPUT_PULLUP); // Button from Pin to Gnd, LOW = pressed

  StartOfInterval = millis();
}

void loop()
{
  unsigned long currentMillis = millis();

  unsigned long elapsedMillis = currentMillis - StartOfInterval;

  if (elapsedMillis >= BlinkInterval)
  {
    StartOfInterval = currentMillis;
    elapsedMillis = 0;
  }

  if ((elapsedMillis < BlinkLength) || (digitalRead(ButtonPin) == LOW))
    digitalWrite(LEDPin, HIGH);  // LED On
  else
    digitalWrite(LEDPin, LOW);  // LED Off
}

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