Programming the Raspberry Pi Pico in MicroPython

picoPython360

 

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into Thonny or VS Code project. 

The only downside is that you have to create a project to paste the code into.

To do this follow the instructions in the book.

All of the programs below were copy and pasted from working programs in the IDE. They have been formatted using the built in formatter and hence are not identical in layout to the programs in the book. This is to make copy and pasting them easier. The programs in the book are formatted to be easy to read on the page.

If anything you consider important is missing or if you have any requests or comments  contact:

This email address is being protected from spambots. You need JavaScript enabled to view it. 

Page 30

from machine import Pin
import time

pin = Pin(25, Pin.OUT)

while True:
    pin.value(1)
    time.sleep(1)
    pin.value(0)
    time.sleep(1)

Page 30

from machine import Pin
import time

pin = Pin(22, Pin.OUT)
while True:
    pin.toggle()
    time.sleep(1)

Page 34

from machine import  Pin
pin = Pin(22, Pin.OUT)
while True:
    pin.value(1)
    pin.value(0)

Page 34

from machine import  Pin
def flash():
    pin = Pin(22, Pin.OUT)
    while True:
        pin.value(1)
        pin.value(0)
flash()

Page 35

from machine import Pin


@micropython.native
def flash():
    pin = Pin(22, Pin.OUT)
    while True:
        pin.value(1)
        pin.value(0)
 
flash()

Page 36

from machine import Pin
import time

pin = Pin(22, Pin.OUT)
while True:
    pin.value(1)
    time.sleep(0.5)
    pin.value(0)
    time.sleep(0.5)

Page 36

from machine import Pin
import time

pin = Pin(22, Pin.OUT)
while True:
    pin.value(1)
    time.sleep_us(10)
    pin.value(0)
    time.sleep_us(10)

Page 32

from machine import Pin
import time
pin = Pin(22, Pin.OUT)
n = 10
while True:
    for i in range(n):
        pass
    pin.value(1)
    for i in range(n):
        pass
    pin.value(0)

Page 38

from machine import Pin

pin1 = Pin(21, Pin.OUT)
pin2 = Pin(22, Pin.OUT)
while True:
    pin1.value(1)
    pin2.value(0)
    pin1.value(0)
    pin2.value(1)

Page 41

from machine import Pin
import machine

def gpio_get():
    return machine.mem32[0xd0000000+0x010]

def gpio_set(value, mask):
    machine.mem32[0xd0000000 +  0x01C] = (machine.mem32[0xd0000000+0x010]) ^ value & mask


pin = Pin(22, Pin.OUT)
pin = Pin(21, Pin.OUT)
value1 = 1 << 22 | 0 << 21
value2 = 0 << 22 | 1 << 21
mask = 1 << 22 | 1 << 21
while True:
    gpio_set(value1, mask)
    gpio_set(value2, mask)

Page 61

from machine import Pin
import time
pinIn = Pin(22, Pin.IN, Pin.PULL_DOWN)
pinLED = Pin(25, Pin.OUT)

while True:
    if pinIn.value():
        pinLED.on()
    else:
        pinLED.off()
    time.sleep(0.5)

Page 62

from machine import Pin
import time
pinIn = Pin(22, Pin.IN, Pin.PULL_DOWN)
pinLED = Pin(25, Pin.OUT)

while True:
    while pinIn.value() == 0:
        pass
    while pinIn.value() == 1:
        pass
    pinLED.on()
    time.sleep(1)
    pinLED.off()

Page 63

 
from machine import Pin
import time
pinIn = Pin(22, Pin.IN, Pin.PULL_DOWN)
pinLED = Pin(25, Pin.OUT)

while True:
    while pinIn.value() == 0:
        pass
    t = time.ticks_ms()
    time.sleep_ms(1)
    while pinIn.value() == 1:
        pass
    t = time.ticks_diff(time.ticks_ms(), t)
    if t < 2000:
        pinLED.on()
        time.sleep(1)
        pinLED.off()
    else:
        for i in range(10):
            pinLED.on()
            time.sleep_ms(100)
            pinLED.off()
            time.sleep_ms(100)

Page 64

from machine import Pin
import time
pinIn = Pin(22, Pin.IN)

while True:
    while pinIn.value() == 1:
        pass
    while pinIn.value() == 0:
        pass

    t = time.ticks_us()
    while pinIn.value() == 1:
        pass
    t = time.ticks_diff(time.ticks_us(), t)
    print(t)
    time.sleep(1)

Page 65

import time
import machine

pinIn = machine.Pin(22, machine.Pin.IN)

while True:
    t = machine.time_pulse_us(pinIn, 1)
    print(t)
    time.sleep(1)

Page 65

import machine
import time

import machine
pinIn = machine.Pin(22, machine.Pin.IN)

while True:
    while pinIn.value() == 1:
        pass
    t = machine.time_pulse_us(pinIn, 1)
    print(t)
    time.sleep(1)

Page 68

from machine import Pin
import time
pinIn = Pin(22, Pin.IN)

s = 0
count = 0
while True:
    i = pinIn.value()
    t = time.ticks_add(time.ticks_us(), 1000*100)
    if s == 0:  # button not pushed
        if i:
            s = 1
            count = count+1
            print("Button Push ", count)
    elif s == 1:  # button pushed
        if not i:
            s = 0
    else:
        s = 0
    while time.ticks_us() < t:
        pass

Page 70

from machine import Pin
import time
pinIn = Pin(22, Pin.IN)

s = 0
while True:
    i = pinIn.value()
    t = time.ticks_add(time.ticks_us(), 1000*100)
    if s == 0:  # button not pushed
        if i:
            s = 1
        tpush = t
    elif s == 1:  # button pushed
        if not i:
            s = 0
            if time.ticks_diff(t, tpush) > 2000000:
                print("Button held \n\r")
            else:
                print("Button pushed \n\r")
    else:
        s = 0
    while time.ticks_us() < t:
        pass

