I am trying to program my arduino uno to switch on an LED when an object is at a certain range from an IR sensor for more than 2 seconds and to shut off as soon as the object moves out of this determined range. It should also be able to switch the LED on again if the object is in the required range for more than 2 seconds.
The code that I have placed here has been my best attempt of about 200 different variations. The problem is that once the object is within the correct range my sensor will actually turn on the LED but once the object moves out of range the while loop keeps running... (and i keeps increasing by 1 obviously)
I tested this code several times using a potentiometer and a threshold value and it worked fine... If you need any more information let me know.
// These constants won't change:
const int analogPin = A0; // pin that the sensor is attached to
const int ledPin = 13; // pin that the LED is attached to
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communications:
Serial.begin(9600);
}
void loop() {
float analogValue = analogRead(analogPin);
int i;
i=0;
float voltage=analogValue*.00488;
// if the analog value is high enough, start adding to i:
while (voltage > 1.85 && voltage<1.96) {
i=i+1;
Serial.println(i);
analogValue = analogRead(analogPin);
float voltage=analogValue*.00488;
delay(1000);
Serial.println(voltage,2);
if (i>2){
digitalWrite(ledPin, HIGH);
}
}
if (i==0){
digitalWrite(ledPin, LOW);
Serial.println(voltage,2);
delay(1000);
}
}