#include <Servo.h>
// Pin definitions
const int GREEN_PIN = 11;
const int YELLOW_PIN = 12;
const int RED_PIN = 13;
const int BUZZER_BUTTON = 8; // Buzzer connected here
const int PUSH_BUTTON = 4;
const int TRIG = 6; // Ultrasonic sensor TRIG pin
const int ECHO = 5; // Ultrasonic sensor ECHO pin
/*Thiss function activates the buzzer when the distance is less than 15cm*/
// Timing variables
long previousMillis = 0;
long interval = 500; // Duration the buzzer stays on/off (in milliseconds)
// State variables
bool buttonPressed = false;
// Servo setup
Servo myServo1, myServo2; // Cross guard servos (not used here)
// Function to calculate distance using ultrasonic sensor
long getDistance() {
digitalWrite(TRIG, HIGH); // Send a 10-microsecond pulse
delayMicroseconds(10); // Short delay
digitalWrite(TRIG, LOW); // Stop the pulse
unsigned long startTime = 0;
unsigned long endTime = 0;
// Wait for ECHO to go HIGH and record the start time
unsigned long timeout = millis();
while (digitalRead(ECHO) == LOW) {
startTime = micros();
if (millis() - timeout > 50) return -1; // Timeout if no response
}
// Wait for ECHO to go LOW and record the end time
timeout = millis();
while (digitalRead(ECHO) == HIGH) {
endTime = micros();
if (millis() - timeout > 50) return -1; // Timeout if signal is stuck
}
// Calculate the pulse duration and convert to distance
long duration = endTime - startTime;
return duration / 58; // Convert microseconds to centimeters
}
void setup() {
// Initialize serial communication
Serial.begin(9600);
Serial.println("Train Crossing Active!");
// Configure pins
pinMode(BUZZER_BUTTON, OUTPUT);
pinMode(PUSH_BUTTON, INPUT);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
}
void loop() {
// Detect button press to activate the system
if (digitalRead(PUSH_BUTTON) == HIGH && !buttonPressed) {
buttonPressed = true; // Record that the button has been pressed
}
if (buttonPressed) {
// Measure distance
long distance = getDistance();
Serial.print("Distance: ");
Serial.println(distance);
// Decide actions based on distance
if (distance >= 90) {
noTone(BUZZER_BUTTON); // No action, turn buzzer off
} else if (distance > 40 && distance < 90) {
noTone(BUZZER_BUTTON); // No action, turn buzzer off
} else if (distance > 16 && distance <= 40) {
noTone(BUZZER_BUTTON); // No action, turn buzzer off
} else if (distance <= 15) {
// Activate the buzzer only when distance <= 15 cm
if (millis() - previousMillis > interval) {
tone(BUZZER_BUTTON, 500); // Set buzzer tone at 500 Hz
previousMillis = millis(); // Reset the timer
}
}
}
}