Git Product home page Git Product logo

pico-micropython-examples's People

Contributors

7west avatar aallan avatar atrueresistance avatar henley-regatta avatar hoihu avatar kilograham avatar lurch avatar pkoscik avatar robert-hh avatar tobybroberts avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pico-micropython-examples's Issues

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

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.

pio_pinchange.py example pin change to high

Hi all

I have this function below from this PIO example https://github.com/raspberrypi/pico-micropython-examples/blob/master/pio/pio_pinchange.py

@rp2.asm_pio()
def wait_pin_low():
    wrap_target()

    wait(0, pin, 0)
    irq(block, rel(0))
    wait(1, pin, 0)

    wrap()

That example (pio_pinchange.py ) using PIO wait for a pin change to LOW and raise an IRQ. I would like to do exactly that, but with pin change do HIGH. I readed this doc https://docs.micropython.org/en/latest/library/rp2.html about the commands of PIO to understand a bit, and changed to that code to this:

@rp2.asm_pio()
def wait_pin_high():
    wrap_target()

    wait(1, pin, 0)
    irq(block, rel(0))
    wait(0, pin, 0)

    wrap()

But not works. I did others modifications, but not success.

Could you please provide this function to works to pin change to high?

I'm using RPICO with MicroPython version 1.8:

import os
>>> os.uname()
(sysname='rp2', nodename='rp2', release='1.18.0', version='v1.18 on 2022-01-17 (GNU 11.2.0 MinSizeRel)', machine='Raspberry Pi Pico with RP2040')
>>>

Thank you very much!

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.

DMA and Interrupt examples

Are there any examples for ADC with DMA or interrupt using the micropython ?
The same goes for Other peripherals too. I can't seem to find any documentation for using DMA or interrupt with either of the peripherals

support for UART rx interrupt

I am using raspberry pi pico for my new project.
I was checking for example for UART receive interrupt. Do we have support for the same?
How can we achieve the UART rx interrupt.
I checked the micropython documentation but I didn't see support for RPi pico.

SPI master slave communication

I am using pico in my project in which I am in need of using master-slave SPI communication.
What modifications are required to change the SPI master code to spi slave?
Is there any existing example for reference.

Request Deep Sleep example

Will be nice to include a Deep Sleep Example:

  • Time Interval
  • Interrupt Button
  • Changing clock speed at run-time.

Thank you.

ADS1115

I was trying to connect the ADS1115 to the Pico using the libraries from circuitpython. I was able to initialize the sensor, but I always get the wrong result back. Anyone who can help?

Why can not use IRQ in a new thread?

from machine import Pin
import utime
import _thread

interruptCounter = 0
def callback(pin):
  global interruptCounter
  interruptCounter = interruptCounter+1
  
def foo():
    p16 = Pin(16, Pin.IN, Pin.PULL_UP)
    p16.irq(callback, Pin.IRQ_FALLING)
    while True:
        utime.sleep(1)
        

_thread.start_new_thread(foo, ())

while True:
    print(interruptCounter)
    utime.sleep(1)

The irq is not work

"__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.

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).

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.

Bluetooth examples

Now that Pico W has support for Bluetooth (yey!), is there any plan to port the C/C++ examples to Micropython?

Wrong kwarg names in Pico Python SDK documentation

The text and the small example box in chapter "3.9. PIO Support", page 19, use the keyword arg names set_pins and sideset_pins, which should be set_init/set_base for the former and sideset_init/sideset_base for the latter.

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

blink.py doesn't work on Pico W

The onboard LED is not tied to GPIO 25 on the new Pico W so the example code in blink.py doesn't work.

Replacing the initialisation with:
led = Pin("LED", Pin.OUT)

..works using an alias and is portable (for recent firmwares) between Pico and Pico W

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

webserver.py NameError: name 'stateis' isn't defined

I copied and pasted the code from the webserver.py into my pico w and got this error.

Traceback (most recent call last):
  File "<stdin>", line 72, in <module>
NameError: name 'stateis' isn't defined

if I comment out this line and line 76 I get a different error

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

Is there any way to fix this?

Raspberry pi pico und MPX2200AP

Hallo,

ich möchte den Drucksensor MPX2200AP mit einem Raspberry Pi Pico verbinden. Dafür benötige ich ein Netzteil, da die Spannung des Drucksensors 10-16 V beträgt. Ich habe ein Netzteil RS 15-12. Können Sie mir bitte bei der Verkabelung und beim Schreiben des Codes für MicroPython helfen?

Vielen Dank!

PWM channels

How do you synchronize 5 different PWM channels (3 slices) so they start at the same time?

neopixel_ring.py Green led timing issue?

When using a RGBW Neopixel ring and the green neopixel led is being used the pixels_fill() and pixels_show() methods take longer to execute. Has a noticeable effect on fast color fade in and outs. Tested on RGBW 12 Neopixel ring. Any ideas as to what is causing the issue and any possible fixes?

Timing tests of pixels_fill() and pixels_show() methods

Fill took 0.842 milli seconds for color: RED
Show took 12.763 milli seconds for color: RED

Fill took 1.542 milli seconds for color: YELLOW
Show took 14.026 milli seconds for color: YELLOW

