Min/Max detection

This routine will be useful where you need to take readings from any sensor and use the previous reading as a comparison for an action to be taken. Nothing special about this.

I use an LDR connected in a voltage divider configuration to pin A0.

/*
This application will read the light level from the LDR
on power-up and will use that initial value as the first reference
for the min/max light levels.
It will then continually compare that initial stored value
with the next reading and update the min/max levels accordingly
*/

int ldr=A0;
int tempmin,tempmax;
int initreading;

void setup()
{
Serial.begin(9600);
pinMode(ldr,INPUT);
delay(200);
initreading=analogRead(ldr); // take an initial reading
tempmin=initreading; // assign the initial reading to the min
tempmax=initreading; // and the max readings
Serial.print("Initial light level: ");
Serial.println(initreading);
Serial.println("This is lux(min) and lux(max)");
}

void loop()
{
int reading=analogRead(ldr);
delay(1000);

if (reading<tempmin)
{
tempmin=reading;

Serial.print("New minimum of: ");
Serial.print(reading);
Serial.println(" read from the sensor");
}
if (reading>tempmax)
{
tempmax=reading;
Serial.print("New maximum of: ");
Serial.print(reading);
Serial.println(" read from the sensor");
}
else
{
Serial.print("Current mimimum is: ");
Serial.print(tempmin);
Serial.print(" and the maximum is: ");
Serial.print(tempmax);
Serial.print(" with a current lux of: ");
Serial.println(reading);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *