Advertisement
safwan092

Untitled

Jun 8th, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 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. delay(500);
  28. myservo.write(0);
  29. delay(1000);
  30. myservo.detach();
  31. digitalWrite(ledPin, 0);
  32. digitalWrite(buzzerPin, 0);
  33. flag = 0;
  34. }
  35.  
  36. void loop() {
  37. US();
  38. if (distance < alertDistance && flag == 0) {
  39. myservo.attach(servoPin);
  40. delay(500);
  41. myservo.write(90);
  42. delay(1000);
  43. myservo.detach();
  44. alert();
  45. flag = 1;
  46. }
  47. delay(50);
  48. }
  49.  
  50.  
  51. void US() {
  52. digitalWrite(trigPin, LOW);
  53. delayMicroseconds(2);
  54. digitalWrite(trigPin, HIGH);
  55. delayMicroseconds(10);
  56. digitalWrite(trigPin, LOW);
  57. duration = pulseIn(echoPin, HIGH);
  58. distance = duration * 0.034 / 2;
  59. Serial.print("Distance: ");
  60. Serial.print(distance);
  61. Serial.println(" cm");
  62. }
  63.  
  64. void alert() {
  65. for (int i = 0; i < alertTimes; i++) {
  66. digitalWrite(ledPin, 1);
  67. digitalWrite(buzzerPin, 1);
  68. delay(1000);
  69. digitalWrite(ledPin, 0);
  70. digitalWrite(buzzerPin, 0);
  71. delay(1000);
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement