Examples to accompany the

Overview

MicroPython Examples

Examples to accompany the "Raspberry Pi Pico Python SDK" book published by Raspberry Pi Trading, which forms part of the technical documentation in support of Raspberry Pi Pico and the MicroPython port to RP2040.

Contributions

While we welcome pull requests to contribute further example code, please do not link to personal sites or to your social media. Contributions which are fully documented with an AsciiDoc description and a Fritzing wiring diagram, e.g. see the NeoPixel Ring example, stand more chance of inclusion.

Our example code is under the BSD-3-Clause License: any contributions must be under the same license.

Comments
  • Thread Example held up by error messages and dies

    Thread Example held up by error messages and dies

    When running the example it hangs with a error box. The LED flashes correctly but the 'Done' does not get printed until the error box is cleared.

    Thonny gave these error messages:

    ManagementError

    THONNY FAILED TO EXECUTE COMMAND get_globals

    SCRIPT: __thonny_helper.print_mgmt_value({name : (thonny_helper.repr(value), id(value)) for (name, value) in globals().items() if not name.startswith('')})

    STDOUT:

    STDERR: Traceback (most recent call last): File "", line 1 SyntaxError: invalid syntax

    done

    I've no idea what is going on

    bug thonny 
    opened by tonygo 12
  • Need FIFO joining example

    Need FIFO joining example

    opened by IndustrialMuffin 10
  • UART on Pico with MicroPython has no documentation, please at least include example

    UART on Pico with MicroPython has no documentation, please at least include example

    I have scoured for some reference or documentation for the use of UART with MicroPython on the Pico with no luck. The "Raspberry Pi Pico Python SDK" loosely references the MicroPython documentation when discussing UART (pg 14). However, MicroPython's documentation on UART does not seem to apply to the Pico (https://docs.micropython.org/en/latest/library/machine.UART.html), because I don't even think the init() function got ported to the Pico.

    I am really lost. I even looked through the "Get started with MicroPython on Raspberry Pi Pico" book and found no examples or references.

    Maybe I am being really dumb and missing the documentation on this port. Thank you in advance.

    documentation 
    opened by 7west 9
  • There is a problum with GPIO19 for micropython

    There is a problum with GPIO19 for micropython

    It can't control high or low with machine.Pin with GIOP19, no higt or low output, but 18, 20 is OK! please cheak!

    Test code as follow:

    from machine import Pin import time

    LED1 = Pin(18, Pin.OUT)

    LED1.high() time.sleep_ms(1000) LED1.low() time.sleep_ms(1000)

    upstream paused 
    opened by CaptainJackey 8
  • machine.ADC(4) - initialization becoming corrupted

    machine.ADC(4) - initialization becoming corrupted

    sensor_temp = machine.ADC(4) - initialization becoming corrupted by subsequent port allocations e.g. Vsys = machine.ADC(0)

    Will result in temp reading of 84 C instead of 24 C from ADC(4) When done in the reversed order placing ADC(4) last, it works fine.

    Vsys = machine.ADC(0) Vbus = machine.ADC(1) Vout = machine.ADC(2) sensor_temp = machine.ADC(4) # works

    bug 
    opened by arajnak 6
  • Wrong pins on sh1106 spi example

    Wrong pins on sh1106 spi example

    Been trying for 2h+, and finally discovered the SPI wiring pins on the comments are wrong.

    Instructions goes as (wrong): ` Sample code sections ------------ SPI ------------------ Pin Map SPI

    • 3v - xxxxxx - Vcc
    • G - xxxxxx - Gnd
    • D7 - GPIO 13 - Din / MOSI fixed *1
    • D5 - GPIO 14 - Clk / Sck fixed *2
    • D8 - GPIO 4 - CS (optional, if the only connected device)
    • D2 - GPIO 5 - D/C
    • D1 - GPIO 2 - Res `

    But only works if you use (right): ` Pin Map SPI

    • GPIO 11 - Din / MOSI fixed *1
    • GPIO 10 - Clk / Sck fixed *2 `

    Also may include a suggestion to use a logic level adapter, because there are 5v sh1106 displays.

    Link to photo of working set, also using lg. lvl. adap. 5v

    The mistake is located at: https://github.com/raspberrypi/pico-micropython-examples/blob/master/i2c/1106oled/sh1106.py

    Thanks 4 the great work.

    documentation 
    opened by Garfius 5
  • "__thonny_helper isn't defined" error

    I made a silly coding mistake but the error message threw me off so I hope documenting it here will help others or allow a fix to get a more informative error message. Here is the error message:

    >>> %Run -c $EDITOR_CONTENT
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 8, in Bomb
    NameError: name 'self' isn't defined
    >>> THONNY FAILED TO EXECUTE COMMAND get_globals
    
    
    SCRIPT:
    __thonny_helper.print_mgmt_value({name : (__thonny_helper.repr(value), id(value)) for (name, value) in globals().items() if not name.startswith('__')})
    
    STDOUT:
    
    
    STDERR:
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <dictcomp>
    NameError: name '__thonny_helper' isn't defined
    

    Here is some simplified code to demonstrate the issue:

    class Bomb:
        def __init__(self):
            print("running __init__()")
        
        def something(self):
            print("doing something")
            
        self.ooops = True
        
        def otherthing(self):
            print("doing otherthing")
    

    self.ooops tries to assign to a property outside a method block. Once, moved into init the error message goes away.

    opened by biodives 4
  • pio_blink.py and pio_irq.py examples uses 1000Hz frequency which is too low for Pi Pico

    pio_blink.py and pio_irq.py examples uses 1000Hz frequency which is too low for Pi Pico

    The examples https://github.com/raspberrypi/pico-micropython-examples/blob/master/pio/pio_irq.py and https://github.com/raspberrypi/pico-micropython-examples/blob/master/pio/pio_blink.py set a frequency of 1000Hz using freq=1000.

    If my understanding is correct then the maxium divisor is 65535 + 255/256 which at typical 125MHz gives 1907.349Hz as the lowest achievable frequency. That makes these examples misleading as that frequency cannot be achieved and is almost wrong by a factor of 2.

    Is 2000Hz as used by https://github.com/raspberrypi/pico-micropython-examples/blob/master/pio/pio_1hz.py a better choice for low frequency for examples? That's precisely attainable at 125MHz and close at 133Mhz (1.47% over).

    opened by kevinjwalters 4
  • In wiring for pio/neopixel_ring example, Ring V+ may better be connected to Pico VBUS (pin 40)

    In wiring for pio/neopixel_ring example, Ring V+ may better be connected to Pico VBUS (pin 40)

    In pio/neopixel_ring example, 3V3 (pin 36) may be a little low for NeoPixel's V+ as 4-7V is recommended in https://www.adafruit.com/product/1463#description. Unless there is a reason of using 3V3, VBUS (pin 40) may be better for that.

    documentation 
    opened by vjou 4
  • Change subtraction to addition to properly calculate temperature

    Change subtraction to addition to properly calculate temperature

    After following the example codes from: Python SDK Doc and running them for myself I realized that the calculation of the current temperature is wrong.

    wontfix 
    opened by ryakosh 3
  • Pico W i2c issues

    Pico W i2c issues

    I've had issues with a Pico W running latest MicroPython uf2 MicroPython v1.19.1 on 2022-09-20; Raspberry Pi Pico W with RP2040

    Running 'i2c.py'

    Traceback (most recent call last):
      File "<stdin>", line 5, in <module>
    OSError: [Errno 5] EIO
    

    same for a couple of different i2c devices.

    opened by dbuggz 2
  • PIO 1Hz example off-by-one cycle

    PIO 1Hz example off-by-one cycle

    The pio_1hz.py example has a off-by-one cycle issue between pin high and pin low. The delays should be exact, even if it's insignificant for a LED blink in this IRQ example.

    This Logic 2 capture shows the timing difference between pin high and pin low. Logic2_pio_1hz_timing_measurements

    opened by stigbjorlykke 0
  • blink.py error

    blink.py error

    Traceback (most recent call last): File "", line 3, in TypeError: can't convert str to int

    I am using thonny to code and this error is showing up in the shell when I click run current script

    opened by Rudra076 1
  • Add better examples with how to interact between PIO routines and the Micropython program running

    Add better examples with how to interact between PIO routines and the Micropython program running

    I have been searching quite a lot on how to communicate back and forth between PIO and Micropython on the Pi Pico with synchronized activation between state machines and PIO blocks signaling back with interrupts etc. I came up with nothing.

    I started this project: https://github.com/Vendelator/RP2040_PIO_Steppermotors Which uses the technique i was searching for. The best source i could find was: https://dernulleffekt.de/doku.php?id=raspberrypipico:pico_pio

    My suggestion is to add an example code doing this, as i have seen a lot of people are looking for this.

    I provide this example program to be added as an example in: https://github.com/raspberrypi/pico-micropython-examples

    This example is working as intended, but all comments have been put there quite hasty.

    # Code was written for the Pi Pico, for the Pi Pico W, use an output with an external LED to get visual feedback.
    
    # This example takes a simpler approach to explain PIO and how it integrates with Micropython
    # on the Raspberry Pi Pico.
    
    # This is example code on how to have two pairs or state machines, who are working together, run simultaneously.
    # Because they can't be called at the same time, but can run independently at the same time,
    # we activate the machines one by one, and then use a Pin which they both are waiting for at the same time.
    # The onboard LED will turn ON while both programs are running. When each program is completed they will write to REPL.
    # Once both programs are done, user will be asked to press enter again to run the programs again.
    
    # Program can run without connecting anything to the Pi Pico, but one suggestion is adding LED's to the outputs
    # and use Pins that works for you.
    
    # I used this code as a base for my stepper motor project:
    # https://github.com/Vendelator/RP2040_PIO_Steppermotors - MIT license
    # The best source for explaining PIO: https://dernulleffekt.de/doku.php?id=raspberrypipico:pico_pio
    
    # To change how many times the pins toggle, change the values in sm_0.put() and sm_4.put().
    # To change how fast the program toggles, change frequency and add/remove delay [x]
    # which can be done to any isntruction in the PIO routines.
    # In the example i use nop() [31], which delays for 1 + 31 cycles.
    
    # At current setting with 20_000 Hz frequency, (1 + 1 + (32 * 65) + 1) instruction in delay(), 
    # pins will toggle at approximatly 10 hZ.(10 times a second)
    # This means PIO block 0 will take 10 seconds to finish and PIO block 1 will take 20 seconds.
    
    
    import machine     # To be able to control GPIO Pins
    import rp2         # To be able to use state machines
    
    trigger_pin = machine.Pin(25, machine.Pin.OUT) # This pin will trigger our state machines using wait(1, gpio, 25).
    pio_block_0 = False                            # True/False object used to see if the program is allowed to proceed.
    pio_block_1 = False                            # - " -
    
    @rp2.asm_pio(set_init=rp2.PIO.OUT_LOW)  # Tells our program that this is a PIO routine and to set the pin low on activation.
    def pin_activator():
        pull(block)                    # Wait for FIFO to fill (put), then pull data to OSR.
        mov(x, osr)                    # Copy OSR data from to X.
        wait(1, gpio, 25)              # Does nothing until GPIO Pin 25 is set to high, this is how we synchronize activation.
        
        label("Jump_Point")            # this is a header we jump back to for counting steps.
        set(pins, 1)                   # Sets the in_base Pin high.
        jmp(not_x, "end")              # if X is 0(zero), jump to end.
        irq(5)                         # Sets IRQ 5 high, signaling.
        irq(block, 4)                  # Waiting for IRQ flag 4 to clear before proceeding.
        set(pins, 0)                   # Sets the in_base Pin low.
        jmp(x_dec, "Jump_Point")       # if x is NOT 0(zero), remove one (-1) from X and jump back to "Jump_Point", Else, proceed.
        
        label("end")                   # This is a label we can jump to if X is 0.
        irq(block, rel(0))             # Signals IRQ handler of the actual state machine and waits for handler to clear the flag.
                                        
                                       # Once the handler clears the flag, the program restarts and is blocked until new data is available.
    
    @rp2.asm_pio()                     # Does not manipulate any hardware, it's just code. empty  ()
    def delay():
        wait(1, irq, 5)                # Waiting for IRQ flag 5 from pin_activator and then clears it.
        set(y, 31)                     # Sets Y to the value 31.
        label("Delay")                 # This is a header we jump back to for adding a delay.
        nop() [31]                     # nop() does nothing for [n] instructions.
        nop() [31]                     # - " -
        jmp(y_dec, "Delay")            # If Y not 0(zero), remove one (-1) from Y and make jump to delay, Else, proceed.
        irq(clear, 4)                  # Clears IRQ flag 4, allowing step_counter() to continue
    
                                       # At this point, the program restarts, and begins with waiting for IRQ
    
    def pio_0_handler(sm):             # This is our Interrupt handler for PIO block 0.
        global pio_block_0             # To be able to change our global variable.
        pio_block_0 = True             # Change variable to True to be able to exit loop.
        print(sm, "sending interrupt.", "\nPio-Block 0 done!")
                                       # sm is the statemachine calling the handler.
                                       # Here we could trigger other functions or execute code
                                       # like turning a Pin on or off.
    
    def pio_1_handler(sm):             # This is our Interrupt handler for PIO block 1
        global pio_block_1             # To be able to change our global variable
        pio_block_1 = True             # Change variable to True to be able to exit loop.
        print(sm, "sending interrupt.", "\nPio-Block 1 done!")
                                       # sm is the statemachine calling the handler.
                                       # Here we could trigger other functions or execute code
                                       # like turning a Pin on or off.
    
    
    #                        --- PIO Block 0 ---
    sm_0 = rp2.StateMachine(0, pin_activator, freq=20000, set_base=machine.Pin(0))
                                      # Calls rp2 and Instantiate a statemachine
                                      # (0, ... is the statemachine number. (0-7)
                                      # , pin_activator ... is the PIO routine
                                      # , freq=2000 ... sets the frequency to 2000 Hz
                                      # , in_base=machine.Pin(0) ... sets GPIO 0 as our base pin.
    
    sm_0.irq(pio_0_handler)           # Tells the program that any interrupt from sm_0 should activate 
                                      # the function pio_0_handler(sm):
    
    sm_1 = rp2.StateMachine(1, delay, freq=20000)
                                      # Creates object called sm_1 and binds it to state machine 1 in PIO block 0)
    
    #                        --- PIO Block 1 ---
    sm_4 = rp2.StateMachine(4, pin_activator, freq=20000, set_base=machine.Pin(1))
                                      # Calls rp2 and Instantiate a statemachine
                                      # (4, ... is the statemachine number. (0-7)
                                      # , pin_activator ... is the PIO routine
                                      # , freq=2000 ... sets the frequency to 2000 Hz
                                      # , set_base=machine.Pin(0) ... sets GPIO 0 as our base pin.
    
    sm_4.irq(pio_1_handler)           # Tells the program that any interrupt from sm_4 should activate 
                                      # the function pio_1_handler(sm):
    
    sm_5 = rp2.StateMachine(5, delay, freq=20000)
                                      # Creates object called sm_1 and binds it to state machine 5 in PIO block 1)
    
    #                        --- Starting the State machines ---
    sm_0.active(1), sm_1.active(1), sm_4.active(1), sm_5.active(1)
                                      # All 4 state machines are now running
                                      # State machine 0 in PIO 0 and state machine 4 in PIO 1 are both waiting to be fed data.
                                      
    sm_0.put(100)                     # We can "put" data into state machine 0 using an integer.
                                      # This number will tell pin_activator() how many times to turn on/off.
    any_number = 200 
    sm_4.put(any_number)              # We can also use a variable.
    
                                      # Both state machines are now fed, have copied this value into X
                                      # and are waiting for GPIO 25 to turn high.
    
    
    #                        --- Running the program ---
    while True:
        input("Press enter to execute both programs synchronous...")
        trigger_pin.value(1)
        while True:
            if pio_block_0 and pio_block_1: # Check if they are both True
                trigger_pin.value(0)
                pio_block_0 = False
                pio_block_1 = False
                break
    #                        --- Explaining the program ---
                                     # while is an endless loop unless exited.
                                     # input will pause the while loop until user inputs something (Presses enter in REPL).
                                     # trigger_pin.value(1) sets GPIO 25 high and the onboard LED turns on, 
                                     # this will activate our state machines and they will start toggeling the pins.
                                     # their pins and wait for out pre determined period of time before swithcing them of
                                     # again.
                                     # The second while loop will lock us into a loop where we check if
                                     # both handlers have changed pio_block_0 and pio_block_1 to True.
    
    opened by Vendelator 3
  • Add Example for reading a PWM signal with PIO

    Add Example for reading a PWM signal with PIO

    Works well up to a 200 kHz input signal - deviation below 1% of frequency and duty cycle.

    The example has a build-in testmode. Lower frequencies are dead on, higher ones have a slight error.

    100 Hz / 0.5 duty OK
    	100.00 Hz / 0.50 duty cycle measured
    	Diff: 0.00 Hz
    	Diff: 0.00% of freq
    	Diff: 0.00% duty cycle
    
    1000 Hz / 0.5 duty OK
    	1000.02 Hz / 0.50 duty cycle measured
    	Diff: 0.02 Hz
    	Diff: 0.00% of freq
    	Diff: 0.00% duty cycle
    
    10000 Hz / 0.5 duty OK
    	10002.00 Hz / 0.50 duty cycle measured
    	Diff: 2.00 Hz
    	Diff: 0.02% of freq
    	Diff: 0.01% duty cycle
    
    200000 Hz / 0.5 duty OK
    	200803.21 Hz / 0.50 duty cycle measured
    	Diff: 803.20 Hz
    	Diff: 0.40% of freq
    	Diff: 0.20% duty cycle
    
    500000 Hz / 0.5 duty OUTSIDE LIMITS ---------
    	505050.47 Hz / 0.49 duty cycle measured
    	Diff: 5050.50 Hz
    	Diff: 1.01% of freq
    	Diff: 0.50% duty cycle
    
    enhancement 
    opened by zeroflow 0
