I need a help from anybody who can help me. when an input ON (remain ON) the output should ON for 10 second and OFF (remain OFF), when an input changes to OFF (remain OFF) no changes in output, it is remain OFF position. (The output ON for 10 second only if the input ON.)
Look at the StateChangeDetection example (File->examples->02.Digital->StateChangeDetection) and you will learn how to detech when a button/switch changes from On -> Off or Off->On rather than just knowing if it is on or off. This will help you accomplish your goal.
Try it. If you get stuck, read the sticky post at the top of the forum and post your code properly (use code tags) and people will help you.
From my different search and experiment, I got this way ,but it not solve my problem, please see below code and help me.
int pin = 2;
int led = 13;
void setup()
{
pinMode(pin, INPUT_PULLUP);
pinMode(led, OUTPUT);
attachInterrupt(0, isr, FALLING);
}
volatile long last = 0;
volatile bool turnOff = false;
volatile long offAt = 0;
void isr()
{
if( (millis() - last ) > 20 ) //if at least 20 ms has passed since last press, this is not a dup
{
last = millis(); //note the time, for ignoring duplicate presses
turnOff = true;
offAt = millis() + 2000; //save a variable of now + 5 seconds
digitalWrite(led, HIGH); //turn on
}
}
void loop()
{
if(turnOff)
{
if(millis() >= offAt)
{
digitalWrite(led, LOW); //turn off led
}
}
}
In addition to Robin2's comments, your time variables need to be 'unsigned long' so the math will work correctly if/when millis() rolls over, back to 0.
You will also run into the same problem when trying to compute a time in the future
offAt = millis() + 2000
You should only ever subtract a past time from the current time to measure elapsed time.