Doubt in the code

I guys, it’s the first time i try to make a some simple code…
How can I make the code for an output to work, if the input is OFF and has previously been ON for at least 10 seconds (that is, make sure that the output is only triggered, if the input has been at least 10 seconds on, previously).

thanls :slight_smile:

enum { Off = HIGH, On = LOW };

#define Interval 3000L

const  byte  pinBut = A1;
const  byte  pinLed = 10;

unsigned long msecLst = 0;
unsigned long msec;

// -----------------------------------------------------------------------------
void
setOutput ()
{
    digitalWrite (pinLed, On);

    msecLst = millis ();
}

// -----------------------------------------------------------------------------
void setup()
{
    Serial.begin (9600);
    digitalWrite (pinLed, Off);
    pinMode      (pinLed, OUTPUT);

    pinMode      (pinBut, INPUT_PULLUP);
}

// -----------------------------------------------------------------------------
void loop()
{
    msec = millis ();

    // check for button change and press
    static byte butLst = Off;
    byte but = digitalRead (pinBut);
    if (butLst != but)  {
        butLst = but;
        if (On == but)
            setOutput ();
    }

    // turn off LED after Interval
    if ( (0 < msecLst) && ((msec - msecLst) > Interval))  {
        msecLst = 0;
        digitalWrite (pinLed, Off);
    }
}
1 Like
// How can I make the code for an output to work, if the
// input is OFF and has previously been ON for at least
// 10 seconds

const byte InputPin = 2;
const byte OutputPin = LED_BUILTIN;

unsigned long TimeLastOff = 0;

void setup()
{
  pinMode(InputPin, INPUT_PULLUP);
  pinMode(OutputPin, OUTPUT);
}

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

  if (digitalRead(InputPin) == LOW)
  {
    // If the input has been HIGH for 
    // at least 10 seconds before going LOW
    if (currentMillis - TimeLastOff >= 10000UL)
      digitalWrite(OutputPin, HIGH);
      
    TimeLastOff = currentMillis;
  }
}
1 Like

thank you so much , that’s it :smiley:

by the way, can you tell me how to reset everything with just a click on the button?

I would really appreciate it

Rui Silva

Just use digitalWrite(OutputPin, LOW); to reset everything.

the code i provided does that. it calls setOutput () which captures the timestamp at the time the output is set (i think john’s approach, which is a good approach, resets the timer when the output is reset (off))

Thanks for the support Jonh , i really aprecciate,

Can you help me with another simple situation please?

I now have another output (a 12v led strip, on which I will use a relay to act) and I want the arduino to be able to control it …
I want this new output to be always on … and only starts to flash when the other output (the first one) is working (that means , INPUT OFF) :wink:
Thanks :smiley:

What have you tried?

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