Fill took 1.539 milli seconds for color: GREEN
Show took 13.988 milli seconds for color: GREEN

Fill took 1.541 milli seconds for color: CYAN
Show took 14.054 milli seconds for color: CYAN

Fill took 0.815 milli seconds for color: BLUE
Show took 12.76 milli seconds for color: BLUE

Fill took 0.823 milli seconds for color: PURPLE
Show took 12.746 milli seconds for color: PURPLE

Fill took 0.822 milli seconds for color: WHITE
Show took 12.761 milli seconds for color: WHITE

Fill took 1.557 milli seconds for color: WHITE(RGB)
Show took 14.082 milli seconds for color: WHITE(RGB)

Fill took 0.829 milli seconds for color: ORANGE
Show took 12.771 milli seconds for color: ORANGE

Adapted code for RGBW Neopixel -
`# Example using PIO to drive a set of WS2812 LEDs.

import array, time
from machine import Pin
import rp2

NUM_LEDS = 12
PIN_NUM = 22
brightness = 0.2

@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=32)
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() .side(0) [T2 - 1]
wrap()

sm = rp2.StateMachine(1, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))

sm.active(1)

ar = array.array("I", [0 for _ in range(NUM_LEDS)])

def pixels_show():
dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
for i,c in enumerate(ar):
r = int(((c >> 8) & 0xFF) * brightness)
g = int(((c >> 16) & 0xFF) * brightness)
b = int((c & 0xFF) * brightness)
w = int(((c >> 24) & 0xFF) * brightness)
dimmer_ar[i] = (w<<24) + (g<<16) + (r<<8) + b
sm.put(dimmer_ar, 0)
time.sleep_ms(10)

def pixels_set(i, color):
green = color[1]<<24
red = color[0]<<16
blue = color[2]<<8
white = color[3]
ar[i] = red + green + blue + white

def pixels_fill(color):
for i in range(len(ar)):
pixels_set(i, color)

def color_chase(color, wait):
for i in range(NUM_LEDS):
pixels_set(i, color)
time.sleep(wait)
pixels_show()
time.sleep(0.2)

def wheel(pos):
if pos < 0 or pos > 255:
return (0, 0, 0, 0)
if pos < 85:
return (255 - pos * 3, pos * 3, 0, 0)
if pos < 170:
pos -= 85
return (0, 255 - pos * 3, pos * 3, 0)
pos -= 170
return (pos * 3, 0, 255 - pos * 3, 0)

def rainbow_cycle(wait):
for j in range(255):
for i in range(NUM_LEDS):
rc_index = (i * 256 // NUM_LEDS) + j
pixels_set(i, wheel(rc_index & 255))
pixels_show()
time.sleep(wait)

BLACK = (0, 0, 0,0)
RED = (255, 0, 0,0)
YELLOW = (255, 125, 0,0)
GREEN = (0, 255, 0,0)
CYAN = (0, 255, 255,0)
BLUE = (0, 0, 255,0)
PURPLE = (180, 0, 255,0)
WHITE = (0,0,0,255)
WHITE_RGB = (255,255,255,0)
ORANGE = (255,40,0,0)
COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, WHITE_RGB, ORANGE)
COLORNAMES = ('BLACK', 'RED', 'YELLOW', 'GREEN', 'CYAN', 'BLUE', 'PURPLE', 'WHITE', 'WHITE(RGB)', 'ORANGE')

print("fills")
for color in COLORS:
pixels_fill(color)
pixels_show()
time.sleep(0.2)

print("chases")
for color in COLORS:
color_chase(color, 0.01)

print("rainbow")
rainbow_cycle(0)

print("Timing tests of pixels_fill() and pixels_show() methods")
index = 0
for color in COLORS:
if index > 0: # Skip color BLACK
tic = time.ticks_us() # Start timer
pixels_fill(color)
toc = time.ticks_us() # Stop timer
print("")
print("Fill took {} milli seconds for color: {}".format((toc - tic) / 1000, COLORNAMES[index]))
tic = time.ticks_us() # Start timer
pixels_show()
toc = time.ticks_us() # Stop timer
print("Show took {} milli seconds for color: {}".format((toc - tic) / 1000, COLORNAMES[index]))
time.sleep(0.5)
index += 1`

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

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.

multicore example does not work on Pico

Running this example code from Thonny version 3.3.5 (hosted on Pi 4B) on Pico MicroPython v1.14, generates several errors as shown below. This is also discussed here: https://www.raspberrypi.org/forums/viewtopic.php?f=146&t=308150

https://github.com/raspberrypi/pico-micropython-examples/blob/master/multicore/multicore.py

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/thonny/workbench.py", line 1708, in event_generate
handler(event)
File "/usr/lib/python3/dist-packages/thonny/shell.py", line 433, in _handle_program_output
self._update_visible_io(None)
File "/usr/lib/python3/dist-packages/thonny/shell.py", line 512, in _update_visible_io
self._apply_io_event(data, stream_name)
File "/usr/lib/python3/dist-packages/thonny/shell.py", line 555, in _apply_io_event
self.active_extra_tags.pop()
IndexError: pop from empty list

