Home |

Trigat

Servo With Ultrasonic Sensor

10-11-2017

Language or Platform: Arduino

Code:

// This program was used for ticket gate used for
// my daughters toy cars. The gate lifts up and
// allows cars to pass through once the sonar sensor
// picks up the car.

// A servo motor and ultrasonic sensor are used.

#include <Servo.h>
Servo myservo; 
int pos = 180;

// defines pins numbers for ultrasonic
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;

void setup() {

// servo 
myservo.write(pos);
myservo.attach(4);

// ultrasonic
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication

}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
// Serial.print("Distance: ");
// Serial.println(distance);

if (distance > 10) {
//  Serial.print("Greater");   Can use serial monitor to test and make sure it's working
 
    delay(600);
    myservo.write(10);  // Give the car time to pull up and leave the gate
}
else {
//  Serial.print("Greater");  
 
    delay(600);
    myservo.write(100);
}

}

Back