ROBOTICS · LEVEL 1 · ARDUINO FOUNDATIONS · LESSON 09

Build an Arduino Servo Gate or Safe Latch

Code can move cardboard: program a servo mechanism that becomes part of your invention.

Until now, your Arduino has made lights and sounds. Today it will make a real object move.

A servo motor is a small motor with a tiny controller inside. Instead of merely spinning freely, it can move to an angle you name in code. You will use it to move a cardboard gate, toy-safe latch, alert flag, or score marker. The hard and interesting part is not copying an angle number—it is finding angles and a cardboard linkage that work together without forcing anything.

At a glance

Age range10–13
Estimated time65–90 minutes
DifficultyBeginner-plus mechanical build
Parent involvementMedium for first power-up and safety check; light for angle testing and cardboard design
Major conceptsServo library, signal/power/ground, mechanical range, named constants, angles, mechanism testing, iteration
Suggested session plan15 min wiring/test, 20 min cardboard mechanism, 15 min angle trials, 10 min explain/notebook; optional 20–30 min stronger enclosure

What you will learn

  • How a three-wire servo differs from an LED or a normal motor.
  • How to use Arduino’s Servo library to move to a named angle.
  • Why the servo needs a signal wire, power wire, and ground wire.
  • How to find safe open and closed positions by testing a mechanism gradually.
  • Why cardboard geometry can matter as much as the code.
  • How to separate a safe mechanical test from a larger capstone program.

Before you begin

Complete Lesson 8: Choose and Plan Your Arduino Invention first. Bring your capstone planning page. Decide what your servo will move: a toy-safe latch, an armed flag for Room Sentinel, a winner flag or score pointer, or a pet-care reminder flag. It is also fine to make a general gate now and decide later where it belongs.

You will reuse the button wiring from Lesson 2 and the named constants habit from Lesson 5. This lesson uses D9 for the servo signal, so remove any LED circuit previously connected to D9 before connecting the servo.

Use the small three-wire servo supplied with the Arduino Student Kit. Its wire colors are usually red for 5V, brown or black for ground, and orange, yellow, or white for signal. If your servo uses different colors, check its included card before powering it. Arduino’s official Basic Servo Control guide is the supporting technical reference.

Do not simulate the mechanism first. A screen cannot reveal whether cardboard rubs, a horn hits a stop, or the Uno resets under load. Build the unloaded physical servo test first, then add cardboard only after the motion is calm and predictable.

What you need

Required components

QuantityItemCompatible substitute
1Arduino Uno from the Arduino Student KitGenuine Uno R3 or Uno R3 SMD
1Small three-wire hobby servo from the Student Kit5V micro servo; use only one small unloaded servo in this USB-powered lesson
1Solderless breadboardStandard half-size breadboard
1Tactile pushbuttonAny normally-open momentary pushbutton that fits a breadboard
5–8Male-to-male jumper wiresJumper leads suitable for the servo connector
1USB-A to USB-B data cableArduino-branded USB-A-to-B data cable
1Servo horn or arm supplied with the servoAny supplied non-damaged horn; use the small center screw only if needed
1Small piece of cardboardCereal-box cardboard is an excellent first prototype
1Tape or rubber bandPainter’s tape or masking tape works well for prototypes

Optional components

  • Cardboard box, paper fastener or brad, wooden craft stick, string, and markers for a sturdier linkage.
  • Potentiometer from Lesson 5 if you choose the optional dial-controlled version.
  • LED and 220 Ω resistor for a labeled “armed” or “open” indicator.
  • Adult help with a tiny screwdriver, craft knife, or hot glue. Neither hot glue nor a craft knife is required.

Tools

Scissors and tape for cardboard. A small screwdriver may be needed for the servo horn’s center screw.

Computer/software requirements

  • Arduino IDE 2 with Arduino Uno and its port selected.
  • The Arduino AVR board package, which includes the standard Servo library used by #include <Servo.h>.
  • No Tinkercad account is needed for this physical mechanism lesson.

Safety and setup notes

  • Unplug USB before changing servo wires, attaching a horn, or moving cardboard near the horn.
  • Test only one small, unloaded kit servo from the Uno’s USB-powered 5V pin. Do not connect a larger servo, a second servo, or a jammed mechanism to the Uno’s 5V pin. If the servo buzzes continuously, feels hot, the Uno resets, or the computer disconnects it, unplug immediately and remove the mechanical load.
  • A servo can pinch a finger or damage itself when it tries to move through cardboard. Keep fingers out of the horn’s path and make the gate or flag light enough to swing freely.
  • Never force a servo horn by hand while the board is powered. Never use a 9V rectangular battery for this servo. Do not use wall power.
  • Start with cardboard disconnected from the horn. Add a loose, easily removable linkage only after the servo moves calmly between positions.
  • The adult should supervise the first power-up, the first horn attachment, and any cutting. Let the child choose angles, observe the motion, and redesign cardboard. Step in for buzzing, stalling, reset or disconnection, pinching risk, or a mechanism that needs force.

