Advertisement
zoro-10

Ultrasonic sensor

Apr 1st, 2024 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. https://imgur.com/a/TWiO6FY
  2.  
  3.  
  4. // Define the pins for the ultrasonic sensor
  5. const int trigPin = 9; // Arduino digital pin for the trigger
  6. const int echoPin = 10; // Arduino digital pin for the echo
  7.  
  8.  
  9. // Variables to store the duration and distance
  10. long duration;
  11. int distance;
  12. void setup()
  13. {
  14.   // Initialize serial communication for debugging
  15.   Serial.begin(9600);
  16.   pinMode(trigPin, OUTPUT);
  17.   pinMode(echoPin, INPUT);
  18. }
  19. void loop()
  20. {
  21.   // Trigger a pulse to the sensor
  22.   digitalWrite(trigPin, LOW);
  23.   delayMicroseconds(2);
  24.   digitalWrite(trigPin, HIGH);
  25.   delayMicroseconds(10);
  26.   digitalWrite(trigPin, LOW);
  27.   // Measure the duration of the pulse from the echo
  28.   duration = pulseIn(echoPin, HIGH);
  29.   // Calculate the distance based on the speed of sound
  30.   distance = duration * 0.034 / 2; // Divide by 2 because the sound travels to the object and back
  31.                                    // Print the distance to the serial monitor
  32.   Serial.print("Distance: ");
  33.   Serial.print(distance);
  34.   Serial.println(" cm");
  35.   // Add a delay between measurements
  36.   delay(1000); // 1 second
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement