⭐⭐ Advanced beginner ⏱️ 20 minutes

Barrier

You build a barrier, like at a parking garage. Press the button: the servo turns the barrier up, waits a little, and closes again.

First you log in for a moment. Then your project is ready right away.

🧰 What do you need?

1× Arduino UNO
1× Push button
1× Servo motor SG90
🔌
USB cable + Jumper wires

🗺️ Wiring diagram

Follow the wires from the Arduino to each part. You can choose the wire colors yourself.

From To
Arduino UNO · D2 Push button · 1
Push button · 2 Arduino UNO · GND
Arduino UNO · D9 Servo motor SG90 · PWM
Arduino UNO · 5V Servo motor SG90 · VCC
Arduino UNO · GND Servo motor SG90 · GND

🛠️ This is how you build it

  1. Put the push button across the gap in your breadboard: one leg to pin 2, and a leg on the other side to GND.
  2. Connect the servo: orange to pin 9, red to 5V, and brown to GND.
  3. Stick a straw or popsicle stick onto the arm of the servo: that is your barrier!

💻 The code

// Barrier
// Press the button: the barrier (servo) goes up, waits a little, and closes again.

#include <Servo.h>

const int BUTTON_PIN = 2;   // Push button on pin 2 (other side to GND)
const int SERVO_PIN = 9;    // Orange/yellow wire of the servo on pin 9

const int CLOSED = 0;       // Servo angle when the barrier is closed
const int OPEN = 90;        // Servo angle when the barrier is open

Servo barrier;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  barrier.attach(SERVO_PIN);
  barrier.write(CLOSED);    // Start with the barrier closed
}

void loop() {
  if (digitalRead(BUTTON_PIN) == LOW) { // Button pressed
    // Turn open slowly, degree by degree
    for (int angle = CLOSED; angle <= OPEN; angle++) {
      barrier.write(angle);
      delay(15);
    }
    delay(3000);                        // Open for 3 seconds: the car drives through
    // Slowly close again
    for (int angle = OPEN; angle >= CLOSED; angle--) {
      barrier.write(angle);
      delay(15);
    }
  }
}

🧠 What does the code do?

  • We use the Servo library. With write() you tell the servo which angle to go to.
  • After a button press, we turn degree by degree from 0 to 90. Nice and calm.
  • After 3 seconds, we turn back to 0: the barrier is closed.

🎯 Try this…

  • Make the barrier open and close faster
  • Make a buzzer beep while the barrier is moving
  • Turn on a red LED when the barrier is closed and a green one when it is open

🚀 Build this project with Codey: open codey.online/starter-kits/uno/projects/barrier and click MAKE THIS. Then the code and the wiring diagram are ready right away.

First you log in for a moment. Then your project is ready right away.
⬇️ Download this page as a PDF 📚 Download the complete tutorial (PDF)

Codey Online is a product of OTRONIC

Build your Arduino or ESP32 project with AI

Describe what you want to build. Codey Online writes the code, draws the wiring diagram, compiles it and flashes your board straight from the browser.

Start for free