how to execute a code just once after crossing a thresholds

Hello friends.

I am measuring a value. Now i want to add a logile to my project.

So basic idea: Everytime a given thresholds is crossed, a logfile should be written.
In my "code-planing" i am facing the following problem.
Lets say my thresholds is 10. I am currently measuring a value that is lets say 12.
My first idea was something like this

if(currentvalue < 10)
{
...write loggile ....
}

obviously wrong. Because it would write me a logfile the whole time as long the value is < 10

Next idea:

if(currentvalue == 10)
{
...write loggile ....
}

is also far from perfect, becauce it is not always guaranteed that the measured value == 10. Becauce when the value changes to fast, it could be the case that the value 10 is skipped.

Adding a range of values into my if statement is possibly also not the right why, because it could be the case that the measured value will be in this range and i have the same problem like i mentioned above.

So the last idea that crossed my mind is something like this:

if(currentvalue < 10)
{
...execute a code that writes a logfile just once...
}

So i am a bit uninspired how to realize this idea IF the idea is the best

Someone has an idea or every faced the same problem?

Thank you

Use a boolean variable to control when data is written to the file

Set the boolean, let's name it okToWrite to false and write code to write to the file when the boolean is true and set it to false after writing. Now, when the threshold becomes exceeded set the boolean to true and the write will only happen once

Keep a variable with the previous value you read, prevValue perhaps. When checking whether to log, only log if previous was one side of the threshold and current is on the other.

thank you for the answers:

you wrote:

Use a boolean variable to control when data is written to the file
Set the boolean, let's name it okToWrite to false and write code to write to the file when the boolean is true and set it to false after writing. Now, when the threshold becomes exceeded set the boolean to true and the write will only happen once

But when i do something like this (simplified)

bool okToWrite = false;

if(currentvalue < 10)
{ 
  okToWrite = true
}


and i have a function like

void writelog()
{
 if(okToWrite)
{
  ...write logfile...;
   okToWrite = false;
}}

To check if the value is < 10, the if statement must be in the loop.

So the problem is see now is: after i write the logfile, okToWrite will be set to false. BUT, since the value is still < 10 the okToWrite will be set again to true and another logfile will be written and so on.

Or do i miss something?

Thank you

since the value is still < 10 the okToWrite will be set again to true and another logfile will be written and so on.

Or do i miss something?

You missed something.

I wrote
when the threshold becomes exceeded. That is not the same as when the threshold is exceeded

See also reply #2