Build overview

The servo has three jobs happening at once:

Button press → Arduino reads D2 → code chooses OPEN or CLOSED angle → D9 signal tells servo where to point
                                       ↑                                  ↓
                                named constants                   5V + GND give servo power

The motor does not know what “a good latch” means. It only knows angles. You will test which angle pair makes your cardboard gate close without crushing it, then open far enough to clear it. The code and the mechanism must agree.

This starter version opens only while the button is held. That is intentional: it proves one input controls one mechanical output. In Lesson 10, your capstone can decide when the servo should open—after the correct code, after a fair game result, or after a reminder is acknowledged.

Step-by-step build instructions

Step 1: Prepare a safe, empty motion area

  1. Clear a hand-sized area beside the breadboard. Put the servo on the table with no cardboard attached.
  2. Choose one servo horn or arm and set it aside. Do not attach it yet.
  3. Make a rough cardboard gate or flag: a 2–3 inch rectangle is enough. Give it a tape hinge or a paper-fastener hinge so it can swing freely by hand.
  4. Mark one position CLOSED and another OPEN on the cardboard or table. Keep the gate separate from the servo for now.

Checkpoint: swing the cardboard by hand. It must move freely without bending, catching, or needing force. If it does not, fix the cardboard before adding electronics.

Step 2: Wire the button input

  1. Place the tactile button across the breadboard’s center trench so its two switch sides are not already connected together.
  2. Connect one button side to Arduino D2.
  3. Connect the opposite button side to Arduino GND.
  4. Do not add an external resistor. The code uses INPUT_PULLUP, just as in Lesson 8.

Checkpoint: trace D2 → button → GND. Predict: when the button is pressed, will the Arduino read HIGH or LOW with INPUT_PULLUP? Answer: LOW.

Step 3: Wire the servo—signal, power, and ground

  1. Identify the three servo wires before connecting anything. On the usual kit servo: red = 5V, brown/black = GND, orange/yellow/white = signal.
  2. Connect the servo’s red power wire to Arduino 5V.
  3. Connect the servo’s brown or black ground wire to Arduino GND.
  4. Connect the servo’s orange, yellow, or white signal wire to Arduino D9.
  5. Keep the servo on the table with clear space around its output shaft. Do not attach cardboard or a horn yet.
Servo connectionArduino connectionJob
Red5VProvides power for the small servo test
Brown or blackGNDProvides the return path and common reference
Orange, yellow, or whiteD9Carries the angle-control signal

Checkpoint: with USB still unplugged, say the three jobs out loud: “red gives power, dark wire is ground, bright wire gets the D9 signal.” Confirm the D9 LED circuit from Lesson 8 is removed.

Step 4: Upload the unloaded servo test

  1. Connect USB to the Uno. Make sure nobody is holding the servo shaft.
  2. In Arduino IDE, select Arduino Uno and the correct port.
  3. Create a new sketch, paste or type the complete code in the next section, then click Verify and Upload.
  4. The servo should move to the starter CLOSED_ANGLE when the sketch starts. Hold the button to move it to OPEN_ANGLE; release to return it to closed.
  5. If it chatters, presses against something, resets the Uno, or does not move, unplug USB and use the troubleshooting table before attaching a horn.

Checkpoint: the bare servo moves smoothly and quietly in both directions. You can name its three wires and point to D2 and D9.

Step 5: Attach the horn and test the mechanism gently

  1. Unplug USB. With the servo at its last closed position, gently press the chosen horn onto the servo shaft. Do not force it.
  2. Reconnect USB. Watch one button-controlled open/close movement with no cardboard attached. If the horn hits the servo body or looks badly aligned, unplug and choose a different horn position.
  3. Make a temporary connection from horn to cardboard: tape, a rubber band, a paper clip, or a short linkage is enough. The connection should pop loose rather than jam if something goes wrong.
  4. Test with a hand nearby but not in the motion path. The mechanism should swing freely from CLOSED to OPEN. It should not bend the cardboard at either end.

Checkpoint: your mechanism can make three calm open/close cycles in a row. The servo should not buzz after reaching either position.

Step 6: Record angle evidence before you improve it

Make a table in your notebook. Test the starter pair and at least two other pairs, moving one angle only 10° at a time. Test with the cardboard disconnected whenever a new pair might move too far.

TrialCLOSED_ANGLEOPEN_ANGLEWhat happened?Safe to keep?
130110Starter testYes / No
2_________Yes / No
3_________Yes / No

Checkpoint: choose your best pair based on evidence, not on what looked most dramatic. A good open position clears the latch or gate; a good closed position stops before the cardboard or servo is forced.

