// https://create.arduino.cc/projecthub/madhav133/light-gate-using-arduino-de846c?ref=platform&ref_id=424_trending___&offset=21
int timer = 0; //For the counting of the breaked time of light.
bool checking = false; //Checks if the the object is being monitored.
float speed = 0; //The final speed of the object.
float lengthOfBreaker = 0.04; //The length of the breaker used in the object.
void setup() {
pinMode(8, OUTPUT); //An LED for showing the 'checking' variable.
Serial.begin(9600); //Begin the serial communication.
}
void loop() {
if (analogRead(A0) < 900) { //Checks if the light intensity is below 900. That means the light is breaked.
checking = true;
digitalWrite(8, checking);
timer = 0;
while (analogRead(A0) <= 900) { //Increment the timer until the object is gone.
timer++;
delay(1); //A fixed time of 1 millisecond is given for counting.
}
if (timer > 0) { //Check if the timer value is greater that 0 milliseconds.
checking = false; //Set the completed variable to true since the checking is completed.
digitalWrite(8, checking);
float timeInSec = (float(timer) / float(1000)); //Convert the time in milliseconds to seconds. Output is a float value.
speed = lengthOfBreaker / timeInSec; //Calculates the speed of the object by using this formula: Speed = Distance / Time
Serial.print("Object Instantaneous Speed: "); //
Serial.print(speed); // Print the object speed
Serial.print(" m/s"); // in the Serial monitor.
Serial.print("\n"); //
timeInSec = 0; // Reset the seconds value.
}
speed = 0; //
checking = false; // Reset other values too.
timer = 0; //
}
}