Owner
Raspberry Pi
Raspberry Pi
Code release to accompany paper "Geometry-Aware Gradient Algorithms for Neural Architecture Search."

Geometry-Aware Gradient Algorithms for Neural Architecture Search This repository contains the code required to run the experiments for the DARTS sear

null 18 May 27, 2022
Code and data to accompany the camera-ready version of "Cross-Attention is All You Need: Adapting Pretrained Transformers for Machine Translation" in EMNLP 2021

Code and data to accompany the camera-ready version of "Cross-Attention is All You Need: Adapting Pretrained Transformers for Machine Translation" in EMNLP 2021

Mozhdeh Gheini 16 Jul 16, 2022
ColossalAI-Examples - Examples of training models with hybrid parallelism using ColossalAI

ColossalAI-Examples This repository contains examples of training models with Co

HPC-AI Tech 185 Jan 9, 2023
Minimal examples of data structures and algorithms in Python

Pythonic Data Structures and Algorithms Minimal and clean example implementations of data structures and algorithms in Python 3. Contributing Thanks f

Keon 22k Jan 9, 2023
This repository contains code examples and documentation for learning how applications can be developed with Kubernetes

BigBitBus KAT Components Click on the diagram to enlarge, or follow this link for detailed documentation Introduction Welcome to the BigBitBus Kuberne

