Advertisement
chowdhury_riham

Sonar sensor sample code

Nov 17th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. // defines pins numbers
  2. const int trigPin = 9;
  3. const int echoPin = 10;
  4. // defines variables
  5. long duration;
  6. int distance;
  7. void setup() {
  8. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  9. pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  10. Serial.begin(9600); // Starts the serial communication
  11. }
  12. void loop() {
  13. // Clears the trigPin
  14. digitalWrite(trigPin, LOW);
  15. delayMicroseconds(2);
  16. // Sets the trigPin on HIGH state for 10 micro seconds
  17. digitalWrite(trigPin, HIGH);
  18. delayMicroseconds(10);
  19. digitalWrite(trigPin, LOW);
  20. // Reads the echoPin, returns the sound wave travel time in microseconds
  21. duration = pulseIn(echoPin, HIGH);
  22. // Calculating the distance
  23. distance= duration*0.0347/2;
  24. // Prints the distance on the Serial Monitor
  25. Serial.print("Distance: ");
  26. Serial.println(distance);
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement