Advertisement
safwan092

Order #9615

Jun 5th, 2022
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. #include <Servo.h>
  2.  
  3. #define echoPin 2
  4. #define trigPin 3
  5. #define servoPin 9
  6. #define buzzerPin 10
  7. #define ledPin 11
  8.  
  9. Servo myservo;
  10. long duration;
  11. int distance;
  12. int flag = 0;
  13.  
  14. //----------------------------------
  15. int alertTimes = 3;
  16. int alertDistance = 20; // 20 CM
  17. //----------------------------------
  18.  
  19. void setup() {
  20. Serial.begin(9600);
  21. Serial.println("Serial COM Test");
  22. pinMode(buzzerPin, OUTPUT);
  23. pinMode(ledPin, OUTPUT);
  24. pinMode(trigPin, OUTPUT);
  25. pinMode(echoPin, INPUT);
  26. myservo.attach(servoPin);
  27. myservo.write(0);
  28. digitalWrite(ledPin, 0);
  29. digitalWrite(buzzerPin, 0);
  30.  
  31. }
  32.  
  33. void loop() {
  34. US();
  35. if (distance < alertDistance && flag == 0) {
  36. myservo.write(90);
  37. alert();
  38. flag = 1;
  39. }
  40. delay(50);
  41. }
  42.  
  43.  
  44. void US() {
  45. digitalWrite(trigPin, LOW);
  46. delayMicroseconds(2);
  47. digitalWrite(trigPin, HIGH);
  48. delayMicroseconds(10);
  49. digitalWrite(trigPin, LOW);
  50. duration = pulseIn(echoPin, HIGH);
  51. distance = duration * 0.034 / 2;
  52. Serial.print("Distance: ");
  53. Serial.print(distance);
  54. Serial.println(" cm");
  55. }
  56.  
  57. void alert() {
  58. for (int i = 0; i < alertTimes; i++) {
  59. digitalWrite(ledPin, 1);
  60. digitalWrite(buzzerPin, 1);
  61. delay(1000);
  62. digitalWrite(ledPin, 0);
  63. digitalWrite(buzzerPin, 0);
  64. delay(1000);
  65. }
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement