On this page
  1. Welcome
  2. Part 1 · Pico W
  3. Part 2 · Pins
  4. Part 3 · Thonny
  5. Part 4 · Onboard LED
  6. Part 5 · Buttons
  7. Part 6 · Ultrasonic
  8. Part 7 · Servo
  9. Part 8 · Projects
  10. Part 9 · AI prompts
  11. Quick reference
  12. Practice

Year 8 · Pico W

Physical computing with the Raspberry Pi Pico W

After the Year 8 Python module, you put coding into hardware. In Year 7 you learnt Python: variables, data types, if statements and for loops. This year you'll use Python to control real things: lights, buttons, distance sensors and motors. You'll also meet while loops, functions (def), and how to write good prompts when an AI helps you code.

  • What a Raspberry Pi Pico W is and how it works
  • How the Pico W's pins work
  • How to use Thonny to program the Pico W
  • How to use buttons, an ultrasonic distance sensor and a servo motor
  • How to write good prompts when asking an AI to help you code

Part 1: What is a Raspberry Pi Pico W?

The Raspberry Pi Pico W is a microcontroller: a tiny computer on a single chip, built to control electronics. The W means it also has Wi-Fi (and Bluetooth) built in.

Microcontroller vs computer

Your laptopRaspberry Pi Pico W
What it's forRunning lots of apps, browsing, gamesDoing one job over and over: reading sensors, controlling motors
Operating systemWindows, macOS, etc.None: it runs your program directly
Screen, keyboardYesNo: you plug it into a computer to program it
Start-up timeUp to a minuteAlmost instant
PowerLotsTiny: it can run on batteries
CostHundreds of poundsAbout £4–£6

Microcontrollers are everywhere: in microwaves, washing machines, TV remotes, car dashboards, toys and traffic lights. Each one runs a small program that reads inputs and controls outputs.

Input → Process → Output

Every Pico W project follows the same pattern:

Sensors provide input. Your program decides what to do. Actuators such as LEDs, servos and buzzers create the output.

What's on the board

USB at the top for power and data. The RP2040 is the brain. The metal wireless chip and antenna give the Pico W Wi-Fi. The built-in LED is useful for testing. BOOTSEL installs firmware. Forty pins along the edges match the original Pico.
  • Micro-USB port: gives the Pico W power and connects it to your computer.
  • Processor chip: RP2040. This runs your code.
  • Wireless chip + antenna: the metal can and the zigzag antenna at the end opposite the USB. These give the Pico W Wi-Fi (and Bluetooth).
  • Built-in LED: a small light you can control from code with Pin("LED"). On the Pico W the LED is wired through the wireless chip, so always use the name "LED" — do not use a GP number for the onboard LED.
  • BOOTSEL button: hold this down while plugging in to install new firmware (more in Part 3).
  • 40 pins: the gold holes along the edges. This is how the Pico W connects to other electronics. The pinout matches the original Pico.

How does Python run on the Pico W?

The Pico W runs MicroPython, a small version of Python made for microcontrollers. Almost everything you learnt in Year 7 works the same way. MicroPython adds extra modules for controlling hardware, mainly:

  • machine: controls the pins, motors and sensors
  • time: lets you pause your program
  • network: connects the Pico W to Wi-Fi (you may use this later for online projects)

In this Year 8 tutorial you will focus on pins, sensors and motors over USB. Wi-Fi is there when you need it later.

When you click Run in Thonny, your code is sent over the USB cable and the Pico W runs it straight away.

Part 2: Understanding the pins

Pin numbers: GP vs physical

Every pin has two numbers, which can be confusing at first:

  • Physical pin number (1 to 40): its position on the board. Pin 1 is top-left next to the USB port. The numbers go down the left side to 20, then continue up the right side from 21 to 40.
  • GP number (GP0 to GP28): the number you use in your code.
⚠️ In code you always use the GP number. For example, Pin(15) means GP15, which is physical pin 20, not physical pin 15!

Always keep a pinout diagram next to you when wiring. Search "Raspberry Pi Pico W pinout" or use the one on the official Raspberry Pi website.