Code

#include <Servo.h>

const int BUTTON_PIN = 2;
const int SERVO_PIN = 9;

// Change these only after safe, unloaded angle tests.
const int CLOSED_ANGLE = 30;
const int OPEN_ANGLE = 110;

Servo gateServo;

void setup() {
  pinMode(BUTTON_PIN, INPUT_PULLUP);

  gateServo.attach(SERVO_PIN);
  gateServo.write(CLOSED_ANGLE);
}

void loop() {
  bool buttonPressed = digitalRead(BUTTON_PIN) == LOW;

  if (buttonPressed) {
    gateServo.write(OPEN_ANGLE);
  } else {
    gateServo.write(CLOSED_ANGLE);
  }

  delay(20);
}

What the important code means

  • Library: #include <Servo.h> gives your sketch extra tools for communicating with a hobby servo. Servo gateServo; creates a named servo object your code can control.
  • Variables and constants: BUTTON_PIN and SERVO_PIN name D2 and D9. CLOSED_ANGLE and OPEN_ANGLE are named values you will improve through testing. They are not secret “correct” numbers.
  • setup(): this runs once. It sets the button input mode, connects gateServo to D9 using attach(), and sends the servo to the starting closed position with write().
  • loop(): this repeats: read the button, choose one of two positions, and wait briefly.
  • Inputs and outputs: the button on D2 is the input. Servo movement is the output. The red 5V and dark ground wires provide power; the D9 wire carries the control signal.
  • Condition: with INPUT_PULLUP, button pressed means LOW. The if asks whether the input is pressed. If yes, open; otherwise, close.
  • Why delay(20)? It gives the loop a short, steady rhythm. The servo needs time to physically move, but the angle values—not this delay—tell it where to go.

Arduino’s official Basic Servo Control guide explains the Servo library and angle control. A servo’s advertised range is often described as about 0–180°, but your safe mechanism range can be much smaller. Test it; do not assume every servo and cardboard design can safely use every angle.

Make it work

The first version works when all of these are true:

  1. Arduino IDE says Done uploading.
  2. The servo goes to its closed position at startup without buzzing or forcing anything.
  3. Holding the button opens the gate or flag; releasing it closes the gate or flag.
  4. The servo moves smoothly through three repeated cycles without resetting the Uno.
  5. The cardboard mechanism moves freely and can always be opened by hand.
  6. You can explain the job of the servo’s signal, power, and ground wires.

Understand it

  1. Why does a servo need three wires while an LED needs only an output path and ground?
  2. What does gateServo.attach(SERVO_PIN) do?
  3. What would happen if you accidentally left the old D9 LED circuit connected while using D9 for the servo signal?
  4. Why should you test a new angle pair with the cardboard disconnected first?
  5. Why are CLOSED_ANGLE and OPEN_ANGLE better than writing 30 and 110 directly inside the if/else blocks?

Required “change it” challenge

Desired outcome: choose and prove your own CLOSED_ANGLE and OPEN_ANGLE so your mechanism actually latches, clears, points, or flags correctly.

Constraints: keep the angles as named constants; test at least three angle pairs; change no angle by more than 10° at a time; make your first test of each new pair with the cardboard disconnected; document the pair, observed result, and keep/change decision in your notebook. The finished mechanism must never press into a hard stop or need your hand to force it.

Hints:

  1. Start near the middle of the servo’s possible motion, such as 90°, then move outward by 10° only when the bare servo is calm.
  2. If your gate goes the wrong direction, swap which named constant is used for OPEN and CLOSED before changing the wiring.
  3. If the gate misses its target, first move the cardboard linkage or horn position. Code cannot repair a gate that is too far away, too heavy, or stuck on tape.
  4. A less dramatic angle pair that works every time is a better engineering choice than a wide swing that buzzes.

Parent guidance: let the student select the trials, write observations, and alter named constants. A useful struggle is comparing whether the problem is an angle, a horn position, or cardboard geometry. Ask, “Does the bare servo reach the position calmly?” and then, “What changed when cardboard was attached?” Resist holding the gate in the correct place permanently; ask how it can move freely. Step in at buzzing or stalling, Uno resets, finger-pinch risk, a hot servo, or 15–20 minutes without one new test. Unplug before any mechanical adjustment.

Optional enhancements

Try this

Make a moving armed or winner flag. Keep the same button control, but use a cardboard arrow or colored flag instead of a gate. Hint: a short, light flag on a craft-stick arm needs less force than a heavy door.

Challenge

Use the Lesson 5 potentiometer to choose a servo angle. First test the servo with no cardboard; then map the knob’s 0–1023 range to a deliberately safe angle range, such as your tested closed angle through open angle. Explain why you should not automatically map to 0–180.

Stretch

