Introductory Examples - Raspberry Pi Pico¶
The following short Python programs will demonstrate essential operation of the
Raspberry Pi Pico board. These use only the onboard hardware and the serial
console. Each can be run by copying the program into code.py
on the
CIRCUITPY drive offered by the board. The text can be pasted directly from this
page, or each file can be downloaded from the CircuitPython sample code folder on this site.
Related Pages
Blink¶
Direct download: pico_blink.py.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # pico_blink.py
# Raspberry Pi Pico - Blink demo
# Blink the onboard LED and print messages to the serial console.
import board
import time
from digitalio import DigitalInOut, Direction, Pull
#================================================================
# Set up the hardware: script equivalent to Arduino setup()
# Set up built-in green LED
led = DigitalInOut(board.LED) # GP25
led.direction = Direction.OUTPUT
#================================================================
# Run the main loop: script equivalent to Arduino loop()
while True:
led.value = True
print("On")
time.sleep(1.0)
led.value = False
print("Off")
time.sleep(1.0)
|
Sieve of Eratosthenes¶
The Sieve of Eratosthenes is an ancient algorithm for finding prime numbers which was popular as a compiler benchmark in the 1980s.
Direct download: pico_sieve.py.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | # pico_sieve.py
# Raspberry Pi Pico - Sieve of Eratosthenes demo
# Calculate all the prime numbers within a range of low integers. Note that
# this is purely computational; nothing depends specifically on CircuitPython,
# and this works fine in a normal desktop Python 3 as well.
import time
size = 40000
# Capture an initial time stamp to compute runtime.
start = time.monotonic()
# Array of boolean flags, one per integer. A True represents a possible prime number,
# a False a composite number.
flags = [True]*size
# Walk up through the array, identifying all prime numbers and removing their
# multiples from the set of integers by setting the corresponding flag to False.
for i in range(2, size):
if flags[i] is True:
# this value is a prime, now remove all the multiples from the set
multiple = 2 * i
while multiple < size:
flags[multiple] = False
multiple += i
# Capture an final time stamp to compute runtime.
end = time.monotonic()
# Any remaining True values are prime
print("Prime numbers:")
for i in range(2, size):
if flags[i] is True:
print(i)
print("Sieve running time:", end - start, "seconds.")
|