/*
Project: Break-beam Timer
Description: Measure the time it takes for an
object to travel from A to B.
"j" triggers Start, "k" triggers the "IR beam"
Creation date: 10/23/23
Author: AnonEngineering
From a question by:
ichiko aoba's cat
Discord Arduino #coding-help 10/23/23 6:13PM
License: https://en.wikipedia.org/wiki/Beerware
*/
#include <Servo.h>
const int SERVO_PIN = 3;
const int BTN_PIN = 5;
const int IR_PIN = 4;
const int CLOSE_ANGLE = 0;
const int OPEN_ANGLE = 180;
const unsigned long RELEASE_DELAY = 10;
Servo gateServo; // create servo object
bool checkButton() {
static bool oldBtnState = true; // INPUT_PULLUP idles high
bool isButtonPressed = false;
int btnState = digitalRead(BTN_PIN);
if (btnState != oldBtnState) { // if the button changed
oldBtnState = btnState; // remember new state
if (btnState == LOW) { // and it's now LOW
isButtonPressed = true;
//Serial.println("Button pressed");
} else {
//Serial.println("Button released");
}
delay(20); // for debounce
}
return isButtonPressed;
}
void checkIR() {
while (digitalRead(IR_PIN)) {
// do nothing until the beam breaks
};
}
void closeGate() {
gateServo.write(CLOSE_ANGLE);
}
void openGate() {
gateServo.write(OPEN_ANGLE);
}
void setup() {
Serial.begin(9600);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(IR_PIN, INPUT_PULLUP);
gateServo.attach(SERVO_PIN);
gateServo.write(CLOSE_ANGLE); // initial position
delay(500);
Serial.println("System ready");
}
void loop() {
int btnState = checkButton();
if (btnState) { // the button was pressed
openGate();
delay(RELEASE_DELAY); // mechanical gate delay
unsigned long startTime = millis();
checkIR(); // this function blocks until IR triggers
unsigned long stopTime = millis();
unsigned long duration = stopTime - startTime;
Serial.print("Stop time:\t");
Serial.print(stopTime);
Serial.println(" ms");
Serial.print("Start time:\t");
Serial.print(startTime);
Serial.println(" ms");
Serial.print("Duration:\t");
Serial.print(duration);
Serial.println(" ms");
Serial.println();
closeGate();
delay(500);
Serial.println("System ready");
}
}