const int GREEN_PIN = 17;
const int YELLOW_PIN = 18;
const int RED_PIN = 19;
const int TRIG = 20; //..We are setting the TRIG on the ultrasonic sensor to port 23
const int ECHO = 21;
void setup() {
// put your setup code here, to run once:
pinMode(GREEN_PIN, OUTPUT);
pinMode(YELLOW_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
pinMode(TRIG, OUTPUT); // TRIG pin as output
pinMode(ECHO, INPUT); // ECHO pin as input
Serial.begin(9600);
Serial.println("Train Crossing Active!");
}
//define a function that is called get distance gets distance of ultrasonic wave that is sent
long getDistance()// #define a function that is called get distanc
{
digitalWrite(TRIG, HIGH); //) #set the gpio pin to a high value or 1
delayMicroseconds(10);//#sleeps or waits for 1 micro second
digitalWrite(TRIG, LOW);
unsigned long int startTime = 0;
unsigned long int endTime = 0;
long signal_of_utrasonic_distance_sensor;
long distance_traveled_soundwave;
while(digitalRead(ECHO)==LOW) //if the input ro echo is false or off
{ //get the time in seconds sinec echo, the echo is where the time starts
startTime = micros(); //record the start time
} //it contonously resest while echo is false
while(digitalRead(ECHO)==HIGH)
{
endTime = micros(); //this lets the time since the echo
}//it continously resets while echo is true
//distance in cm is equal to
signal_of_utrasonic_distance_sensor = endTime - startTime; //This is the total time elpased since the sound wave was outputed
distance_traveled_soundwave = signal_of_utrasonic_distance_sensor/0.000058; //inches 0.000148 maybe 58 instead
return distance_traveled_soundwave;
}
//This is what the output should be when the function green light is to be run
void greenLight()
{
digitalWrite(GREEN_PIN, HIGH); //turn will turn on green light
digitalWrite(YELLOW_PIN, LOW); //turn the yellow led off
digitalWrite(RED_PIN, LOW); //turn the red led off
}
void yellow_light()
{
digitalWrite(GREEN_PIN, LOW); // Turn off green light
digitalWrite(YELLOW_PIN, HIGH); // Turn on yellow light
digitalWrite(RED_PIN, LOW); // Turn off red light
}
void red_light()
{
digitalWrite(GREEN_PIN, LOW); // Turn off green light
digitalWrite(YELLOW_PIN, LOW); // Turn off yellow light
digitalWrite(RED_PIN, HIGH); // Turn on red light
}
void no_light()
{
// Ensure all lights and buzzer are off
digitalWrite(GREEN_PIN, LOW);
digitalWrite(YELLOW_PIN, LOW);
digitalWrite(RED_PIN, LOW);
}
void loop()
{
// put your main code here, to run repeatedly:
long distance = getDistance();
// start the crossing guard actions
if(distance >=90)
{
no_light();
}
else if(23 < distance <90)
{
greenLight();
}
else if(16 < distance < 22)
{
yellow_light();
}
else if(distance <=15)
{
red_light();
}
}