LeventeDaradici

Servo 90 degrees sliding with ultrasonic sensor

Dec 29th, 2021 (edited)
268
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.79 KB | None | 0 0
  1. // Include the Servo library
  2. #include <Servo.h>
  3. // Declare the Servo pin
  4. int servoPin = 3;
  5. // Create a servo object
  6. Servo Servo1;
  7. int trigPin = 11;    // Trigger
  8. int echoPin = 12;    // Echo
  9. long duration, cm, inches;
  10.  
  11. void setup()
  12.      {
  13.         // We need to attach the servo to the used pin number
  14.         Servo1.attach(servoPin);
  15.         pinMode(trigPin, OUTPUT);
  16.         pinMode(echoPin, INPUT);
  17.         Serial.begin(9600);
  18.      }
  19.  
  20. void loop()
  21.      {
  22.  
  23.         // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  24.         // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  25.         digitalWrite(trigPin, LOW);
  26.         delayMicroseconds(5);
  27.         digitalWrite(trigPin, HIGH);
  28.         delayMicroseconds(10);
  29.         digitalWrite(trigPin, LOW);
  30.         // Read the signal from the sensor: a HIGH pulse whose
  31.         // duration is the time (in microseconds) from the sending
  32.         // of the ping to the reception of its echo off of an object.
  33.         pinMode(echoPin, INPUT);
  34.         duration = pulseIn(echoPin, HIGH);
  35.         // Convert the time into a distance
  36.         cm = (duration/2) / 29.1;     // Divide by 29.1 or multiply by 0.0343
  37.         inches = (duration/2) / 74;   // Divide by 74 or multiply by 0.0135
  38.         Serial.print(inches);
  39.         Serial.print("in, ");
  40.         Serial.print(cm);
  41.         Serial.print("cm");
  42.         Serial.println();
  43.  
  44.     if (cm < 50 )
  45.       {
  46.         for(int i = 45; i <= 135; i=i+2)
  47.            {
  48.               Servo1.write(i);
  49.               //Serial.println(i);
  50.               delay(50);
  51.            }  
  52.         for(int i = 135; i >= 45; i=i-2)
  53.           {
  54.               Servo1.write(i);
  55.               //Serial.println(i);
  56.               delay(50);
  57.           }
  58.       }      
  59.     }
Add Comment
Please, Sign In to add comment