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.