Types of pin

Pin labelWhat it does
GP0–GP22, GP26–GP28General Purpose Input/Output (GPIO) pins. Your code controls these.
GND (ground)The "negative" side of the circuit. Every circuit must connect back to GND. There are 8 GND pins.
3V3(OUT) (physical pin 36)Gives out 3.3 volts. Use it to power small sensors.
VBUS (physical pin 40)Gives out 5 volts straight from the USB cable. Use it for servos and 5V sensors.
VSYS (physical pin 39)Used to power the Pico W from batteries.
RUNResets the Pico W when connected to GND. You won't need it yet.

What can GPIO pins do?

ModeMeaningExample
Digital outputPin is either on (3.3V) or off (0V)Turning an LED on and off
Digital inputPin reads whether something is on (1) or off (0)Reading a button
PWM (Pulse Width Modulation)Pin switches on and off very fast to control how muchDimming an LED, moving a servo
Analogue input (ADC)Reads a range of values, not just on/off. Only GP26, GP27 and GP28.Reading a light sensor or a knob

Safety rules for wiring

  1. Unplug the USB cable before changing any wires.
  2. Never connect 5V (VBUS) to a GP pin. The GP pins can only handle 3.3V, and 5V can permanently damage the Pico W.
  3. Never connect a power pin (3V3 or VBUS) directly to GND. This is a short circuit.
  4. Do not use a GP number for the onboard LED. Always write Pin("LED") on the Pico W.
  5. Check your wiring with a partner or your teacher before plugging back in.

Part 3: Using Thonny

Thonny is a free, beginner-friendly program for writing Python and sending it to the Pico W. Download it from thonny.org (Windows, Mac and Linux). It's already installed on Raspberry Pi computers.

The Thonny window

Write in the editor, watch printouts and errors in the Shell, and make sure the interpreter selector says MicroPython (Raspberry Pi Pico) — this option also covers the Pico W.
PartWhat it's for
Editor (top)Where you write and edit your program
Shell (bottom)Shows anything your program prints, plus error messages. You can also type single Python commands after >>> to test them.
Run button ▶ (green)Sends your program to the Pico W and runs it. Shortcut: F5.
Stop button ■ (red)Stops the program. Shortcut: Ctrl+F2. Also use it to reconnect if the Pico W isn't responding.
Interpreter selector (bottom-right corner)Chooses where your code runs: on your computer or on the Pico W

Step 1: Install MicroPython on the Pico W (only needed once)

A brand-new Pico W needs MicroPython firmware installed before it can run Python. You must install the Pico W firmware (not the plain Pico firmware).

  1. Hold down the BOOTSEL button on the Pico W.
  2. While holding it, plug the USB cable into your computer. Then let go of the button.
  3. The Pico W appears on your computer like a USB stick, called RPI-RP2.
  4. In Thonny, click the interpreter selector in the bottom-right corner and choose Configure interpreter…
  5. Choose MicroPython (Raspberry Pi Pico) from the drop-down list.
  6. Click the link Install or update MicroPython.
  7. Choose Raspberry Pi Pico W / Pico WH (not plain Pico) and click Install.
  8. Wait until it says Done, then close the window. The Pico W restarts by itself.
💡 If your teacher has already set up the Pico W, you can skip this step.

