safwan092

Untitled

Oct 15th, 2022
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.71 KB | None | 0 0
  1. #define trigPin 2
  2. #define echoPin 3
  3. #define motor 4
  4.  
  5. long duration;
  6. int distanceD;
  7.  
  8.  
  9. void setup() {
  10. pinMode(trigPin, OUTPUT);
  11. pinMode(echoPin, INPUT);
  12. pinMode(motor, OUTPUT);
  13. digitalWrite(motor, 0);
  14. Serial.begin(9600);
  15. }
  16.  
  17. void loop() {
  18. US();
  19. if (distanceD < 50) {
  20. digitalWrite(motor, 1);
  21. delay(1000);
  22. digitalWrite(motor, 0);
  23. }
  24. delay(100);
  25. }
  26.  
  27. void US() {
  28. digitalWrite(trigPin, LOW);
  29. delayMicroseconds(2);
  30. digitalWrite(trigPin, HIGH);
  31. delayMicroseconds(10);
  32. digitalWrite(trigPin, LOW);
  33. duration = pulseIn(echoPin, HIGH);
  34. distanceD = duration * 0.034 / 2;
  35. Serial.print("Distance: ");
  36. Serial.print(distanceD);
  37. Serial.println(" cm");
  38. }
Advertisement
Add Comment
Please, Sign In to add comment