const int trigPin = 15;
const int echoPin = 2;
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(26, OUTPUT);
pinMode(25, OUTPUT);
pinMode(33, OUTPUT);
pinMode(32, OUTPUT);
pinMode(4, OUTPUT);
}
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);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
if(distanceCm > 50.0){
digitalWrite(26, HIGH);
digitalWrite(25, LOW);
digitalWrite(32, LOW);
digitalWrite(33, LOW);
}
if(distanceCm > 100.0){
digitalWrite(26, HIGH);
digitalWrite(25, HIGH);
digitalWrite(32, LOW);
digitalWrite(33, LOW);
}
if(distanceCm > 200.0){
digitalWrite(26, HIGH);
digitalWrite(25, HIGH);
digitalWrite(32, HIGH);
digitalWrite(33, LOW);
}
if (distanceCm > 300.0){
digitalWrite(26, HIGH);
digitalWrite(25, HIGH);
digitalWrite(32, HIGH);
digitalWrite(33, HIGH);
digitalWrite(4, HIGH);
delay(500);
}
digitalWrite(4, LOW);
delay(500);
}