Step 2: Connect Thonny to the Pico W

  1. Plug in the Pico W normally (don't hold BOOTSEL this time).
  2. Click the interpreter selector in the bottom-right corner.
  3. Choose MicroPython (Raspberry Pi Pico).
  4. The Shell should show something like:

Output:

MicroPython v1.xx on 20xx-xx-xx; Raspberry Pi Pico W with RP2040 Type "help()" for more information. >>>

If you see that, you're connected!

Step 3: Test the Shell

Click next to >>> in the Shell, type this and press Enter:

>>> print("Hello from the Pico W!")
Hello from the Pico W!

That command ran on the Pico W, not your computer.

Type this into the editor:

from machine import Pin
import time

led = Pin("LED", Pin.OUT)   # Pico W onboard LED (use "LED", not a GP number)

while True:
    led.toggle()            # switch the LED on if off, off if on
    time.sleep(0.5)         # wait half a second

Click Run ▶. Thonny asks where to save the file:

  • This computer: saves on your computer and runs it on the Pico W. Good while you're still testing.
  • Raspberry Pi Pico: saves the file onto the Pico W itself (Thonny uses this label for Pico and Pico W).

The LED on the Pico W should start blinking. Click Stop ■ to stop it.

New Python idea: while True loops

In Year 7 you used for loops, which repeat a set number of times. A while loop repeats as long as a condition is True. Because True is always True, while True: repeats forever.

Microcontroller programs usually use while True:, because a device like a burglar alarm should keep checking its sensors until it is switched off.

Step 5: Make your program run without a computer

To make your program run automatically whenever the Pico W gets power (for example from a battery pack):

  1. Click File → Save as…
  2. Choose Raspberry Pi Pico.
  3. Name the file main.py exactly.

Every time the Pico W powers up, it runs main.py automatically.

💡 To see the files stored on the Pico W, click View → Files.

Troubleshooting Thonny

ProblemTry this
Shell says "Couldn't find the device" or "Device is busy"Click Stop ■. If that doesn't work, unplug the Pico W, wait 3 seconds and plug it back in.
Pico W doesn't appear at allTry a different USB cable. Some cables only charge and can't send data.
Interpreter list doesn't show the Pico WMake sure MicroPython is installed (Step 1).
ImportError: no module named 'machine'You're running on your computer, not the Pico W. Change the interpreter selector to MicroPython (Raspberry Pi Pico).
Old program keeps running when you plug inIt's saved as main.py on the Pico W. Click Stop, then delete or rename it in View → Files.

Part 4: Outputs — the onboard LED

Your Pico W already has a small LED on the board. You can turn it on and off from code. No breadboard wires are needed.

⚠️ On the Pico W, always write Pin("LED", Pin.OUT). Do not use a GP number for the onboard LED. It is wired through the wireless chip.

Code: blink ten times

This program turns the onboard LED on and off ten times, then stops.

from machine import Pin
import time

led = Pin("LED", Pin.OUT)   # Pico W onboard LED

for i in range(10):         # blink 10 times
    led.on()                # turn the light on
    time.sleep(0.3)         # wait 0.3 seconds
    led.off()               # turn the light off
    time.sleep(0.3)

print("Finished!")
CommandWhat it does
led.on() or led.value(1)Turns the onboard LED on
led.off() or led.value(0)Turns the onboard LED off
led.toggle()Switches to the opposite state (on ↔ off)
💡 In Part 3 you used while True: and toggle() to blink forever. Here for + on() / off() blinks a set number of times, then ends.

Part 5: Buttons

A push button is the simplest input. When you press it, it connects two wires together.

How a button works with the Pico W

The Pico W reads a pin as:

  • 1 (HIGH) if the voltage is near 3.3V
  • 0 (LOW) if the voltage is near 0V

But when the button isn't pressed, the pin isn't connected to anything. It "floats" and gives random readings. To fix this we use a pull-up resistor, which gently holds the pin at 1 when nothing is connected. The Pico W has pull-up resistors built in, so you just switch one on in your code.

The built-in pull-up holds GP14 at 1. Pressing the button connects GP14 to GND, so the pin reads 0.
ButtonPin reads
Not pressed1
Pressed0
⚠️ This feels backwards at first: pressed = 0 when using a pull-up.

Wiring

  • One leg of the button goes to GP14.
  • The opposite (diagonal) leg goes to GND.
💡 Breadboard buttons have 4 legs. Using legs that are diagonally opposite guarantees they're on opposite sides of the switch.

Code: read the button

from machine import Pin
import time

button = Pin(14, Pin.IN, Pin.PULL_UP)   # input with built-in pull-up

while True:
    print(button.value())
    time.sleep(0.1)

Run it and watch the Shell. You'll see 1 1 1 1 until you press the button, then 0 0 0.

Code: button controls an LED

from machine import Pin
import time

button = Pin(14, Pin.IN, Pin.PULL_UP)
led = Pin("LED", Pin.OUT)   # Pico W onboard LED

while True:
    if button.value() == 0:      # pressed
        led.on()
    else:
        led.off()
    time.sleep(0.01)

Code: count button presses

from machine import Pin
import time

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

while True:
    if button.value() == 0:
        presses = presses + 1
        print("Pressed", presses, "times")
        while button.value() == 0:   # wait until the button is released
            time.sleep(0.01)
        time.sleep(0.05)             # short pause to ignore "bounce"
💡 Why the extra waiting? The program loops thousands of times a second. Without waiting for release, one press would be counted hundreds of times. Buttons also "bounce": the metal contacts flicker on and off for a few milliseconds when pressed. The short pause ignores that. This is called debouncing.

Part 6: Ultrasonic distance sensor (HC-SR04)

How it works

The HC-SR04 measures distance the same way a bat or a dolphin does: with echoes.

1. The sensor sends ultrasound. 2. The sound bounces back. Your program times the echo and converts it to centimetres.
  1. The Pico W sends a short pulse to the TRIG pin.
  2. The sensor sends out 8 pulses of ultrasound (40 kHz, too high for humans to hear).
  3. The sound hits an object and bounces back.
  4. The sensor sets the ECHO pin to HIGH for exactly as long as the sound took to travel there and back.
  5. Your program measures that time and works out the distance.

The maths

Sound travels at about 343 metres per second, which is 0.0343 cm per microsecond. (A microsecond is one millionth of a second.)

The sound goes there and back, so we divide by 2:

distance (cm) = time (microseconds) × 0.0343 ÷ 2

Example: if the echo takes 1000 microseconds:
1000 × 0.0343 ÷ 2 = 17.15 cm

The four pins

Sensor pinConnect to
VCCPower (see the warning below)
TRIGGP3 (physical pin 5)
ECHOGP2 (physical pin 4), through a voltage divider if using 5V
GNDGND
⚠️ Important voltage warning
The standard HC-SR04 needs 5V power (VBUS). Its ECHO pin then also sends out 5V, which can damage the Pico W's 3.3V pins.

Option A (easiest): use the HC-SR04P or RCWL-1601 version. These work on 3.3V, so connect VCC to 3V3(OUT) and everything is safe.

Option B: if you have the 5V version, connect VCC to VBUS and put a voltage divider on ECHO (see diagram). Ask your teacher to check this wiring before plugging in.
ECHO → 1kΩ → junction to GP2, and from that junction 2kΩ down to GND. This lowers about 5V to about 3.3V.

New Python idea: functions

A function is a named block of code you can use again and again. You create one with def:

def say_hello(name):
    print("Hello,", name)

say_hello("Amir")    # Hello, Amir
say_hello("Chloe")   # Hello, Chloe

A function can also give back an answer using return:

def double(number):
    return number * 2

answer = double(7)
print(answer)        # 14

Functions keep your code tidy. Instead of repeating the same 6 lines every time you want a distance reading, you write them once inside a function.

Code: measure distance

from machine import Pin, time_pulse_us
import time

trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)

