Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Include the Servo library
- #include <Servo.h>
- // Declare the Servo pin
- int servoPin = 3;
- // Create a servo object
- Servo Servo1;
- int trigPin = 11; // Trigger
- int echoPin = 12; // Echo
- long duration, cm, inches;
- void setup()
- {
- // We need to attach the servo to the used pin number
- Servo1.attach(servoPin);
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- Serial.begin(9600);
- }
- void loop()
- {
- // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
- // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
- digitalWrite(trigPin, LOW);
- delayMicroseconds(5);
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Read the signal from the sensor: a HIGH pulse whose
- // duration is the time (in microseconds) from the sending
- // of the ping to the reception of its echo off of an object.
- pinMode(echoPin, INPUT);
- duration = pulseIn(echoPin, HIGH);
- // Convert the time into a distance
- cm = (duration/2) / 29.1; // Divide by 29.1 or multiply by 0.0343
- inches = (duration/2) / 74; // Divide by 74 or multiply by 0.0135
- Serial.print(inches);
- Serial.print("in, ");
- Serial.print(cm);
- Serial.print("cm");
- Serial.println();
- if (cm < 50 )
- {
- for(int i = 45; i <= 135; i=i+2)
- {
- Servo1.write(i);
- //Serial.println(i);
- delay(50);
- }
- for(int i = 135; i >= 45; i=i-2)
- {
- Servo1.write(i);
- //Serial.println(i);
- delay(50);
- }
- }
- }
Add Comment
Please, Sign In to add comment