const int trigPin = 3;
const int echoPin = 2;
long duration;
int distinCM;
// Function to measure distance using the ultrasonic sensor
int distance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distinCM = duration * 0.034 / 2;
return distinCM;
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(7, OUTPUT); // Pin for first LED
pinMode(8, OUTPUT); // Pin for second LED
pinMode(9, OUTPUT); // Pin for third LED
Serial.begin(9600); // Start the serial communication for debugging
}
void loop() {
int dist = distance();
Serial.print("Distance: ");
Serial.print(dist);
Serial.println(" cm");
if (dist <= 10) { // Check if the distance is 10 cm or less
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
} else {
digitalWrite(7, LOW);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
}
delay(500); // Add a delay to avoid overwhelming the sensor and serial monitor
}
No comments:
Post a Comment