def get_distance_cm():
    # Send a 10 microsecond pulse to TRIG
    trig.off()
    time.sleep_us(2)
    trig.on()
    time.sleep_us(10)
    trig.off()

    # Measure how long ECHO stays HIGH (give up after 30 000 µs)
    duration = time_pulse_us(echo, 1, 30000)
    # duration is the time for the sound to go there and back

    if duration < 0:          # negative means no echo came back
        return -1

    return duration * 0.0343 / 2

while True:
    distance = get_distance_cm()
    if distance == -1:
        print("Out of range")
    else:
        print("Distance:", round(distance, 1), "cm")
    time.sleep(0.2)

Move your hand towards and away from the sensor and watch the numbers change.

Code: parking sensor

from machine import Pin, time_pulse_us
import time

trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
led = Pin("LED", Pin.OUT)   # Pico W onboard LED

def get_distance_cm():
    trig.off()
    time.sleep_us(2)
    trig.on()
    time.sleep_us(10)
    trig.off()
    duration = time_pulse_us(echo, 1, 30000)
    if duration < 0:
        return -1
    return duration * 0.0343 / 2

while True:
    distance = get_distance_cm()

    if distance == -1 or distance > 50:
        led.off()                       # far away: LED off
    elif distance > 20:
        led.toggle()                    # getting close: slow blink
        time.sleep(0.4)
    else:
        led.on()                        # too close: LED stays on

    time.sleep(0.05)

