How to check if a condition is true only for the first time

Hey
I want to save information when a condition is checked and found to be true but I only want to save the information the first time the condition happened.
In my case, I want to store the time when a motor (with encoder) reaches the target position for the first time. If it reaches, then I want to save the reaching time, and if it reaches again I want my saved time to remain the same as the first time the motor reaches the target position.
I tried this code:

if (pos == target); {
      targetAchive = 1;
      targetTime = millis();
      targetAchive = 0;
    }

but if the motor overshoots the target position and returns for the second time to the target position - the "targetTime" get changed.
Thanks

bool firstTime = true;
...
if (pos == target and firstTime == true) {
      targetAchive = 1;
      targetTime = millis();
      targetAchive = 0;
      firstTime = false;
    }

Your code has a bug, there should be no semicolon after the if statement, just a brace {.

Also you have contradictory code, targetAchive always gets set to 0 after it is set to 1. So the first line does nothing. Not sure what you are trying to do.

Hi,

I think this will do what you require:

  if (pos == target && targetAchive == 0) {
      targetTime = millis();
      targetAchive = 1;
    }

Welcome to the forum.

Study state machines. The Boolean provided is the most basic of these. The principle is important.

this code never will do what you expected because the semicolon after the condition.

good spotting.

but bit late... may be :slight_smile:

Thank you
I tried your solution and its worked.

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