Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Sonar and servo code
- // Define Trig and Echo pin:
- #define trigPin 2
- #define echoPin 3
- // Define variables:
- long duration;
- int distance;
- #include <Servo.h>
- int servoPin = 5;
- Servo Servo1;
- void setup() {
- // Define inputs and outputs:
- pinMode(trigPin, OUTPUT);
- pinMode(echoPin, INPUT);
- //Begin Serial communication at a baudrate of 9600:
- Serial.begin(9600);
- Servo1.attach(servoPin);
- }
- void loop() {
- // Clear the trigPin by setting it LOW:
- digitalWrite(trigPin, LOW);
- delayMicroseconds(5);
- // Trigger the sensor by setting the trigPin high for 10 microseconds:
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
- duration = pulseIn(echoPin, HIGH);
- // Calculate the distance:
- distance= duration*0.034/2;
- // Print the distance on the Serial Monitor (Ctrl+Shift+M):
- Serial.print("Distance = ");
- Serial.print(distance);
- Serial.println(" cm");
- delay(50);
- if(distance<=15){
- // Make servo go to 90 degrees
- Servo1.write(90);
- delay(1000);
- }
- else{
- Servo1.write(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement