How to put a time constraint on a while statement

3477 views c++

I'm using an arduino nano and I want an accelerometer to trigger a relay after detecting free fall for a given time, lets say 1 second. I can get the freefall detection working, but how do I put a time constraint on the trigger?

Simply put my logic is this:

WHEN (In FreeFall) IF (1 second has Passed) Trigger something

Here is what I currently have:

while (event.acceleration.z < 0) // "while in freefall"

    unsigned long currentTime = millis(); //Set variable to current time

    if ((currentTime - Initial_Time) > Fall_Duration) //Initial_Time is a global variable initialized at 0
        Initial_Time = currentTime; //resets the timing

        digitalWrite(Relay, HIGH); //activate trigger

This code doesn't quite execute what I want. It basically loops the timer continually for 1 second interval. Whether or not the object is in freefall, if the loop has been running for 1 second it will trigger immediately then wait 1 second to trigger again if it detects freefall state.

Any ideas??

By the way, I don't write code nor am I a programmer of any sorts so please make an explanation for dummies :D

Thanks for any help!

answered question

Initial_Time is a global variable I suggest reconsidering this. Global variables make for brittle code. Use them when you have to, but do your best to avoid them. Passing Initial_Time into the function as a reference, eg int & init_time is likely a cleaner option.

1 Answer


Have you tried exploring the delay function in Arduino? This function sets the program to wait before it outputs the signal from sensor. In your case, you could just drop your if(1 second has passed) logic and instead do:

while (in free fall){

posted this

Have an answer?


Please login first before posting an answer.