null 51 Oct 16, 2022
Unadversarial Examples: Designing Objects for Robust Vision

Unadversarial Examples: Designing Objects for Robust Vision This repository contains the code necessary to replicate the major results of our paper: U

Microsoft 93 Nov 28, 2022
Streamlit dashboard examples - Twitter cashtags, StockTwits, WSB, Charts, SQL Pattern Scanner

streamlit-dashboards Streamlit dashboard examples - Twitter cashtags, StockTwits, WSB, Charts, SQL Pattern Scanner Tutorial Video https://ww

null 122 Dec 21, 2022
Code examples for my Write Better Python Code series on YouTube.

Write Better Python Code This repository contains the code examples used in my Write Better Python Code series published on YouTube: https:/

null 858 Dec 29, 2022
Source code, datasets and trained models for the paper Learning Advanced Mathematical Computations from Examples (ICLR 2021), by François Charton, Amaury Hayat (ENPC-Rutgers) and Guillaume Lample

Maths from examples - Learning advanced mathematical computations from examples This is the source code and data sets relevant to the paper Learning a

Facebook Research 171 Nov 23, 2022
Several simple examples for popular neural network toolkits calling custom CUDA operators.

Neural Network CUDA Example Several simple examples for neural network toolkits (PyTorch, TensorFlow, etc.) calling custom CUDA operators. We provide

