Triggering loops?

Hi, I want to make a code that does the following:

I have certain analog channels connected to my Arduino (with some sensors)

I want to make it so that when certain channel reaches X value (sensor senses whatever) it will trigger a function, and then when that value reaches certain treshold again (sensor senses whatever again), it will stop doing the loop. I assume the shutdown technique would be to use a while loop,
while value < X
{
do loop
}

but then I dont know how to activate it for the first time? should it be with an IF loop? but if so will they be "sequential" or would they instantly start/end since the value was reached for an instant

I was thinking something like (incorrect syntax, just get the idea)

If value > X
{
delay (300)

while ( X< value)
{
do certain things
}
delay (300)
}

(I am using the delays to avoid the instant on/off
but I am not sure if this would work.

If you use a while loop then code that is not in the loop will execute while the loop condition is true. For instance if one of the analogue channel readings goes above its threshold then no other channels will be read until the reading goes below the threshold. Is that acceptable ?

Using an if (it's not a loop by the way) then you can take actions if one of the analogue channel readings goes above its threshold then move on to test the next one and take action if required. The next time the first condition is checked the same sequence will be executed.

The difference between the two approaches is that the first is 'blocking' code whilst the second is not. Which is more appropriate to your circumstances is up to you to decide.

I want to make it so that when certain channel reaches X value (sensor senses whatever) it will trigger a function, and then when that value reaches certain treshold again (sensor senses whatever again), it will stop doing the loop.

You can use loop() to do repeated actions and within loop, trigger which actions to perform.

You can trigger by elapsed time, sensor input, serial input, and whatever else you can get to run. XD

You can use a process state approach and use 1 or more state variable(s) that trigger one process that when it's done, it sets the state to trigger the next step in the process.

So you have state changes

  • when certain channel reaches X value
  • when that value reaches certain treshold again

So states:
State 10 (no rule says start anywhere) is where you watch for X and when you get X you change the process state to 20.
State 20 is where you watch for the certain threshold and if it's not then give the matching function a turn of the handle but no more, do not block or hog cycles unless it's vital, state 20 will likely run again in microseconds.

The matching function should be written like the inside of a loop, it gets called repeatedly during its duty cycle.
If there's anywhere in that that needs to wait on time or event, make sure it doesn't block or hog.

Is that general enough?