Last active
October 15, 2019 17:54
-
-
Save MM-coder/5b8c1e09e274956a8e8243b085ade489 to your computer and use it in GitHub Desktop.
System to stop a traffic light when a "vehicle" gets too close
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int green = 2; | |
int yellow = 3; | |
int red = 4; | |
int trigPin = 5; | |
int echoPin = 6; | |
// ECHO to RX0 | |
long duration; | |
int distance; | |
// the setup function runs once when you press reset or power the board | |
void setup() { | |
// initialize digital pin LED_BUILTIN as an output. | |
pinMode(green, OUTPUT); | |
pinMode(yellow, OUTPUT); | |
pinMode(red, OUTPUT); | |
pinMode(trigPin, OUTPUT); | |
pinMode(echoPin, INPUT); | |
Serial.begin(9600); // Starts the serial communication | |
out_distance(); | |
} | |
// the loop function runs over and over again forever | |
void loop() { | |
// do_traffic(); | |
} | |
void do_traffic(){ | |
digitalWrite(green, LOW); | |
digitalWrite(red, HIGH); | |
delay(10000); | |
digitalWrite(red, LOW); | |
digitalWrite(yellow, HIGH); | |
delay(2000); | |
digitalWrite(yellow, LOW); | |
digitalWrite(green, HIGH); | |
delay(10000); | |
out_distance(); | |
} | |
void out_distance(){ | |
while (1 == 1) { | |
// Clears the trigPin | |
digitalWrite(trigPin, LOW); | |
delayMicroseconds(2); | |
// Sets the trigPin on HIGH state for 10 micro seconds | |
digitalWrite(trigPin, HIGH); | |
delayMicroseconds(10); | |
digitalWrite(trigPin, LOW); | |
// Reads the echoPin, returns the sound wave travel time in microseconds | |
duration = pulseIn(echoPin, HIGH); | |
// Calculating the distance | |
distance= duration*0.034/2; | |
// Prints the distance on the Serial Monitor | |
if (distance >= 1000) { | |
Serial.print("Anomaly, disregarding \n"); | |
} | |
if (distance <= 10) { | |
Serial.print("Getting close, traffic lights activating \n"); | |
do_traffic(); | |
} | |
else { | |
Serial.print("Distance: "); | |
Serial.println(distance); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment