PyRasp

2. Time and patterns

You will be able to

  • pause a program with utime.sleep and utime.sleep_ms,
  • measure how long something took with ticks_ms and ticks_diff,
  • build a repeated pattern without copying and pasting.

You need: the LED from lesson 1. Problems: Double blink, Running lights, Countdown.

The idea

A program runs one line at a time, very fast. If you turn an LED on and off with no pause, it happens thousands of times per second — faster than your eye can see, so it looks dim.

A sleep gives time a chance to pass:

GP13 over two seconds: high for 0.5 s, low for 0.5 s, repeating. One on-and-off cycle takes one second, which is 1 Hz.

The pattern “on 0.5 s, off 0.5 s” is one cycle per second, or 1 Hz.

The exact tools

WhatMicroPythonNotes
Sleep in secondsutime.sleep(0.5)0.5 is half a second
Sleep in millisecondsutime.sleep_ms(500)500 ms = 0.5 s
A millisecond clockutime.ticks_ms()wraps around; use it with ticks_diff
Difference between two ticksutime.ticks_diff(now, started)safe across the wrap
time or utime?They are the same module on the PicoEither import works

Careful. utime.sleep(500) is 500 seconds, not 500 milliseconds. If your LED takes eight minutes to blink, this is why.

Build it

from machine import Pin
import utime

led = Pin(13, Pin.OUT)
for _ in range(4):
    led.on()
    utime.sleep_ms(200)
    led.off()
    utime.sleep_ms(200)

Four short flashes, then stop. Now make it repeat forever:

while True:
    led.toggle()
    utime.sleep(0.5)

Fun fact. “Hz” means per second. A 1 Hz blink is once per second; a 2 Hz blink is twice. Your computer screen is around 60 Hz — it draws 60 pictures every second.

What you should see

The first program flashes four times and ends. The second blinks until you press Stop.


Common mistakes

What you seeWhyFix
The blink is far too slowsleep(500) instead of sleep(0.5)Seconds, not milliseconds
The app seems frozenwhile True: with no sleep insideAdd utime.sleep_ms() in every loop
The LED looks dimNo sleep between on and offGive each state a visible pause
The pattern driftsAdding work inside the loopUse ticks_ms to schedule, or keep the work small

Check yourself

  1. How long is utime.sleep(2)?
  2. What is one cycle of a 2 Hz blink, in seconds?
  3. Why does while True: pass stop the board responding?

Answers: two seconds · 0.5 s · it never sleeps, so the program never gives anything else a turn.

Remember

  • sleep is in seconds, sleep_ms in milliseconds.
  • A cycle is one full on+off; Hz is cycles per second.
  • Every while True loop needs a sleep.

Go further

Next: Lesson 3 — Read a pin