Hi,
I am new to the programming and I have a question about the if statements. Is it possible to check a condition for a certain amount before deciding true or false?
For example
If (x=0) {
digitalWrite(13, high)
}
In this code, even if the x is 0 for a milisecond , it runs the code. What I want the program to do is to run the code if the condition(x=0 in this case) is true for 2 seconds.
If you want to make as sure as possible that a certain condition is true for an x amount of time such as a pin input either you need to use an interrupt (which is probably a tad more than you will want to do as a beginner) or not run an aSync task so creating a function like
Mmarya:
I am new to the programming and I have a question about the if statements. Is it possible to check a condition for a certain amount before deciding true or false?
The short answer is YES. However the details depend on exactly what you want to achieve. We need more information.
The demo Several Things at a Time illustrates the use of millis() to manage timing without blocking. It may help with understanding the technique.
Mmarya:
What I want the program to do is to run the code if the condition(x==0 in this case) is true for 2 seconds.
I find that the easiest way is to restart a timer every time the condition is false. If the timer reaches the desired interval then the condition has been true for that long:
unsigned long LastTimeConditionWasFalse;
void loop()
{
if (x != 0)
{
LastTimeConditionWasFalse = millis();
}
if (millis() - LastTimeConditionWasFalse >= 2000)
{
// Condition (x==0) has been true for two seconds
// Put your code here
}
}
If you want it to trigger only after the condition has been false at least once:
unsigned long LastTimeConditionWasFalse = 0;
void loop()
{
if (x != 0)
{
LastTimeConditionWasFalse = millis();
}
if (LastTimeConditionWasFalse != 0 && millis() - LastTimeConditionWasFalse >= 2000)
{
// Condition (x==0) has been true for two seconds
LastTimeConditionWasFalse = 0; // Prevent re-triggering until the condition goes false again
// Put your code here
}
}