Help with conditional code - check A0 same or less for time before continuing

Hi All

Scenario: I am setting up a night-time home lighting curcuit using Arduino using several PIR sensors, and relays to control hidden LED strip lights etc. Now, I only want the entire circuit to become operational when the ambient light level has fallen below a certain threshold. However, the value of the analog reading might fluctuate slightly around a value for a few mins as the ambient light decreases i.e. the value might be something like 100, 99, 99, 98, 99, 98, 98,97 etc... so falling over time yes, but it might rise by a value too.

So, I want to be able to write some code that will check that the analoge reading is below a certain threshold AND has been for several minutes - before I then proceed with the rest of the code.

A WHILE statement would do it, but how do I code the expression? How do I check that a value on say, A0, is dropping AND has been at value 'v' or less, for 't' time please?

Just can't get my head around it!


Don't use a while loop as this will lock the program into the loop. That may seem to be what you want but it would be better to use the loop() function to do what you want as then the program can run freely and possibly do other things.

So, how to do it ? When the start condition is met, ie the light level falls below the threshold, save the value of millis() and set a boolean variable, maybe named timing, to true. Then, each time through loop() check whether the current value of millis() minus the start time is greater than the required interval. If it is and the timing variable is true then do whatever you need to control the LEDs. If, at any time when timing is true the light level goes above the threshold set it back to false and save the start time from millis() again to restart the timing process.

Thanks for the WHILE suggestion - good advice, cheers!

Damn you Bob - you make it sound so so easy :slight_smile: :slight_smile: (then again, I guess it is really!!). Thanks... will work on using this in my code.

I have the LED's already, but the majority of the kit (PIR's, Relay module) arriving tomorrow and so will be making a start on the code pretty much straight away.

Another way to deal with the issue is to only read the light sensor once every n seconds, minutes, hours, etc.

If the idea is to start the process when it gets dark, and stop it when it gets light, reading the sensor every 10 minutes should be often enough. Then, if it is getting darker, a lower reading 10 minutes later is not going to restart the show, and it is unlikely to be lighter 10 minutes later.