WeiYang 798 Jan 1, 2023
Official PyTorch implementation for Generic Attention-model Explainability for Interpreting Bi-Modal and Encoder-Decoder Transformers, a novel method to visualize any Transformer-based network. Including examples for DETR, VQA.

PyTorch Implementation of Generic Attention-model Explainability for Interpreting Bi-Modal and Encoder-Decoder Transformers 1 Using Colab Please notic

Hila Chefer 489 Jan 7, 2023
Examples and code for the Practical Machine Learning workshop series

Practical Machine Learning Workshop Series Practical Machine Learning for Quantitative Finance Post conference workshop at the WBS Spring Conference D

CompatibL 21 Jun 25, 2022
A repo with study material, exercises, examples, etc for Devnet SPAUTO

MPLS in the SDN Era --> DevNet SPAUTO Get right to the study material: Checkout the Wiki! A lab topology based on MPLS in the SDN era book used for 30

Hugo Tinoco 67 Nov 16, 2022
🐸STT integration examples

?? STT 0.9.x Examples These are various examples on how to use or integrate ?? STT using our packages. It is a good way to just try out ?? STT before

coqui 92 Dec 19, 2022
transfer attack; adversarial examples; black-box attack; unrestricted Adversarial Attacks on ImageNet; CVPR2021 天池黑盒竞赛

