// Define the pins to be used const int trigPin = 2; // Output pin of the ultrasonic sensor const int echoPin = 3; // Input pin of the ultrasonic sensor // Define variables to store the times long duration; int distance; void setup() { // Initialize the pins as input or output pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); // Initialize serial communication Serial.begin(9600); } void loop() { // Send a 10-microsecond pulse to the output pin digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); // Measure the time it takes for the echo to arrive duration = pulseIn(echoPin, HIGH); // Calculate the distance in centimeters distance = duration * 0.034 / 2; // Print the distance to the serial console Serial.print("Distance: "); Serial.print(distance); Serial.println(" cm"); // Wait a moment before repeating delay(1000); }