safwan092

RC Car with type-C Car Camera and arduino nano Ultrasonic and buzzer and led

Dec 25th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1.  
  2. #define echoPin 10
  3. #define trigPin 9
  4. #define ledPin 4
  5.  
  6. long duration;
  7. int distance;
  8. int flag = 0;
  9.  
  10. //----------------------------------
  11. int alertDistance = 20; // 20 CM
  12. //----------------------------------
  13.  
  14. void setup() {
  15. Serial.begin(9600);
  16. Serial.println("Serial COM Test");
  17. pinMode(ledPin, OUTPUT);
  18. pinMode(trigPin, OUTPUT);
  19. pinMode(echoPin, INPUT);
  20. digitalWrite(ledPin, 1);
  21.  
  22. }
  23.  
  24. void loop() {
  25. US();
  26. if (distance < alertDistance) {
  27. digitalWrite(ledPin, 0);
  28. }
  29. else {
  30. digitalWrite(ledPin, 1);
  31. }
  32. delay(50);
  33. }
  34.  
  35.  
  36. void US() {
  37. digitalWrite(trigPin, LOW);
  38. delayMicroseconds(2);
  39. digitalWrite(trigPin, HIGH);
  40. delayMicroseconds(10);
  41. digitalWrite(trigPin, LOW);
  42. duration = pulseIn(echoPin, HIGH);
  43. distance = duration * 0.034 / 2;
  44. Serial.print("Distance: ");
  45. Serial.print(distance);
  46. Serial.println(" cm");
  47. }
Advertisement
Add Comment
Please, Sign In to add comment