transfer_adv CVPR-2021 AIC-VI: unrestricted Adversarial Attacks on ImageNet CVPR2021 安全AI挑战者计划第六期赛道2:ImageNet无限制对抗攻击 介绍 : 深度神经网络已经在各种视觉识别问题上取得了最先进的性能。

null 25 Dec 8, 2022
Guide & Examples to create deeplearning gstreamer plugins and use them in your pipeline

upai-gst-dl-plugins Guide & Examples to create deeplearning gstreamer plugins and use them in your pipeline Introduction Thanks to the work done by @j

UPAI.IO 11 Dec 11, 2022
[ICLR2021] Unlearnable Examples: Making Personal Data Unexploitable

Unlearnable Examples Code for ICLR2021 Spotlight Paper "Unlearnable Examples: Making Personal Data Unexploitable " by Hanxun Huang, Xingjun Ma, Sarah

Hanxun Huang 98 Dec 7, 2022
This framework implements the data poisoning method found in the paper Adversarial Examples Make Strong Poisons

Adversarial poison generation and evaluation. This framework implements the data poisoning method found in the paper Adversarial Examples Make Strong

null 31 Nov 1, 2022
TensorRT examples (Jetson, Python/C++)(object detection)

TensorRT examples (Jetson, Python/C++)(object detection)

Nobuo Tsukamoto 53 Dec 22, 2022