Movement · Lesson 5 of 5· 18 min

Making things move: a button gate

Why this matters

Robots move. A servo motor turns to an exact angle you choose, from 0 to 180 degrees. Servos open gates, steer wheels and move robot arms.

Controlling a servo

A servo listens to pulses 50 times a second. A short pulse (about 0.5 milliseconds) means 0 degrees; a long one (about 2.5 milliseconds) means 180.

Open a tool

Wokwi simulator

Free, nothing to install. Works best on a laptop; on a phone you can still read the steps and the code below.

Opens wokwi.com in a new tab. Come back here when you are done.

Open Wokwi simulator

Step by step

  1. Add a servo in Wokwi.

  2. Wire its PWM pin to GP16, V+ to VBUS (5 volts) and GND to GND.

  3. Keep your button on GP14.

from machine import Pin, PWM
import time

servo = PWM(Pin(16))
servo.freq(50)

def angle(deg):
    # 0.5 ms to 2.5 ms out of every 20 ms, as a number from 0 to 65535
    servo.duty_u16(int(1638 + deg / 180 * (8192 - 1638)))

button = Pin(14, Pin.IN, Pin.PULL_UP)

while True:
    if button.value() == 0:
        angle(90)       # open
        time.sleep(3)   # stay open for 3 seconds
    else:
        angle(0)        # closed
    time.sleep(0.05)

Example

Teaching scenario (fictional)

Kwame helps at a school in Tamale where goats keep walking into the garden. He plans a small gate that opens when a teacher presses a button and closes by itself after a few seconds. This program is his first test, in the simulator, before buying any parts.

You built a robot

The button senses, the if statement thinks, and the servo acts. That is the whole loop from Robotics Introduction, running in real code.

You’re reading for free. Sign in to save your progress, ask questions on any lesson, and earn a certificate when you finish.Sign in to keep my progress →
Last lesson

Lesson 5 of 5