MicroPython v1.14 on 2021-03-28; Raspberry Pi Pico with RP2040
Type "help()" for more information.

%Run -c $EDITOR_CONTENT
THONNY FAILED TO EXECUTE COMMAND Run

SCRIPT:

class __thonny_helper:
try:
import uos as os
except ImportError:
import os
import sys

# for object inspector
inspector_values = dict()
last_repl_values = []
@classmethod
def print_repl_value(cls, obj):
    if obj is not None:
        cls.last_repl_values.append(obj)
        cls.last_repl_values = cls.last_repl_values[-5:]
        print('[object_link_for_thonny=%d]' % id(obj), repr(obj), '', sep='')

@staticmethod
def print_mgmt_value(obj):
    print('<thonny>', repr(obj), '</thonny>', sep='', end='')

@staticmethod
def repr(obj):
    try:
        s = repr(obj)
        if len(s) > 50:
            s = s[:50] + "..."
        return s
    except Exception as e:
        return "<could not serialize: " + str(e) + ">"

@classmethod
def listdir(cls, x):
    if hasattr(cls.os, "listdir"):
        return cls.os.listdir(x)
    else:
        return [rec[0] for rec in cls.os.ilistdir(x) if rec[0] not in ('.', '..')]


@classmethod
def getcwd(cls):
    if hasattr(cls, "getcwd"):
        return cls.os.getcwd()
    else:
        # micro:bit
        return ""

@classmethod
def chdir(cls, x):
    return cls.os.chdir(x)

@classmethod
def rmdir(cls, x):
    return cls.os.rmdir(x)

STDOUT:

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

ManagementError

done
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, in
NameError: name '__thonny_helper' isn't defined

cant take input

on the example blink if i try taking input it freaks out. i have to completly restart it each time.

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)

Possible Issue with pio/pio_spi.py

Could it be that there is an issue somewhere in the code for the pio_spi. For me i only get MOSI getting pulled low trying to send something. It could also well be, that i am using it wrong, since there is no example given, and im completely new to PIO. Anyway here is my code:

import rp2
from machine import Pin
import time

@rp2.asm_pio(out_shiftdir=0, autopull=True, pull_thresh=8, autopush=True, push_thresh=8, sideset_init=(rp2.PIO.OUT_LOW, rp2.PIO.OUT_HIGH), out_init=rp2.PIO.OUT_LOW)
def spi_cpha0():
    # Note X must be preinitialised by setup code before first byte, we reload after sending each byte
    # Would normally do this via exec() but in this case it's in the instruction memory and is only run once
    set(x, 6)
    # Actual program body follows
    wrap_target()
    pull(ifempty)            .side(0x2)   [1]
    label("bitloop")
    out(pins, 1)             .side(0x0)   [1]
    in_(pins, 1)             .side(0x1)
    jmp(x_dec, "bitloop")    .side(0x1)

    out(pins, 1)             .side(0x0)
    set(x, 6)                .side(0x0) # Note this could be replaced with mov x, y for programmable frame size
    in_(pins, 1)             .side(0x1)
    jmp(not_osre, "bitloop") .side(0x1) # Fallthru if TXF empties

    nop()                    .side(0x0)   [1] # CSn back porch
    wrap()


class PIOSPI:

    def __init__(self, sm_id, pin_mosi, pin_miso, pin_sck, cpha=False, cpol=False, freq=1000000):
        assert(not(cpol or cpha))
        self._sm = rp2.StateMachine(sm_id, spi_cpha0, freq=4*freq, sideset_base=Pin(pin_sck), out_base=Pin(pin_mosi), in_base=Pin(pin_sck))
        self._sm.active(1)
        self._sm.exec("set(x,6)")

    # Note this code will die spectacularly cause we're not draining the RX FIFO
    def write_blocking(self, wdata):
        for b in wdata:
            self._sm.put(b << 24)

    def read_blocking(self, n):
        data = []
        for i in range(n):
            data.append(self._sm.get() & 0xff)
        return data

    def write_read_blocking(self, wdata):
        rdata = []
        for b in wdata:
            self._sm.put(b << 24)
            rdata.append(self._sm.get() & 0xff)
        return rdata



spi = PIOSPI(0,19, 16, 18)
cs_pin = machine.Pin(2, machine.Pin.OUT)

def set_voltage(voltage):
    global spi
    global cs_pin
    
    # Calculate the 10-bit digital value for the given voltage
    digital_value = int(voltage / 2.048 * 1023)
    
    # Calculate the configuration bits for output voltage range and power-down mode
    config_bits = 0b00110000  # 0b001 for full-scale output voltage range, 0b0 for normal mode
    
    # Send the configuration bits and digital value to the MCP4812 via SPI
    cs_pin.value(0)  # Activate chip select
    spi.write_blocking(bytes([(config_bits | ((digital_value >> 6) & 0xFF))]))
    spi.write_blocking(bytes([((digital_value & 0x3F) << 2)]))
    cs_pin.value(1)  # Deactivate chip select
    spi.read_blocking(2)

while True:
    set_voltage(1.23)
    print("1.23")
    time.sleep(1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.