Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int redled = 8;
- int yellowled = 7;
- int greenled = 6;
- const int trigPin = 9;
- const int echoPin = 10;
- long duration;
- int distance;
- void setup() {
- pinMode(redled, OUTPUT);
- pinMode(yellowled, OUTPUT);
- pinMode(greenled, OUTPUT);
- pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
- pinMode(echoPin, INPUT); // Sets the echoPin as an Input
- Serial.begin(9600); // Starts the serial communication
- }
- void loop() {
- // 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;
- Serial.print("Distance: ");
- Serial.println(distance);
- if (distance <= 30){ //this
- digitalWrite(redled, LOW);
- digitalWrite(yellowled, LOW);
- digitalWrite(greenled, HIGH);
- }
- if (distance <= 20){ //this
- digitalWrite(redled, LOW);
- digitalWrite(yellowled, HIGH);
- digitalWrite(greenled, LOW);
- }
- if (distance <= 10){ //this
- digitalWrite(redled, HIGH);
- digitalWrite(yellowled, LOW);
- digitalWrite(greenled, LOW);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement