I am trying to program a photogate whereby you slide a business card down the center of a breadboard and calculate the speed in miles per hour - based on the time when the first photogate is blocked and the time the second one is blocked - they will both be blocked at the same time.
The problem is that if I keep both blocked, it keeps returning values even after it does the calculations one time.
I'm trying to use the break command but maybe I'm using it incorrectly.
What am I doing wrong and how do I fix it?
float distance =2.75;
int ledStart = 8;
int ledEnd = 9;
int gate1 = 0;
int gate2 = 0;
long starttime=0;
long endtime=0;
float velocity = 0;
long timeDiff = 0;
float milesPerHour=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledStart,OUTPUT); //set led pins as output
pinMode(ledEnd, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(ledStart,HIGH); //turn and keep light on
digitalWrite(ledEnd, HIGH);
gate1 = analogRead(A1);
gate2 = analogRead(A2);
if ((gate1 < 600) && (gate2 > 600)); // gate 1 is blocked and gate 2 is clear
starttime =millis();
while (gate1 < 600) { //as long as gate 1 is blocked check gate 2
if (gate2 <600) { //if gate 2 is also blocked
long endtime= millis(); //record how long till gate 2 got blocked
timeDiff =endtime-starttime; //calculate time difference
velocity = distance / timeDiff; // calculate speed in inches / millisecond
milesPerHour = velocity * 58.82; // convert to miles/hour
Serial.println (starttime); //print times and speed
Serial.println (endtime);
Serial.println (timeDiff);
Serial.print ("The speed is: ");
Serial.print(milesPerHour,6);
Serial.println (" miles per hour");
break;
}
gate1 = analogRead(A1);
gate2 = analogRead(A2);
}
}