Page 71  Corrected - see Erata.

from machine import Pin
import time
pinIn = Pin(22, Pin.IN)
pinLED1 = Pin(21, Pin.OUT)
pinLED2 = Pin(20, Pin.OUT)
pinLED3 = Pin(19, Pin.OUT)
pinLED1.on()
pinLED2.off()
pinLED3.off()
s=0
buttonState=pinIn.value()
while True:
    buttonNow=pinIn.value()
    edge=buttonState-buttonNow
    buttonState=buttonNow
    t=time.ticks_add(time.ticks_us(),1000*100)
    if s==0:
        if edge==1:
            s=1
            pinLED1.off()
            pinLED2.on()
            pinLED3.off()
    
    elif s==1:
        if edge==1:
            s=2
            pinLED1.off()
            pinLED2.off()
            pinLED3.on()
    elif s==2:
        if edge==1:
            s=0
            pinLED1.on()
            pinLED2.off()
            pinLED3.off()
    else:
        s=0
    while time.ticks_us()<t:
        pass

Page 79

from utime import sleep
from machine import Pin
import machine


def gpio_get_events(pinNo):
    mask = 0xF << 4 * (pinNo % 8)
    intrAddr = 0x40014000 + 0x0f0 + (pinNo // 8)*4
    return (machine.mem32[intrAddr] & mask) >> (4 * (pinNo % 8))


def gpio_clear_events(pinNo, events):
    intrAddr = 0x40014000 + 0x0f0 + (pinNo // 8)*4
    machine.mem32[intrAddr] = events << (4 * (pinNo % 8))


pin = Pin(22, Pin.IN, Pin.PULL_UP)
while True:
    event = gpio_get_events(22)
    if(event & Pin.IRQ_FALLING):
        print("falling")
    if(event & Pin.IRQ_RISING):
        print("rising")
    gpio_clear_events(22, Pin.IRQ_FALLING | Pin.IRQ_RISING)
    sleep(0.5)

Page 79

from utime import sleep
from machine import Pin

pin = Pin(22, Pin.IN, Pin.PULL_DOWN)

print("Press Button")
sleep(10)
if pin.value():
    print("Button Pressed")
else:
    print("Button Not Pressed")

Page 80

from utime import sleep
from machine import Pin
import machine


def gpio_get_events(pinNo):
    mask = 0xF << 4 * (pinNo % 8)
    intrAddr = 0x40014000 + 0x0f0 + (pinNo // 8)*4
    return (machine.mem32[intrAddr] & mask) >> (4 * (pinNo % 8))


def gpio_clear_events(pinNo, events):
    intrAddr = 0x40014000 + 0x0f0 + (pinNo // 8)*4
    machine.mem32[intrAddr] = events << (4 * (pinNo % 8))


pin = Pin(22, Pin.IN, Pin.PULL_DOWN)

print("Press Button")
gpio_clear_events(22, Pin.IRQ_FALLING)
sleep(10)
event = gpio_get_events(22)
gpio_clear_events(22, Pin.IRQ_FALLING)
if event & Pin.IRQ_FALLING:
    print("Button Pressed")
else:
    print("Button Not Pressed")

Page 81

import time
from utime import sleep
from machine import Pin
import machine


def gpio_get_events(pinNo):
    mask = 0xF << 4 * (pinNo % 8)
    intrAddr = 0x40014000 + 0x0f0 + (pinNo // 8)*4
    return (machine.mem32[intrAddr] & mask) >> (4 * (pinNo % 8))


def gpio_clear_events(pinNo, events):
    intrAddr = 0x40014000 + 0x0f0 + (pinNo // 8)*4
    machine.mem32[intrAddr] = events << (4 * (pinNo % 8))


pin = Pin(22, Pin.IN, Pin.PULL_DOWN)
while True:
    gpio_clear_events(22, Pin.IRQ_FALLING | Pin.IRQ_RISING)
    while not(gpio_get_events(22) & Pin.IRQ_RISING):
        pass
    t = time.ticks_us()
    while not(gpio_get_events(22) & Pin.IRQ_FALLING):
        pass
    t = time.ticks_diff(time.ticks_us(), t)
    print(t)
    sleep(1)

Page 84

import time
from machine import Pin
import machine
import array

count = 0
t = array.array('L', [0]*20)


def myHandler(pin):
    global t, count
    t[count] = time.ticks_us()
    count = count+1
    if count > 19:
        for i in range(1, 20):
            print(time.ticks_diff(t[i], t[i-1]))
        pin.irq(None, Pin.IRQ_RISING, hard=True)
        return


pin = Pin(22, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_RISING, hard=False)

Page 86

import time
from machine import Pin


def myHandler(pin):
    print(time.ticks_us())


pin = Pin(22, Pin.IN, Pin.PULL_DOWN)
pin.irq(myHandler, Pin.IRQ_RISING, hard=True)
while True:
    print("doing something useful")

Page 92

from machine import Pin, PWM
pwm16 = PWM(Pin(16))
pwm17 = PWM(Pin(17))

pwm16.freq(250)

pwm16.duty_u16(65535//2)
pwm17.duty_u16(65535//4)

Page 93

from machine import Pin, PWM
import machine


def pwm_set_phase(sliceNo, phase):
    Addr = 0x40050000 + 0x14*sliceNo
    if phase:
        machine.mem32[Addr] = machine.mem32[Addr] | 0x2
    else:
        machine.mem32[Addr] = machine.mem32[Addr] & 0xFFFFFFFD


pwm16 = PWM(Pin(16))
pwm17 = PWM(Pin(17))
pwm16.freq(250)
pwm_set_phase(0, True)
pwm16.duty_u16(65535//2)
pwm17.duty_u16(65535//4)

Page 94

from machine import Pin, PWM
import machine


def pwm_set_polarity(sliceNo, channel, invert):
    Addr = 0x40050000 + 0x14*sliceNo
    if invert:
        machine.mem32[Addr] = machine.mem32[Addr] | 0x1 << (2+channel)
    else:
        machine.mem32[Addr] = machine.mem32[Addr] & ~(0x1 << (2+channel))


pwm16 = PWM(Pin(16))
pwm17 = PWM(Pin(17))

pwm16.freq(250)
pwm_set_polarity(0, 1, True)
pwm16.duty_u16(65535//4)
pwm17.duty_u16(65535//4)

Page 95

from machine import Pin, PWM

pwm16 = PWM(Pin(16))

pwm16.freq(50)

pwm16.duty_u16(65535//2)
while True:
    pwm16.duty_u16(65535//2)
    pwm16.duty_u16(65535//4)

Page 98

from machine import Pin, PWM
import array
import machine
import math


def pwm_get_wrap(sliceNo):
    Addr = 0x40050000 + 0x10+0x14*sliceNo
    return (machine.mem32[Addr])


wave = array.array('H', [0]*256)
for i in range(256):
    wave[i] = int(65535//2 + (math.sin(i * 2.0 * 3.14159 / 256.0) * 65535//2))


pwm16 = PWM(Pin(16))
pwm16.freq(125000000//256)

print(pwm_get_wrap(0))
while(True):
    for i in range(256):
        pwm16.duty_u16(wave[i])

Page 28

from utime import sleep_ms
from machine import Pin, PWM

pwm25 = PWM(Pin(25))
pwm25.freq(2000)

while True:
    for d in range(0,65535,655):
        pwm25.duty_u16(d)
        sleep_ms(50)

Page 101

from utime import sleep_ms
from machine import Pin, PWM

pwm25 = PWM(Pin(25))
pwm25.freq(2000)

while True:
    for b in range(0,100):
        pwm25.duty_u16(int(65535*b*b*b/1000000))
        sleep_ms(50)

Page 111

from machine import Pin, PWM
from time import sleep

class Motor:
    def __init__(self, pinNo):
        self.gpio = pinNo
        self._on = False
        self.speed=0

        self.pwm1=PWM(Pin(pinNo))
        self.pwm1.freq(2000)
        self.pwm1.duty_u16(0)

    def setSpeed(self,s):
        self._on=True
        self.speed=s
        self.pwm1.duty_u16(int(65535*s/100))
    
    def off(self):
        self._on=False
        self.pwm1.duty_u16(0)
    
    def on(self):
        self._on=True
        self.pwm1.duty_u16(int(65535*self.speed/100))

motor=Motor(16)
motor.setSpeed(50)
sleep(1)
motor.off()
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.off()

Page 116

from machine import Pin, PWM
from time import sleep

class Motor:
    def __init__(self, pinNo):
        self.gpio = pinNo
        self._on = False
        self.speed=0

        self.pwm1=PWM(Pin(pinNo))
        self.pwm1.freq(2000)
        self.pwm1.duty_u16(0)

    def setSpeed(self,s):
        self._on=True
        self.speed=s
        self.pwm1.duty_u16(int(65535*s/100))
    
    def off(self):
        self._on=False
        self.pwm1.duty_u16(0)
    
    def on(self):
        self._on=True
        self.pwm1.duty_u16(int(65535*self.speed/100))

class BiMotor(Motor):
    def __init__(self, pinNo):
        super().__init__(pinNo)
        self.forward=True
        self.pwm2=PWM(Pin(pinNo+1))
        self.pwm2.duty_u16(0)
    
    def setForward(self,forward):
        if self.forward==forward:
            return
        self.pwm1.duty_u16(0)
        self.pwm1,self.pwm2=self.pwm2,self.pwm1        
        self.forward=forward
        self.pwm1.duty_u16(int(65535*self.speed/100))

motor=BiMotor(16)
motor.setSpeed(50)
sleep(1)
motor.setForward(False)
sleep(1)
motor.setSpeed(90)
sleep(1)
motor.setForward(True)
motor.off()

Page 115

from machine import Pin, PWM
from time import sleep

class Servo:
    def __init__(self, pinNo):
        self.pwm = PWM(Pin(pinNo))
        self.pwm.freq(50)
        self.position = 65535*2.5/100

    def setPosition(self, p):
        self.position = p
        self.pwm.duty_u16(int(65535*p/1000 + 65535*2.5/100))

servo=Servo(16)
servo.setPosition(100.0)
sleep(1)
servo.setPosition(50.0)
sleep(1)
servo.setPosition(0)

Page 120

from machine import Pin, PWM
import machine
from time import sleep


class Servo:
    def __init__(self, pinNo):
        self.pwm = PWM(Pin(pinNo))
        self.pin = pinNo
        self.pwm.freq(50)
        self.position = 65535*2.5/100

    def setPosition(self, p):
        self.position = p
        self.pwm.duty_u16(int(65535*p/1000 + 65535*2.5/100))

    def getSlice(self):
        return (self.pin >> 1) & 0x07

    def getChannel(self):
        return self.pin & 1

    def setPolarity(self, invert):
        sliceNo = self.getSlice()
        channel = self.getChannel()
        Addr = 0x40050000 + 0x14*sliceNo
        if invert:
            machine.mem32[Addr] = machine.mem32[Addr] | 0x1 << (2+channel)
        else:
            machine.mem32[Addr] = machine.mem32[Addr] & ~(0x1 << (2+channel))


servo = Servo(16)
servo.setPolarity(True)
servo.setPosition(100.0)
sleep(1)
servo.setPosition(50.0)
sleep(1)
servo.setPosition(0)

Page 134

from utime import sleep_ms
from machine import Pin
import machine


class StepperBi4():
    def __init__(self, pinA):
        self.phase = 0
        self.pinA = pinA
        self.timer = None
        self.forward = True
        self.speed = 0

        self.gpios = tuple([Pin(pinA, Pin.OUT), Pin(
            pinA+1, Pin.OUT), Pin(pinA+2, Pin.OUT), Pin(pinA+3, Pin.OUT)])
        self.gpios[0].high()
        self.gpioMask = 0xF << self.pinA
        self.halfstepSeq = [0x1, 0x3, 0x2, 0x6, 0x4, 0xC, 0x8, 0x9]
#   [
#             [0,0,0,1],
#             [0,0,1,1],
#             [0,0,1,0],
#             [0,1,1,0],
#             [0,1,0,0],
#             [1,1,0,0],
#             [1,0,0,0],
#             [1,0,0,1]
#    ]

    def _gpio_set(self, value, mask):
        machine.mem32[0xd0000000 +
                      0x01C] = (machine.mem32[0xd0000000+0x010] ^ value) & mask

    def setPhase(self, phase):
        value = self.halfstepSeq[phase] << self.pinA
        self._gpio_set(value, self.gpioMask)
        self.phase = phase

    def stepForward(self):
        self.phase = (self.phase+1) % 8
        self.setPhase(self.phase)

    def stepReverse(self):
        self.phase = (self.phase-1) % 8
        self.setPhase(self.phase)

    def doRotate(self, timer):
        if self.forward:
            self.stepForward()
        else:
            self.stepReverse()

    def rotate(self, forward, speed):
        self.forward = forward
        self.speed = speed
        if speed == 0:
            self.timer.deinit()
            self.timer = None
            return
        if self.timer == None:
            self.timer = machine.Timer()
        self.timer.init(freq=speed, mode=machine.Timer.PERIODIC,
                        callback=self.doRotate)


step = StepperBi4(16)
step.setPhase(0)
while True:
    step.rotate(True, 100)
    sleep_ms(500)
    step.rotate(True, 0)
    sleep_ms(500)

Page 144

from machine import Pin, SPI

spi = SPI(0, sck=Pin(6), miso=Pin(4), mosi=Pin(7))
spi.init(baudrate=500_000, bits=8, polarity=0, phase=0, firstbit=SPI.MSB)

read = bytearray(3)
write = bytearray([0xAA, 0xAA, 0xAA])
spi.write_readinto(write, read)

print(read, write)
spi.deinit()

Page 150

from utime import sleep_ms
from machine import Pin, SPI
from time import sleep

spi = SPI(0, sck=Pin(18), miso=Pin(16), mosi=Pin(19))
spi.init(baudrate=500_000, bits=8, polarity=0, phase=0, firstbit=SPI.MSB)

CS = Pin(17, Pin.OUT)
CS.high()
sleep_ms(1)

write = bytearray([0xD0])
CS.low()
spi.write(write)
read = spi.read(1)
CS.high()
print("Chip ID is", hex(read[0]))

CS.low()
write = bytearray([0xF2, 0x01])
spi.write(write)
write = bytearray([0xF4, 0x27])
spi.write(write)
CS.high()

CS.low()
write = bytearray([0xF7])
spi.write(write)
sleep_ms(10)
rBuff = spi.read(8)
CS.high()

pressure = (rBuff[0] << 12) | (rBuff[1] << 4) | (rBuff[2] >> 4)
temperature = (rBuff[3] << 12) | (rBuff[4] << 4) | (rBuff[5] >> 4)
humidity = rBuff[6] << 8 | rBuff[7]

print("Humidity = ", humidity)
print("Pressure = ", pressure)
print("Temp. = ", temperature)

Page 155

import machine
import utime
sensor_temp = machine.ADC(4)
conversion_factor = 3.3 / (65535)

while True:
    reading = sensor_temp.read_u16() * conversion_factor
    temperature = 27 - (reading - 0.706)/0.001721
    print(temperature)
    utime.sleep(2)

Page 161

from utime import sleep_ms
from machine import Pin, SPI
from time import sleep

spi = SPI(0, sck=Pin(18), miso=Pin(16), mosi=Pin(19))
spi.init(baudrate=500_000, bits=8, polarity=0, phase=0, firstbit=SPI.MSB)
CS = Pin(17, Pin.OUT)
CS.high()
sleep_ms(1)
CS.low()
write = bytearray([0x01, 0x80, 0x00])
read = bytearray(3)
spi.write_readinto(write, read)
CS.high()
data = (read[1] & 0x03) << 8 | read[2]
volts = data * 3.3 / 1023.0
print(volts)
spi.deinit()

Page 162

from utime import sleep_ms
from machine import Pin, SPI
from time import sleep


class spiADC:
    def __init__(self, spi, sckNo, misoNo, mosiNo, CSNo):
        self.spi = SPI(spi, sck=Pin(sckNo), miso=Pin(misoNo), mosi=Pin(mosiNo))
        self.spi.init(baudrate=500_000, bits=8, polarity=0,
                      phase=0, firstbit=SPI.MSB)
        self.CS = Pin(CSNo, Pin.OUT)
        self.CS.high()
        sleep_ms(1)

    def read(self, chan):
        write = bytearray([0x01, (0x08 | chan) << 4, 0x00])
        self.CS.low()
        read = bytearray(3)
        self.spi.write_readinto(write, read)
        self.CS.high()
        data = (read[1] & 0x03) << 8 | read[2]
        volts = data * 3.3 / 1023.0
        return volts


adc = spiADC(0, 18, 16, 19, 17)
volts = adc.read(1)
print(volts)

Page 176

from machine import Pin,I2C

i2c0=I2C(0,scl=Pin(17),sda=Pin(16),freq=400000)

buf = bytearray([0xE7])
i2c0.writeto( 0x40, buf, True)
read= i2c0.readfrom(0x40, 1, True)
print("User Register =",read)

Page 178

from utime import sleep_ms
from machine import Pin, I2C
from time import sleep

i2c0 = I2C(0, scl=Pin(17), sda=Pin(16), freq=100*1000)

buf = bytearray([0xE3])
i2c0.writeto(0x40, buf, False)
read = i2c0.readfrom(0x40, 3, True)
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)

Page 182

from utime import sleep_ms
from machine import Pin, I2C
from time import sleep


def crcCheck(msb, lsb, check):
    data32 = (msb << 16) | (lsb << 8) | check
    divisor = 0x988000
    for i in range(16):
        if data32 & 1 << (23 - i):
            data32 ^= divisor
        divisor >>= 1
    return data32


i2c0 = I2C(0, scl=Pin(17), sda=Pin(16), freq=100*1000)

buf = bytearray([0xE3])
i2c0.writeto(0x40, buf, False)
read = i2c0.readfrom(0x40, 3, True)
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)

data16 = (msb << 8) | (lsb & 0xFC)
temp = (-46.85 + (175.72 * data16 / (1 << 16)))
print("Temperature C ", temp)
print("Checksum=", crcCheck(msb, lsb, check))

buf = bytearray([0xF5])
i2c0.writeto(0x40, buf, True)
read = bytearray(3)
while True:
    sleep_ms(1)
    try:
        i2c0.readfrom_into(0x40, read, True)
        break
    except:
        continue
msb = read[0]
lsb = read[1]
check = read[2]
print("msb lsb checksum =", msb, lsb, check)
data16 = (msb << 8) | (lsb & 0xFC)
hum = -6 + (125.0 * data16) / 65536
print("Humidity ", hum)
print("Checksum=", crcCheck(msb, lsb, check))

Page 190

import rp2
from machine import Pin


@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW, )
def blink():
    label("again")
    set(pins, 1)
    set(pins, 0)
    jmp("again")


sm = rp2.StateMachine(0, blink, freq=2000, set_base=Pin(16))
sm.active(1)

Page 193

import rp2
from machine import Pin

@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW, )
def blink():
    label("again")
    set(pins, 1)
    set(x,31)
    label("loop1")
    nop() [31]
    jmp(x_dec,"loop1")  
    set(pins, 0)  
    set(x,31)
    label("loop2")
    nop() [31]
    jmp(x_dec,"loop2") 
    jmp("again")  


sm = rp2.StateMachine(0, blink, freq=2000, set_base=Pin(16))
sm.active(1)

Page 194

import rp2
from machine import Pin


@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW, )
def squarewave():
    pull(block)
    label("again")
    set(pins, 1)
    mov(x, osr)
    label("loop1")
    jmp(x_dec, "loop1")
    set(pins, 0)
    mov(x, osr)
    label("loop2")
    jmp(x_dec, "loop2")
    jmp("again")


sm = rp2.StateMachine(0, squarewave, freq=2000, set_base=Pin(16))
sm.active(1)
sm.put(0xFFF)

Page 196

import rp2
from machine import Pin


@rp2.asm_pio(out_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW))
def output():
    pull(block)
    label("again")
    out(pins, 2)
    jmp("again")


sm = rp2.StateMachine(0, output, freq=2000, out_base=Pin(
    16), out_shiftdir=rp2.PIO.SHIFT_RIGHT)
sm.active(1)
sm.put(0xFEDCBA98)

Page 198

import rp2
from machine import Pin


@rp2.asm_pio(out_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW), autopull=True)
def output():
    label("again")
    out(pins, 2)
    jmp("again")


sm = rp2.StateMachine(0, output, freq=2000, out_base=Pin(
    16), out_shiftdir=rp2.PIO.SHIFT_RIGHT)
sm.active(1)
while True:
    sm.put(0xFEDCBA98)

Page 200

import rp2
from machine import Pin

@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW)
def squarewave():
    label("again")    
    nop().side(1)
    jmp("again").side(0) 

sm = rp2.StateMachine(0, squarewave, freq=2000,sideset_base=Pin(16))
sm.active(1)

Page 200

import rp2
from machine import Pin


@rp2.asm_pio(sideset_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW))
def squarewave():
    label("again")
    nop().side(2)
    jmp("again").side(1)


sm = rp2.StateMachine(0, squarewave, freq=2000, sideset_base=Pin(16))
sm.active(1)

Page 202

import rp2
from machine import Pin


@rp2.asm_pio()
def light():
    label("again")
    in_(pins, 1)
    push(block)
    jmp("again")


LED = Pin(25, mode=Pin.OUT)
in1 = Pin(16, mode=Pin.IN)
sm = rp2.StateMachine(0, light, freq=2000, in_base=Pin(16))
sm.active(1)
while True:
    flag = sm.get()
    if (flag == 0):
        LED.value(0)
    else:
        LED.value(1)

Page 204

import rp2
from machine import Pin


@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)
def squarewave():
    label("again")
    wait(0, pin, 0)
    wait(1, pin, 0)
    set(pins, 1)
    set(pins, 0)
    jmp("again")


in1 = Pin(16, mode=Pin.IN)
sm = rp2.StateMachine(0, squarewave, freq=2000,
                      in_base=Pin(16), set_base=Pin(17))
sm.active(1)

Page 217

from machine import Pin
from utime import sleep_ms, ticks_us


class DHT22():
    def __init__(self, gpio):
        self.pin = gpio
        self.pin = Pin(2, mode=Pin.OUT)
        self.pin.high()
        self.checksum = 0
        self.temperature = 0
        self.humidity = 0
        sleep_ms(1)

    def getReading(self):
        DHT = self.pin
        DHT.low()
        sleep_ms(1)
        DHT.init(mode=Pin.IN)
        for i in range(2):
            while DHT.value() == 1:
                pass
            while DHT.value() == 0:
                pass

        data = 0
        t1 = ticks_us()
        for i in range(32):
            while DHT.value() == 1:
                pass
            while DHT.value() == 0:
                pass
            t2 = ticks_us()
            data = data << 1
            data = data | ((t2 - t1) > 100)
            t1 = t2

        checksum = 0
        for i in range(8):
            while DHT.value() == 1:
                pass
            while DHT.value() == 0:
                pass
            t2 = ticks_us()
            checksum = checksum << 1
            checksum = checksum | ((t2 - t1) > 100)
            t1 = t2
        byte1 = (data >> 24 & 0xFF)
        byte2 = (data >> 16 & 0xFF)
        byte3 = (data >> 8 & 0xFF)
        byte4 = (data & 0xFF)
        self.checksum = (checksum == (byte1+byte2+byte3+byte4) & 0xFF)
        self.humidity = ((byte1 << 8) | byte2) / 10.0
        neg = byte3 & 0x80
        byte3 = byte3 & 0x7F
        self.temperature = (byte3 << 8 | byte4) / 10.0
        if neg > 0:
            self.temperature = -self.temperature


dht = DHT22(2)
dht.getReading()
print("Checksum", dht.checksum)
print("Humidity= ", dht.humidity)
print("Temperature=", dht.temperature)

Page 220

import rp2
from machine import Pin


@rp2.asm_pio(set_init=rp2.PIO.OUT_LOW, autopush=True, in_shiftdir=rp2.PIO.SHIFT_RIGHT)
def dht22():
    wrap_target()
    label("again")
    pull(block)
    set(pins, 0)
    mov(x, osr)
    label("loop1")
    jmp(x_dec, "loop1")
    set(pindirs, 0)

    wait(1, pin, 0)
    wait(0, pin, 0)
    wait(1, pin, 0)
    wait(0, pin, 0)

    set(y, 31)
    label("bits")
    wait(1, pin, 0)
    set(x, 0)
    label("loop2")
    jmp(x_dec, "continue")
    label("continue")
    jmp(pin, "loop2")
    in_(x, 4)
    jmp(y_dec, "bits")

    set(y, 7)
    label("check")
    wait(1, pin, 0)
    set(x, 0)
    label("loop3")
    jmp(x_dec, "continue2")
    label("continue2")
    jmp(pin, "loop3")
    in_(x, 4)
    jmp(y_dec, "check")
    wrap()


class DHT22():
    def __init__(self, gpio):
        self.sm = rp2.StateMachine(0, dht22, freq=976562, in_base=Pin(
            gpio), set_base=Pin(gpio), jmp_pin=Pin(gpio))
        self.sm.active(1)

    def getByte(self):
        count = self.sm.get()
        byte = 0
        for i in range(8):
            byte = byte << 1
            if ((count >> i * 4) & 0x0F) > 8:
                byte = byte | 1
        return byte

    def getReading(self):
        self.sm.put(1000)
        byte1 = self.getByte()
        print(byte1)
        byte2 = self.getByte()
        byte3 = self.getByte()
        print(hex(byte2))
        byte4 = self.getByte()
        checksum = self.getByte()
        self.checksum = (checksum == (byte1+byte2+byte3+byte4) & 0xFF)
        self.humidity = ((byte1 << 8) | byte2) / 10.0
        neg = byte3 & 0x80
        byte3 = byte3 & 0x7F
        self.temperature = (byte3 << 8 | byte4) / 10.0
        if neg > 0:
            self.temperature = -self.temperature


dht = DHT22(2)
dht.getReading()
print("Checksum", dht.checksum)
print("Humidity= ", dht.humidity)
print("Temperature=", dht.temperature)

Page 226

import rp2
from machine import Pin


@rp2.asm_pio(set_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_LOW), autopush=True, in_shiftdir=rp2.PIO.SHIFT_LEFT)
def dht22():
    wrap_target()
    label("again")
    pull(block)
    set(pins, 0)
    mov(x, osr)
    label("loop1")
    jmp(x_dec, "loop1")
    set(pindirs, 0)

    wait(1, pin, 0)
    wait(0, pin, 0)
    wait(1, pin, 0)
    wait(0, pin, 0)

    set(y, 31)
    label("bits")
    wait(1, pin, 0)[25]
    in_(pins, 1)
    wait(0, pin, 0)
    jmp(y_dec, "bits")

    set(y, 7)
    label("check")
    wait(1, pin, 0)[25]
    set(pins, 2)
    set(pins, 0)
    in_(pins, 1)
    wait(0, pin, 0)
    jmp(y_dec, "check")
    push(block)
    wrap()


class DHT22():
    def __init__(self, gpio):
        self.sm = rp2.StateMachine(0, dht22, freq=490196, in_base=Pin(
            gpio), set_base=Pin(gpio), jmp_pin=Pin(gpio))
        self.sm.active(1)

    def getReading(self):
        self.sm.put(500)
        data = 0
        data = self.sm.get()
        byte1 = (data >> 24 & 0xFF)
        byte2 = (data >> 16 & 0xFF)
        byte3 = (data >> 8 & 0xFF)
        byte4 = (data & 0xFF)
        checksum = self.sm.get() & 0xFF
        self.checksum = (checksum == (byte1+byte2+byte3+byte4) & 0xFF)
        self.humidity = ((byte1 << 8) | byte2) / 10.0
        neg = byte3 & 0x80
        byte3 = byte3 & 0x7F
        self.temperature = (byte3 << 8 | byte4) / 10.0
        if neg > 0:
            self.temperature = -self.temperature


dht = DHT22(2)
dht.getReading()
print("Checksum", dht.checksum)
print("Humidity= ", dht.humidity)
print("Temperature=", dht.temperature)

Page 245

from utime import sleep_ms, sleep_us
from machine import Pin
from time import sleep


class DS18B20:
    def __init__(self, pin):
        self.pin = Pin(pin, mode=Pin.IN)
        self.pin.high()

    def presence(self):
        self.pin.init(mode=Pin.OUT)
        self.pin.high()
        sleep_ms(1)
        self.pin.low()
        sleep_us(480)
        self.pin.init(mode=Pin.IN)
        sleep_us(70)
        b = self.pin.value()
        sleep_us(410)
        return b

    @micropython.native
    def writeBit(self, b):
        if b == 1:
            delay1 = 1
            delay2 = 30
        else:
            delay1 = 30
            delay2 = 0
        self.pin.low()
        for i in range(delay1):
            pass
        self.pin.high()
        for i in range(delay2):
            pass

    def writeByte(self, byte):
        self.pin.init(mode=Pin.OUT)
        for i in range(8):
            self.writeBit(byte & 1)
            byte = byte >> 1
        self.pin.init(mode=Pin.IN)

    @micropython.native
    def readBit(self):
        self.pin.init(mode=Pin.OUT)
        self.pin.low()
        self.pin.high()
        self.pin.init(mode=Pin.IN)
        b = self.pin.value()
        sleep_us(60)
        return b

    def readByte(self):
        byte = 0
        for i in range(8):
            byte = byte | self.readBit() << i
        return byte

    def convert(self):
        self.writeByte(0x44)
        for i in range(500):
            sleep_ms(10)
            if self.readBit() == 1:
                j = i
                break
        return j

    def crc8(self, data, len):
        crc = 0
        for i in range(len):
            databyte = data[i]
            for j in range(8):
                temp = (crc ^ databyte) & 0x01
                crc >>= 1
                if temp:
                    crc ^= 0x8C
                databyte >>= 1
        return crc

    def getTemp(self):
        if self.presence() == 1:
            return -1000
        self.writeByte(0xCC)
        if self.convert() == 500:
            return -3000
        self.presence()
        self.writeByte(0xCC)
        self.writeByte(0xBE)
        data = []
        for i in range(9):
            data.append(self.readByte())
        if self.crc8(data, 9) != 0:
            return -2000
        t1 = data[0]
        t2 = data[1]
        temp1 = (t2 << 8 | t1)
        if t2 & 0x80:
            temp1 = temp1 | 0xFFFF0000
        return temp1/16


dS18B20 = DS18B20(2)
if dS18B20.presence() == 1:
    print("No device")
else:
    print("Device present")

print(dS18B20.getTemp())

Page 253

import rp2
from machine import Pin
from utime import sleep_ms


@rp2.asm_pio(set_init=rp2.PIO.OUT_HIGH, out_init=rp2.PIO.OUT_HIGH, autopush=True, push_thresh=8)
def DS1820():
    wrap_target()
    label("again")
    pull(block)
    mov(x, osr)
    jmp(not_x, "read")
    label("write")
    set(pindirs, 1)
    set(pins, 0)
    label("loop1")
    jmp(x_dec, "loop1")
    set(pindirs, 2)[31]
    wait(1, pin, 0)[31]

    pull(block)
    mov(x, osr)
    label("bytes1")
    pull(block)
    set(y, 7)
    set(pindirs, 3)
    label("bit1")
    set(pins, 0)[1]
    out(pins, 1)[31]
    set(pins, 1)[20]
    jmp(y_dec, "bit1")
    jmp(x_dec, "bytes1")
    set(pindirs, 0)[31]
    jmp("again")

    label("read")
    pull(block)
    mov(x, osr)
    label("bytes2")
    set(y, 7)
    label("bit2")
    set(pindirs, 1)
    set(pins, 0)[1]
    set(pindirs, 0)[5]
    in_(pins, 1)[10]
    jmp(y_dec, "bit2")
    jmp(x_dec, "bytes2")
    wrap()


class DS18B20:
    def __init__(self, pin):
        self.sm = rp2.StateMachine(0, DS1820, freq=490196, set_base=Pin(2), out_base=Pin(
            2), in_base=Pin(2), out_shiftdir=rp2.PIO.SHIFT_RIGHT, in_shiftdir=rp2.PIO.SHIFT_RIGHT)
        self.sm.active(1)

    def writeBytes(self, bytes, len):
        self.sm.put(250)
        self.sm.put(len-1)
        for i in range(len):
            self.sm.put(bytes[i])

    def readBytes(self, len):
        self.sm.put(0)
        self.sm.put(len-1)
        bytes = []
        for i in range(len):
            bytes.append(self.sm.get() >> 24)
        return bytes

    def getTemp(self):
        self.writeBytes([0xCC, 0x44], 2)
        sleep_ms(1000)
        self.writeBytes([0xCC, 0xBE], 2)
        data = self.readBytes(9)
        t1 = data[0]
        t2 = data[1]
        temp1 = (t2 << 8 | t1)
        if t2 & 0x80:
            temp1 = temp1 | 0xFFFF0000
        return temp1/16


dS18B20 = DS18B20(2)
print(dS18B20.getTemp())

Page 263

from machine import UART, Pin
from utime import sleep_ms

uart = UART(1, baudrate=9600, bits=8, parity=2, rx=Pin(5), tx=Pin(4))
SendData = bytearray("Hello World \n", "utf-8")
uart.write(SendData)
RecData = uart.read()
print(RecData)

Page 264

from machine import UART, Pin
from utime import sleep_ms

uart = UART(1, baudrate=9600, bits=8, parity=2, rx=Pin(5), tx=Pin(4))
SendData = bytearray("A"*32, "utf-8")
uart.write(SendData)
sleep_ms(500)
RecData = uart.read(32)
print(RecData)

Page 266

from machine import UART, Pin, mem32
from utime import sleep_ms


def uart_read(uart):
    rxData = bytes()
    while uart.any() > 0:
        rxData += uart.read(1)
    return rxData


uart = UART(1, baudrate=9600, bits=8, parity=2, rx=Pin(5), tx=Pin(4))
SendData = bytearray("A"*65, "utf-8")
uart.write(SendData)
sleep_ms(500)
RecData = uart_read(uart)
print(RecData)
print(len(RecData))

Page 276

from utime import ticks_us, sleep_ms
from machine import UART, Pin


def uart_read(uart, timeout, interchar):
    rxData = bytes()
    t = ticks_us()
    while True:
        if uart.any() > 0:
            break
        if ticks_us()-t > timeout:
            return None
    while True:
        while uart.any() > 0:
            rxData += uart.read(1)
            t = ticks_us()
        if ticks_us()-t > interchar:
            break
    return rxData.decode("utf-8")


def initWiFi(uartNo):
    uart = UART(uartNo, baudrate=115200, bits=8, stop=1,
                parity=None, rx=Pin(5), tx=Pin(4))
    sleep_ms(100)
    return uart


def ATWiFi(uart):
    SendData = "AT\r\n"
    uart.write(SendData)
    return uart_read(uart, 10000, 100)


uart = initWiFi(1)
response = ATWiFi(uart)
print(response)

Page 288

from utime import ticks_us, sleep_ms
from machine import UART, Pin


class WiFi:
    def __init__(self, uartNo, tx, rx):
        self.uart = UART(uartNo, baudrate=115200, bits=8, stop=1,
                         parity=None, rx=Pin(rx), tx=Pin(tx))
 
 
    def _read(self, timeout, interchar):
        rxData = bytearray(2000)
        t = ticks_us()
        while True:
            if self.uart.any() > 0:
                break
            if ticks_us()-t > timeout:
                return None
        while True:
            while self.uart.any() > 0:
                rxData += self.uart.read(1)
                t = ticks_us()
            if ticks_us()-t > interchar:
                break
        return rxData.decode("utf-8")

    def AT(self):
        self.uart.write(b"AT\r\n")
        return self._read(10000, 100)

    def getVersion(self):
        self.uart.write("AT+GMR\r\n")
        return self._read(10000, 100)

    def reset(self):
        self.uart.write("AT+RST\r\n")
        print(self._read(10000, 10000))
        return self._read(10000, 10000)

    def setUART(self, baud):
        self.uart.write("AT+UART_CUR="+str(baud)+",8,1,0,0\r\n")
        return self._read(10000, 100)

    def mode(self, mode):
        command = "AT+CWMODE_CUR="+str(mode)+"\r\n"
        self.uart.write(command)
        return self._read(10000, 100)

    def scan(self):
        self.uart.write("AT+CWLAP\r\n")
        return self._read(100000, 1000*1000*20)

    def scandisplay(self):
        self.uart.write("AT+CWLAP\r\n")
        block = self._read(10000, 100)
        print(block)
        for i in range(20):
            block = self._read(1000*1000*20, 100)
            if block == None:
                break
            if block.find("OK") >= 0:
                break
            print(block)

    def connect(self, ssid, password):
        command = "AT+CWJAP_CUR=" + '"' + ssid+'"' + ","+'"'+password+'"' + "\r\n"
        self.uart.write(command)
        for i in range(20):
            block = self._read(1000*1000*20, 100)
            if block == None:
                break
            if block.find("OK") >= 0:
                break
        print("connected")

    def getIP(self):
        self.uart.write("AT+CIFSR\r\n")
        return self._read(100000, 100)

    def getWebPage(self, URL, page):
        command = 'AT+CIPSTART="TCP",'+'"'+URL+'"'+",80\r\n"
        self.uart.write(command)
        block = self._read(1000*1000*2, 1000*1000)
        if block.find("OK") < 0:
            return -1
        command = 'GET ' + page + ' HTTP/1.1\r\nHost:'+URL+'\r\n\r\n'
        command2 = "AT+CIPSEND="+str(len(command)) + "\r\n"
        self.uart.write(command2)
        block = self._read(1000*1000*8, 1000*1000*1)
        if block.find(">") < 0:
            return -1
        self.uart.write(command)
        block = self._read(1000*1000*5, 1000*1000*1)
        return block

    def startServer(self):
        self.uart.write("AT+CIPMUX=1\r\n")
        response = self._read(1000*1000*5, 1000)
        print("mux set", response)
        if response.find("OK") < 0:
            return -1
        self.uart.write("AT+CIPSERVER=1,80\r\n")
        response = self._read(1000*1000*5, 1000)
        if response.find("OK") < 0:
            return -1
        print("ready for clients", response)

        while True:
            block = self._read(1000*1000*5, 100)
            if block == None:
                continue
            if block.find("+IPD") < 0:
                continue

            n = block.find("+IPD,")+5
            m = block.find(",", n)
            id = block[n:m]

            data = "HTTP/1.0 200 OK\r\nServer: Pico\r\nContent-type: text/html\r\n\r\n<html><head><title>Temperature</title></head><body><p>{\"humidity\":81%,\"airtemperature\":23.5C}</p></body></html>\r\n"
            command = "AT+CIPSEND="+id+","+str(len(data))+"\r\n"

            self.uart.write(command)
            response = self._read(1000*1000*5, 1000*1000*1)
            if response.find(">") < 0:
                return -1
            self.uart.write(data)
            response = self._read(1000*1000*5, 1000*1000*1)
            if response.find("OK") < 0:
                return -1
            command = "AT+CIPCLOSE="+id+"\r\n"
            self.uart.write(command)
            response = self._read(1000*1000*5, 1000*1000*1)
            if response.find("OK") < 0:
                return -1


wifi = WiFi(1, 4, 5)
print(wifi.AT())
response = wifi.mode(1)
print("mode", response)
wifi.connect("SSID", "password")
print(wifi.startServer())

Page 296

from machine import mem32, Pin
from time import sleep_ms
led = Pin(25, mode=Pin.OUT)
addrSIO = 0xd0000000
while True:
    mem32[addrSIO + 0x014] = 1 << 25
    sleep_ms(500)
    mem32[addrSIO + 0x018] = 1 << 25
    sleep_ms(500)

Page 298

from machine import Pin
import machine


def gpio_get():
    return machine.mem32[0xd0000000+0x010]


def gpio_set(value, mask):
    machine.mem32[0xd0000000+0x01C] =
    (machine.mem32[0xd0000000+0x010]) ^ value & mask


pin = Pin(22, Pin.OUT)
pin = Pin(21, Pin.OUT)
value1 = 1 << 22 | 0 << 21
value2 = 0 << 22 | 1 << 21
mask = 1 << 22 | 1 << 21
while True:
    gpio_set(value1, mask)
    gpio_set(value2, mask)