Tips for accurate readings

  • The sensor works best between about 2 cm and 4 m.
  • Soft or angled objects (like fabric or a slanted surface) reflect sound badly and give odd readings.
  • Wait at least 60 ms between readings, so old echoes don't confuse the next measurement.

Part 7: Servo motors

What is a servo?

A servo is a motor that turns to an exact angle, usually anywhere from 0° to 180°, and holds it there. Servos are used in robot arms, RC car steering, automatic doors and camera mounts. The small blue SG90 is the one you'll probably use in class.

How you control a servo: PWM

You tell the servo which angle to go to by sending a pulse every 20 milliseconds (50 times per second). The length of each pulse sets the angle:

0.5 ms → 0°, 1.5 ms → 90°, 2.5 ms → 180°. This is Pulse Width Modulation (PWM). The Pico W can generate these pulses for you.

Wiring

Red to VBUS (5V), brown/black to GND, orange/yellow signal to GP15. Power from VBUS, not 3V3.
Servo wireUsual colourConnect to
PowerRedVBUS (5V, physical pin 40)
GroundBrown or blackGND
SignalOrange or yellowGP15 (physical pin 20)
⚠️ Servos need 5V to move properly, so power them from VBUS, not 3V3. The signal wire only receives pulses from the Pico W, so it's safe to connect to a GP pin.

⚠️ One small servo is fine powered from USB. For two or more servos, or bigger servos, use a separate battery pack. Connect the battery's GND to the Pico W's GND as well.

The maths for duty cycle

In MicroPython, duty_u16() sets how much of each 20 ms cycle the pin is ON, as a number from 0 to 65535:

duty = pulse length ÷ 20 ms × 65535
AnglePulseDuty value
0°0.5 ms0.5 ÷ 20 × 65535 ≈ 1638
90°1.5 ms1.5 ÷ 20 × 65535 ≈ 4915
180°2.5 ms2.5 ÷ 20 × 65535 ≈ 8192

Code: sweep the servo

from machine import Pin, PWM
import time

servo = PWM(Pin(15))
servo.freq(50)                 # 50 pulses per second = one every 20 ms

def set_angle(angle):
    pulse_ms = 0.5 + (angle / 180) * 2      # 0.5 ms to 2.5 ms
    duty = int(pulse_ms / 20 * 65535)
    servo.duty_u16(duty)

set_angle(0)
time.sleep(1)
set_angle(90)
time.sleep(1)
set_angle(180)
time.sleep(1)

# Smooth sweep from 0° to 180°
for angle in range(0, 181, 5):
    set_angle(angle)
    time.sleep(0.05)
💡 If your servo buzzes or strains at 0° or 180°, it can't quite reach those angles. Use a smaller range, such as 10° to 170°.
💡 To let the servo relax and stop holding its position, use servo.deinit().

Part 8: Putting it all together

Project 1: Button-operated gate

Press the button to open the gate (servo to 90°). Press again to close it (servo to 0°).

from machine import Pin, PWM
import time

button = Pin(14, Pin.IN, Pin.PULL_UP)
servo = PWM(Pin(15))
servo.freq(50)

def set_angle(angle):
    pulse_ms = 0.5 + (angle / 180) * 2
    servo.duty_u16(int(pulse_ms / 20 * 65535))

gate_open = False
set_angle(0)

while True:
    if button.value() == 0:
        gate_open = not gate_open          # flip True ↔ False
        if gate_open:
            set_angle(90)
            print("Gate open")
        else:
            set_angle(0)
            print("Gate closed")
        while button.value() == 0:         # wait for release
            time.sleep(0.01)
        time.sleep(0.05)

