PyRasp

4. Remember state

You will be able to

  • keep a value between loops with a variable,
  • detect the moment a button changes instead of holding it,
  • debounce a real button,
  • build a small state machine with modes.

You need: a button, an LED. Problems: Press to toggle, Two-way switch, Short or long?, Three-mode light, Alarm panel, Servo switch.

The idea

So far, the program reacts to what the pin is now. A latch reacts to what changed: the moment the button went from released to pressed. That needs memory:

held = False
...
pressed = button.value() == 1
if pressed and not held:
    # this block runs once per press
    led.toggle()
held = pressed

held stores the previous state. The condition pressed and not held is true only on the edge.

Bounce — the button lies for a few milliseconds

Real contacts bounce. A single press can look like several quick presses. The Pico's simulated buttons bounce for about 5 ms. The fix is a short wait and a second look:

if pressed and not held:
    utime.sleep_ms(20)
    if button.value() == 1:
        ...  # one press, counted once

State machines

A state machine is a program that is always in one of a few named states, with rules for moving between them:

Three states, OFF, BLINK and STEADY. Each press moves to the next state, and a press in STEADY goes back to OFF.

Each state has its own behaviour; each press moves to the next. This is how traffic lights, alarms and menus work.

The exact tools

WhatMicroPython
Compare== (two equals signs), not =
Combineand, or, not
Previous valueyour own variable, e.g. held
A finite statean integer or string variable, e.g. mode = 0
A mode tablea tuple: items = ("Run", "Stop", "Reset")

Build it

Three-mode light:

from machine import Pin
import utime

button = Pin(12, Pin.IN, Pin.PULL_DOWN)
led = Pin(13, Pin.OUT)
mode = 0          # 0 off, 1 blink, 2 steady
held = False
last = 0

while True:
    pressed = button.value() == 1
    if pressed and not held:
        utime.sleep_ms(20)
        if button.value() == 1:
            mode = (mode + 1) % 3
            led.off()
            last = utime.ticks_ms()
            held = True
    elif not pressed:
        held = False

    if mode == 1 and utime.ticks_diff(utime.ticks_ms(), last) >= 250:
        led.toggle()
        last = utime.ticks_ms()
    elif mode == 2:
        led.on()

    utime.sleep_ms(5)

Fun fact. The % 3 is a clock arithmetic trick: 0, 1, 2, then back to 0. It is the same maths a clock uses from 59 minutes to 0.

What you should see

Off → press → blinking → press → steady → press → off. Every press moves exactly one step, even if you hold the button.


Common mistakes

What you seeWhyFix
It toggles many times per pressBounce, or no edge checkWait 20 ms and re-read; keep held
It toggles while heldThe block runs every loopUse pressed and not held
SyntaxError= instead of === assigns, == compares
The button does two stepsBounce on releaseReset held only when the pin is low

Check yourself

  1. What does the held variable store?
  2. Why wait 20 ms before counting a press?
  3. How many states does the three-mode light have?

Answers: the pin's previous level · to let the contacts settle · three (off, blink, steady).

Remember

  • A variable is memory; an edge check needs the previous value.
  • Debounce = wait ~20 ms, then confirm.
  • A state machine has named states and clear transitions.

Go further

Next: Lesson 5 — Measure a voltage