const int trigPin = 11;
const int echoPin = 12;
void setup() {
Serial.begin(9600); // Start communication with your laptop
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
// 1. Send out the ultrasonic sound wave
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// 2. Measure the time it takes for the bounce to return
long duration = pulseIn(echoPin, HIGH);
// 3. Convert time to Centimeters (Speed of sound / 2)
int distance = duration * 0.034 / 2;
// 4. Print it to your laptop screen
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
delay(200); // Wait a fraction of a second before reading again
}