Riku Lahkar
Published © MIT

Automatic Gate Opener with Arduino and Servo Motor

Build a smart parking gate with Arduino UNO, ultrasonic sensor & servo motor. Detect vehicles and open/close the gate automatically

IntermediateFull instructions provided7 hours138
Automatic Gate Opener with Arduino and Servo Motor

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
SG90 Micro-servo motor
SG90 Micro-servo motor
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Breadboard (generic)
Breadboard (generic)
×1
Jumper wires (generic)
Jumper wires (generic)
×1
AA Batteries
AA Batteries
×1

Software apps and online services

Arduino IDE
Arduino IDE

Hand tools and fabrication machines

Tape, Double Sided
Tape, Double Sided

Story

Read more

Schematics

The circuit diagram

Code

The code for this project

C/C++
#include <Servo.h>

const int trigPin = 8;
const int echoPin = 9;
Servo gateServo;

int distance;
bool gateOpen = false;

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  gateServo.attach(3);
  gateServo.write(0); // Start closed
  Serial.begin(9600);
}

int getDistance() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH, 30000);
  int distance = duration * 0.034 / 2;
  return distance;
}

void moveGate(int fromAngle, int toAngle) {
  if (fromAngle < toAngle) {
    for (int pos = fromAngle; pos <= toAngle; pos++) {
      gateServo.write(pos);
      delay(10);
    }
  } else {
    for (int pos = fromAngle; pos >= toAngle; pos--) {
      gateServo.write(pos);
      delay(10);
    }
  }
}

void loop() {
  distance = getDistance();
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  if (distance > 0 && distance <= 15 && !gateOpen) {
    moveGate(0, 90);
    gateOpen = true;
  } else if (distance > 15 && gateOpen) {
    moveGate(90, 0);
    gateOpen = false;
  }

  delay(200);
}

Credits

Riku Lahkar
3 projects • 1 follower

Comments