Project 2: Automatic bin lid

When a hand comes within 15 cm of the sensor, the lid opens for 3 seconds and then closes.

from machine import Pin, PWM, time_pulse_us
import time

trig = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
servo = PWM(Pin(15))
servo.freq(50)

def set_angle(angle):
    pulse_ms = 0.5 + (angle / 180) * 2
    servo.duty_u16(int(pulse_ms / 20 * 65535))

def get_distance_cm():
    trig.off()
    time.sleep_us(2)
    trig.on()
    time.sleep_us(10)
    trig.off()
    duration = time_pulse_us(echo, 1, 30000)
    if duration < 0:
        return -1
    return duration * 0.0343 / 2

set_angle(0)    # lid closed

while True:
    distance = get_distance_cm()
    if distance != -1 and distance < 15:
        print("Hand detected! Opening lid.")
        set_angle(120)
        time.sleep(3)
        set_angle(0)
        print("Lid closed.")
    time.sleep(0.1)

Part 9: Writing good prompts for coding

AI assistants (such as Claude, ChatGPT or Gemini) can help you write and fix code. But the answer you get is only as good as the question you ask. The instruction you give an AI is called a prompt.

⚠️ Always follow your school's rules on using AI. Use it to learn, not to avoid learning. If you can't explain how your code works, it isn't really your work.

Why prompts matter

The AI can't see your desk, your wiring or your screen. It doesn't know:

  • that you're using a Raspberry Pi Pico W
  • that you're using MicroPython and Thonny
  • which pins you've connected things to
  • what you've already tried
  • that you're in Year 8 and still learning

If you don't tell it, it will guess, and the guess is often wrong. For example, it might write code for an Arduino in C++, or for a Raspberry Pi computer using a different library.

The 6 ingredients of a good coding prompt

IngredientWhat to includeExample
1. Hardware and languageBoard, language, editor"Raspberry Pi Pico W, MicroPython, Thonny"
2. WiringWhat's connected to which GP pin"Button on GP14 to GND, servo signal on GP15"
3. GoalExactly what should happen"When I press the button, the servo moves to 90°, then back to 0° after 2 seconds"
4. Your levelWhat you know already"I'm in Year 8 and know variables, if, for and while loops"
5. The problemError message (copied exactly), what happens vs what you expected"The Shell shows OSError: [Errno 19] ENODEV"
6. How you want helpComments, an explanation, hints only, one step at a time"Add comments to every line and explain how it works afterwards"

Good vs bad prompts

Example 1: Starting a new project

Bad

make a servo code

No hardware, no language, no pin, no idea what the servo should do. You might get Arduino C++ code that won't run on your Pico W at all.

Good

I'm using a Raspberry Pi Pico W with MicroPython in Thonny. I have an SG90 servo with its signal wire on GP15, powered from VBUS. Please write a program that slowly sweeps the servo from 0° to 180° and back again, forever. I'm in Year 8 and know loops and if statements but I'm new to functions, so please add comments explaining each part.

Example 2: Fixing an error

Bad

my code doesnt work fix it

The AI can't see your code or the error. "Doesn't work" could mean a hundred different things.

Good

I'm using a Raspberry Pi Pico W with MicroPython in Thonny. When I click Run I get this error in the Shell:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
NameError: name 'pin' isn't defined

Here is my code:

from machine import Pin
import time

led = pin("LED", Pin.OUT)
led.on()

What does this error mean and how do I fix it? Please explain the reason so I don't make the same mistake again.

(The answer: pin should be Pin with a capital P. Python is case-sensitive!)

Example 3: When the code runs but does the wrong thing

Bad

ultrasonic sensor broken

Is it the wiring, the code or the sensor? What are the readings? The AI has nothing to work with.

Good

