Advertisement
safwan092

Untitled

Mar 13th, 2023
20
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 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(90);
  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(0);
  37. alert();
  38. flag = 1;
  39. delay(300000); // 5 min = 300000 mS | 1 min = 60000 mS
  40. }
  41. else{
  42. myservo.write(90);
  43. flag = 0;
  44. }
  45. delay(50);
  46. }
  47.  
  48.  
  49. void US() {
  50. digitalWrite(trigPin, LOW);
  51. delayMicroseconds(2);
  52. digitalWrite(trigPin, HIGH);
  53. delayMicroseconds(10);
  54. digitalWrite(trigPin, LOW);
  55. duration = pulseIn(echoPin, HIGH);
  56. distance = duration * 0.034 / 2;
  57. Serial.print("Distance: ");
  58. Serial.print(distance);
  59. Serial.println(" cm");
  60. }
  61.  
  62. void alert() {
  63. for (int i = 0; i < alertTimes; i++) {
  64. digitalWrite(ledPin, 1);
  65. digitalWrite(buzzerPin, 1);
  66. delay(1000);
  67. digitalWrite(ledPin, 0);
  68. digitalWrite(buzzerPin, 0);
  69. delay(1000);
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement