Facebook
From veckalov, 3 Weeks ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 118
  1. #include<Servo.h>
  2. #define trigPin 9
  3. #define echoPin 8
  4. Servo servo;
  5. int sound =250;
  6. void setup() {
  7.   // put your setup code here, to run once:
  8. Serial.begin(9600);
  9. pinMode(trigPin,OUTPUT);
  10. pinMode(echoPin,INPUT);
  11. servo.attach(6);
  12.  
  13. }
  14.  
  15. void loop() {
  16.   // put your main code here, to run repeatedly:
  17. long duration, distance;
  18. digitalWrite(trigPin,LOW);
  19. delayMicroseconds(2);
  20. digitalWrite(trigPin,HIGH);
  21. delayMicroseconds(10);
  22. digitalWrite(trigPin,LOW);
  23. duration=pulseIn(echoPin,HIGH);
  24. distance=(duration/2)/29.1;
  25. if (distance<80){
  26.   Serial.print(distance);
  27.   Serial.println("cm");
  28.   servo.write(90);
  29. }
  30. else if(distance<180){
  31.   Serial.print(distance);
  32.   Serial.println("cm");
  33.   servo.write(90);
  34. }
  35. else{
  36.   Serial.println("The distance is more than 180cm ");
  37. }
  38. delay(500);
  39. }