#include <Servo.h>
// Pin definitions
const int GREEN_PIN = 11;
const int PUSH_BUTTON = 4;
const int TRIG = 6; // TRIG pin for ultrasonic sensor
const int ECHO = 5; // ECHO pin for ultrasonic sensor
// Timing variables
long previousMillis = 0;
long interval = 500; // Interval for toggling buzzer (if needed)
// Initial state for the button
bool buttonPressed = false;
void setup() {
// Initialize pin modes
pinMode(GREEN_PIN, OUTPUT);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(PUSH_BUTTON, INPUT);
// Start serial communication for debugging
Serial.begin(9600);
Serial.println("Train Crossing Active!");
}
// Function to get the distance from the ultrasonic sensor
long getDistance() {
// Send a pulse
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
// Variables to store time of the pulse
unsigned long startTime = 0;
unsigned long endTime = 0;
// Wait for the ECHO signal to go HIGH
unsigned long timeout = millis();
while (digitalRead(ECHO) == LOW) {
startTime = micros();
if (millis() - timeout > 50) return -1; // Timeout if no response
}
// Wait for the ECHO signal to go LOW
timeout = millis();
while (digitalRead(ECHO) == HIGH) {
endTime = micros();
if (millis() - timeout > 50) return -1; // Timeout if no response
}
// Calculate duration and convert to distance in cm
long duration = endTime - startTime;
return duration / 58; // Conversion factor for sound in air (us/cm)
}
// Function to turn on the green light
void greenLight() {
digitalWrite(GREEN_PIN, HIGH);
}
// Function to turn off all lights
void noLight() {
digitalWrite(GREEN_PIN, LOW);
}
void loop() {
// Check if the push button is pressed
if (digitalRead(PUSH_BUTTON) == HIGH && !buttonPressed) {
buttonPressed = true; // Mark button as pressed
}
if (buttonPressed) {
// Get the distance from the ultrasonic sensor
long distance = getDistance();
// Perform actions based on the measured distance
if (distance >= 90) {
// Distance is too far; no lights should be on
noLight();
} else if (distance > 40 && distance < 90) {
// Moderate distance; turn on green light
greenLight();
} else if (distance > 16 && distance <= 40) {
// Closer distance; turn off lights
noLight();
} else if (distance <= 15) {
// Very close; turn off lights (can be extended with buzzer if needed)
noLight();
}
}
}