IR obstacle avoidance error

Hello,

I'm trying to count the elapsed time between two obstacles. I've written this code, but nothing is showing up on the serial monitor, I think it might have to do with the var nOfTimes not being saved properly. Could you help me ?

code:

const int avoidPin = 7;
const int ledPin = 13;
int nOfTimes = 0;
long startTime;
long elapsedTime; // currentTime(millis) -start Time

void setup() {
pinMode(avoidPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
boolean avoidVal = digitalRead(avoidPin);

if(avoidVal == LOW){ // object detected
nOfTimes = nOfTimes +1;

}
if(avoidVal == LOW && nOfTimes == 1){ // detected for the first time
startTime = millis();
digitalWrite(ledPin, HIGH);
}
if(avoidVal == LOW && nOfTimes == 2){ // detected for the second time
elapsedTime = millis() - startTime;
Serial.println(" T = ");
Serial.println(elapsedTime);
digitalWrite(ledPin, LOW);
startTime = 0;
elapsedTime = 0;
nOfTimes = 0;
}

P.S = I'm using sunfounder's sensor, and the led is lighting up, so I don't think there's a problem with the sensor.

Please edit your post to add code tags. Post a link to the sensor and a wiring diagram.

Hi again,
I figured out what went wrong- sorry I just got to post this now. I didn't put a delay before the closure of the loop that corresponded to the amount of time the object would be in front of the sensor. And because of the nature of the sensor(continuously sending signals) it didn't realize that the object hadn't even moved.

Guess that just shows how good of a sensor it is, and that you have to really put yourself in place of the machine and what information it has. :slight_smile: :slight_smile:

Don't use delay() until you understand why you should not use delay(). Loop() function is a place you really should not use delay().

One problem: if the object lingers a little longer, it's still counted double. Use state change detection instead: count when the signal goes high (or low, depending on how your sensor works), not when it is high (or low).