Connect the servo mechanism to one capstone input from your Lesson 8 plan, such as an arm button or a light-sensor condition. Keep it a subsystem: prove that one input causes the intended motion before adding game rules, code sequences, or scorekeeping in Lesson 10.

Debugging guide

What you noticeLikely causeSmallest next diagnostic step
Servo does not move at allSignal, power, or ground wire is wrong; attach() or pin number is wrongUnplug, then trace one connection at a time: red → 5V, dark → GND, signal → D9. Compare the SERVO_PIN constant to the wiring.
Servo twitches or moves once, then stopsLoose connection, weak USB connection, or mechanical loadRemove all cardboard and horn load, reseat the three leads, then run one bare-servo button test.
Uno resets, disconnects, or its power LED blinksServo is stalled or drawing too much currentUnplug immediately. Remove the load and do not keep retrying. Verify only one small servo is connected and the mechanism swings freely.
Servo buzzes or grinds at open or closedThe selected angle drives the horn into a stop or the cardboard is jammedUnplug, detach cardboard, reduce the nearest angle by 10°, and test bare motion before reattaching.
Gate moves the opposite directionOpen or closed names do not match the horn or linkage positionSwap the values assigned to OPEN_ANGLE and CLOSED_ANGLE, then test with cardboard disconnected.
Servo moves but gate does notHorn or linkage is loose, gate is too heavy, or hinge catchesTurn off power and test the cardboard by hand. Fix the hinge or attachment before changing code.
Sketch says Servo.h: No such file or directoryThe Arduino Uno board package is incomplete or wrong board or core is selectedSelect Arduino Uno, restart IDE, and verify the standard Arduino AVR board package is installed; do not download a random servo library.
Button has no effectD2 button wiring or INPUT_PULLUP logic is wrongTest only D2 → button → GND; confirm digitalRead(BUTTON_PIN) == LOW remains in the sketch.

Use the Debugging Ladder for the electronic checks. Add this mechanical rule: test bare servo → test horn → test cardboard → test full mechanism. Do not jump straight from a stalled gate to changing several code values.

Recap

You used a library to control a physical actuator, named safe positions, and discovered that an Arduino project is partly code and partly mechanics. The code chooses an angle, but your cardboard design decides whether that angle makes a useful gate, flag, latch, or pointer. You improved it by testing one small change at a time.

Show what you learned

In your maker notebook, answer these prompts:

  • Which angle pairs did you test, and which pair did you keep? Why?
  • What did the cardboard mechanism do that the code alone could not predict?
  • What did you change in the project?
  • What failed, and how did you diagnose it?
  • What would you improve next time? Explain either attach(), write(), or one servo wire in your own words.

What’s next

Next, in Lesson 10: Build Rules, Rounds, and Scores, your Arduino will begin to remember what has happened: a score, a game stage, or code attempt. Your servo can stay as a tested output while you build the rules that decide when it is allowed to move. Keep the current working servo sketch saved as a known-good test.

NEXT · LESSON 10

Lesson 10: Build Rules, Rounds, and Scores

Parent guide

What to prepare in advance

  • Put out the Uno, small kit servo, button, breadboard, compatible jumper leads, cardboard, tape, USB data cable, and notebook. Keep scissors or screwdriver for supervised use only.
  • Confirm Arduino IDE can upload a simple sketch. Open the Components guide, Debugging Ladder, and the child’s Lesson 8 capstone plan.
  • Identify the actual servo wire colors before the child connects it. Clear the table around its motion path.
  • Decide how you will stop promptly if the servo buzzes or board resets: unplug USB first, then inspect.

Where the child should work independently

Let the child trace the three servo wire jobs, wire the button, upload the test, choose a horn or linkage, build the cardboard prototype, select angle trials, log observations, and decide which pair works best. The child should determine whether a problem changes when cardboard is removed.

Moments when the parent should resist taking over

Do not supply “perfect” angles. Do not tape or hold a failing gate into the correct position for the child. Ask what the bare servo does, then what the cardboard does. Let the student discover that a smaller, reliable movement can be better than a dramatic, jammed swing.

When the parent should step in

Step in at continuous buzzing, heat, a reset or disconnect, mechanical force, pinch risk, uncertain wire colors, or an unsafe cardboard latch. Unplug before any mechanical adjustment. If 15–20 minutes of honest tests do not produce new evidence, return to the bare-servo sketch and collect an overhead wiring photo, servo wire-color description, board model, operating system, selected port, full code, exact error text, and expected versus actual motion before requesting help.

A simple understanding-based assessment

Ask the student to point to the servo and explain which wire is power, ground, and signal. Then show one of his tested angle pairs and ask why it was kept or rejected. Assess safe testing, a clear wire explanation, three recorded trials, a freely moving mechanism, and one evidence-based improvement—not merely whether the cardboard looks polished.

Further resource: Arduino: Basic Servo Control