I have an HC-SR04P (3.3V version) connected to a Raspberry Pi Pico W: VCC to 3V3(OUT), GND to GND, TRIG to GP3, ECHO to GP2. I'm using MicroPython in Thonny. My code runs with no errors, but it always prints "Out of range" even when my hand is 10 cm away. Here's my code: [paste code]. What could be causing this? Please list the most likely causes in order, including wiring problems I should check.

Example 4: Learning, not just copying

Bad

write my whole homework project for me

You won't learn anything. Your teacher will be able to tell, and you won't be able to fix it when it breaks.

Good

I'm building an automatic bin lid with a Raspberry Pi Pico W (MicroPython). It uses an ultrasonic sensor on GP2/GP3 and a servo on GP15. I've already got the sensor printing distances. Don't write the whole program. Instead, give me a step-by-step plan for what to add next, and a hint for each step. I'll try to write the code myself and come back if I get stuck.

Example 5: Asking for too much at once

Bad

make a robot with 4 servos, 2 sensors, buttons, a screen, a buzzer, LEDs and it should also play music and connect to my phone

Too many things at once. The code will be long and hard to understand, and when it breaks you won't know which part is wrong.

Good

Break it into small steps and ask for one at a time:
Step 1: I'm using a Raspberry Pi Pico W with MicroPython. Help me make one servo on GP15 turn to 90° when a button on GP14 is pressed. Once this works, I'll ask about adding the sensor.

A prompt template you can copy

I'm using a Raspberry Pi Pico W with MicroPython in Thonny.

Wiring:
- [component] → GP[number]
- [component] → GP[number]

What I want it to do:
[describe exactly what should happen]

What I know: I'm in Year 8 and I know [variables, if, for, while, functions...].

[If something is wrong:]
What happens instead: [describe]
Error message (copied exactly): [paste]
My code: [paste]

Please [add comments / explain each line / give hints only / go one step at a time].

After the AI answers: check its work!

AI can make mistakes. Before using any code:

  1. Read it. Do you understand each line? If not, ask the AI to explain it.
  2. Check the pins match your actual wiring.
  3. Check for safety: never trust AI wiring advice that connects 5V to a GP pin. If unsure, ask your teacher.
  4. Test small parts first before running everything at once.
  5. If it's wrong, say so clearly: "That gave this error: [paste]. I'm using MicroPython on a Pico W, not regular Python."

Quick reference card

from machine import Pin, PWM, time_pulse_us
import time

# --- Outputs ---
led = Pin("LED", Pin.OUT)              # Pico W onboard LED
led.on()  /  led.off()  /  led.toggle()

# --- Inputs ---
button = Pin(14, Pin.IN, Pin.PULL_UP)  # pressed = 0
button.value()

# --- Waiting ---
time.sleep(1)        # seconds
time.sleep_ms(100)   # milliseconds
time.sleep_us(10)    # microseconds

# --- PWM / servo ---
servo = PWM(Pin(15))
servo.freq(50)
servo.duty_u16(4915)                   # 90 degrees

# --- Ultrasonic ---
duration = time_pulse_us(echo, 1, 30000)
distance_cm = duration * 0.0343 / 2
Thonny shortcutAction
F5Run
Ctrl+F2Stop / reconnect
Ctrl+SSave
Ctrl+ZUndo

Practice challenges

Try these yourself. Solutions are hidden — attempt each one, then click Show solution to check.

1. What is the difference between physical pin numbers and GP numbers? Which one do you use in code?

2. Why must you never connect the 5V ECHO pin of a standard HC-SR04 directly to a GP pin?

3. Using a pull-up, what does button.value() return when the button is pressed?

4. An ultrasonic echo takes 2000 microseconds. How far away is the object?

5. Write a program that makes the Pico W onboard LED blink 5 times when a button on GP14 is pressed.

6. What duty value (duty_u16) would move a servo to 45°? (Use the formula from Part 7.)

7. Write a program that moves a servo to 0° when an object is more than 30 cm away and to 180° when it is 30 cm or closer.

8. Rewrite this bad prompt as a good one:
pico button not working

Well done! You now know how to read inputs, control outputs, and ask for help effectively. Next, try designing your own invention: an alarm, a game, a robot. The Pico W can bring your ideas to life.