//Include servo library:
#include <Servo.h>
//Create the servo object:
Servo SM; //'SM' from Servo Motor!...
//Declare the pins to which servo and potentiometer is connected.
const int servoPin = 7;
//Define HC-SR04 & other variables!
#define echoPin 2 //attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
long duration; //variable for the duration of sound wave travel
int distance; //variable for the distance measurement
int RLED1 = 7; //Green LED...
int RLED2 = 6; //Yellow LED...
int White_LED = 5; //Red LED...
int Buzzer = 12;
void setup(){
pinMode(RLED1, OUTPUT);
pinMode(RLED2, OUTPUT);
pinMode(White_LED, OUTPUT);
pinMode(trigPin, OUTPUT); //Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); //Sets the echoPin as an INPUT
pinMode(Buzzer, OUTPUT);
//Attach SM to pin 4 to the Arduino UNO board!
SM.attach(4);
}
void loop(){
//Clears the trigPin condition
digitalWrite(trigPin, LOW);
delay(100);
//Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delay(100);
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; //Speed of sound wave divided by 2 (go and back)
if(distance < 10){
SM.write(90);
digitalWrite(White_LED, LOW);
digitalWrite(RLED1, HIGH);
digitalWrite(RLED2, LOW);
delay(1000);
digitalWrite(RLED1, LOW);
digitalWrite(RLED2, HIGH);
delay(1000);
}
if(distance >= 10 && distance <= 100){
SM.write(90);
digitalWrite(White_LED, LOW);
digitalWrite(RLED1, HIGH);
digitalWrite(RLED2, LOW);
tone(Buzzer, 800, 400);
delay(1000);
digitalWrite(RLED1, LOW);
digitalWrite(RLED2, HIGH);
tone(Buzzer, 800, 400);
delay(1000);
}
if(distance > 100){
SM.write(0);
digitalWrite(RLED1, LOW);
digitalWrite(RLED2, LOW);
digitalWrite(White_LED, HIGH);
delay(2000);
digitalWrite(White_LED, LOW);
delay(2000);
}
}