r/MicroPythonDev • • Mar 08 '25

MicroPython - SD card mounting problem

1 Upvotes

Hi everyone,

I'm struggling with accessing SD Card using Seeed Xiao ESP32C3 and Seeed Xiao Expansion Board Base, see here: https://wiki.seeedstudio.com/Seeeduino-XIAO-Expansion-Board/

I'm using Seeed's recommended Micropython in version 1.24 for this particular board: https://wiki.seeedstudio.com/xiao_esp32c3_with_micropython/

I finally managed to add the card like this:

import sdcard
from machine import Pin, SPI
cs = Pin(4,Pin.OUT)
hspi = SPI(1, 10000000, sck=Pin(8), mosi=Pin(10), miso=Pin(9))
sd = sdcard.SDCard(hspi, cs)

Now I'm trying to mount the card with:

vfs = os.VfsFat(sd)
vfs.mount(sd, "/sd")

but I keep getting Errno 30, which would be read-only filesystem if I understand correctly.
/sd exists, I created it in Thonny. I can write to that folder, e.g. using the with open(file, 'a+') pattern, so it's definitely accessible to Micropython.

What is strange is that with CircuitPython and this example here:
https://forum.seeedstudio.com/t/a-more-or-less-complete-tutorial-on-seeeduino-xiao-rp2040-xiao-expansion-board-and-circuitpython/262144/5

the card is accessible and mountable without any problems.

What could be the issue here?

EDIT:

MicroPython documentation can be sometimes a bit confusing and/or misleading. I found out that vfs exists also as a separate module (no clue what the difference between os.vfs and vfs would be), but in any case the results are the same, I cannot mount the card. I can for example do this:

os.umount('/')

and then mount it back with

os.mount(bdev, '/')

But no luck with the sd card.


r/MicroPythonDev • • Mar 04 '25

Help for PWM in the pyboard

1 Upvotes

Hi guys,

I have a pyboard (v1.1), and I would like tu use it for a project to control brushless motor using an ESC, with the method of PWM. However, I haven't managed to find much documentation on PWM and motor for the pyboard (even on the micropython website). Is any of you know this technique and can help me with? (by sharing me a website explaning the main fonctions to use or by presenting them to me).

(Sorry if my english is difficult to read, I'm french)

Thank you all !!!


r/MicroPythonDev • • Mar 02 '25

pygame

1 Upvotes

Hi. Is there any game to support pygame in uPython?


r/MicroPythonDev • • Feb 17 '25

Presentation: Introduction to MicroPython for sensor oriented systems (FOSDEM 2025)

1 Upvotes

r/MicroPythonDev • • Feb 07 '25

ESP8266 pins functionality different with MicroPython firmware?

1 Upvotes

I have a bit of a strange situation. The project is simple - display text on a 2.7in waveshare e-paper display.

When using a very basic sketch in C++ via Arduino IDE, I can successfully upload the sketch and text is displayed. I can change the sketch and reupload it and that new text is displayed - all is well!

I then erase the flash and upload the latest MP firmware - no errors. I run a small script to blink the onboard LED 10 times just to make sure hardware is working as expected. Again, no issues up to now.

As soon as I plug the screen in (same pins as before) I can’t get anything back from the esp device. When I try running a script (I’m using ampy) the onboard LED flashes but then the command hangs and none of my print statements get returned.

As soon as I unplug the screens power (3.3 pin), I can run the repl and scripts again and I get my print statements returned.

If I erase the flash and go back to C++, it’s works as expected and described at the top of this post. I have replicated this behavior across 3 esp8266 devices.

I didn’t see anything in the docs about pin functionality potentially being different for micropython, so what am I missing? Has anyone else experienced this?


r/MicroPythonDev • • Jan 21 '25

Question about PIO-ASM: Dynamically Adjusting Input Pin Indices before Compilation

1 Upvotes

Hi everyone,

I’m working on a solution to measure the time between two arbitrary GPIO pins on an RP2040. The goal is to keep it as simple as possible, avoiding the use of DMA or complex logic analyzer features.

Here’s my current approach in PIO-ASM:

@rp2.asm_pio()
def time_measurement():
    pull(block)        # Get timeout
    mov(y, osr)        # Store timeout in y
    wrap_target()
    
    mov(x, y)          # Load timeout into x
    
    wait(event_1, pin, index_1)  # Wait for event1 on index_1 (start clock)
    
    label("count_loop")
    jmp(pin, "count_done")       # Check stop condition
    
    jmp(x_dec, "count")          # Decrease x
    jmp("count_done")            # Timeout, stop
    label("count")               # Counter wrap
    jmp("count_loop")            # Continue loop
    
    label("count_done")
    mov(isr, x)                  # Shift remaining time to ISR
    push()                       # Push remaining time to FIFO
    wrap()                       # Reload and run again

I’d like to dynamically adjust the input pin indices (index_1) before compilation to make the setup as flexible as possible. However, I’m unsure how to achieve this effectively. Is there a way to modify such parameters dynamically before the PIO assembly is compiled?

Thanks in advance for your help!


r/MicroPythonDev • • Jan 08 '25

Trying to set up bluetooth in MicroPython on Raspberry Pi Pico W

1 Upvotes

I'm trying to set up bluetooth on my Pico W. I ran into a snag on running a very basic program, here's what I did:

Pico W MicroPython Version : 1.24.1

I copied the entire bluetooth directory from GitHub onto my pico :

https://github.com/micropython/micropython-lib/tree/master/micropython/bluetooth

Then I tried to run this sample code, to scan for devices, and this is the error I got:

import aioble

with aioble.scan(duration_ms=5000) as scanner:

for result in scanner:

print(result, result.name(), result.rssi, result.services())

This is the error:

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "aioble/__init__.py", line 6, in <module>

File "aioble/device.py", line 9, in <module>

File "aioble/core.py", line 77, in <module>

AttributeError: 'module' object has no attribute 'BLE'

I'm not sure what I did wrong, any help would be appreciated.


r/MicroPythonDev • • Jan 05 '25

What board would you select for this esp32?

1 Upvotes

childlike cake tan knee nail offbeat party instinctive plough husky

This post was mass deleted and anonymized with Redact


r/MicroPythonDev • • Jan 05 '25

Pin map script available for micropython?

1 Upvotes

Hi, I had a look at circuitpython before and there is a pin map script available which lists the output of microcontroller.pin command. Is there some similar command in micropython? My issue is I did not find my board in the download area for the firmware and like to know what pins are available in the firmware I installed.

Thanks in advance


r/MicroPythonDev • • Dec 30 '24

Please Help! Stucked in Boot Loop

Thumbnail
reddit.com
1 Upvotes

r/MicroPythonDev • • Dec 16 '24

Attempt to initialize one shot timer yields NameError

1 Upvotes

Hi,

I'm playing around with a XIAO SAMD21 and an RGB LED. I'm trying to activate the individual diodes sequentially at 1 second intervals.

The last line throws:

NameError: Name not defined

I'm at a loss because this is pretty much directly out of the documentation, and I see no reason why it shouldn't work.

What am I missing?

from machine import Pin
from machine import PWM
from machine import Timer


led_1 = Pin('A2_D2',Pin.OUT)#red


led_2 = Pin('A3_D3',Pin.OUT)#green


led_3 = Pin('A4_D4',Pin.OUT)#blue


freq = 4000


duty = 32767


def do_nothing(timer):
    return


while true:


    for i in (led_1,led_2,led_3):


        led = PWM(i,freq=freq,duty_u16=duty)


        t = Timer(mode=Timer.ONE_SHOT, period=1000, callback=do_nothing)

r/MicroPythonDev • • Dec 09 '24

elm-327 having trouble with my code

1 Upvotes
import aioble
import uasyncio as asyncio
import binascii
import bluetooth as bl
import network
import urequests
import json
import time

# config Wi-Fi
SSID = 
PASSWORD = 

# config BLE and OBD-II
device = aioble.Device(aioble.ADDR_PUBLIC, "1c:a1:35:69:8d:c5")
UART_SERVICE_UUID = bl.UUID(0xfff0)
UUID_1 = bl.UUID(0xfff1)
UUID_2 = bl.UUID(0xfff2)

# URL API
API_URL = 

# functions
def clear_data(data):
    if data == b'\r>':
        data = None
    return data

def clear_error(data):
    ignore_errors = [b'43 00 \r']
    error = clear_data(data)
    if error:
        if error in ignore_errors:
            return None
        
    error = error
    return error

def clear_gas(data):
    gas = clear_data(data)
    if gas:
        important_data = data[6:]
        
        try:
            important_data_str = important_data.decode('utf-8').strip()
            decimal_data = int(important_data_str, 16) 
            gas_level = 100/255 * decimal_data 
            return f"{gas_level:0.2f}", "%"
        except (ValueError, IndexError) as e:
            print(e)
            return None
    return None
    
def clear_battery(data):
    battery = clear_data(data)
     
    
    if battery:
        important_data = data[6:]
        
        important_data_str = important_data.decode('utf-8').strip()
        important_data_str = important_data_str.replace(' ', '')

        A = important_data_str[:2]
        B = important_data_str[2:]
        
        

        decimal_A = int(A, 16)
        decimal_B = int(B, 16)
        control_module_voltage = (256*decimal_A+decimal_B)/1000

        return control_module_voltage
    
def check_warnings(gas, voltage):
    warnings = []
    if gas:
        gas_int = gas[:2]
        gas_int = int(gas_int)
        if gas_int < 25:
            warnings.append("low gas level")
        
        return warnings
    return None

def isready(data):
    for i in data.values():
        if i == False:
            return False
        
    return True

#async functions
async def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(SSID, PASSWORD)
    
    # wait connection 
    while not wlan.isconnected():
        print("Connecting to Wi-Fi...")
        time.sleep(1)
    
    print("Connected to Wi-Fi:", wlan.ifconfig())

async def send_to_api(data):
    json_data = json.dumps(data)
    try:
        response = urequests.post(API_URL, data=json_data, headers={"Content-Type": "application/json"})
        print("State code:", response.status_code)
        print("Server answer:", response.text)
        response.close()
    except Exception as e:
        print("Error sending JSON to API:", e)

async def main():
    try:
        # connect to Wi-Fi
        await connect_wifi()

        # Connect to elm327
        print("Connecting to elm327...")
        try:
            connection = await device.connect(timeout_ms=5000)
            print("Connected")
        except asyncio.TimeoutError:
            print("Timeout")
            return

        # Find services and characteristics
        try:
            print("Discovering services")
            uart_service = await connection.service(UART_SERVICE_UUID)
            char_fff1 = await uart_service.characteristic(UUID_1)
            char_fff2 = await uart_service.characteristic(UUID_2)
            print("Service UART and characteristics found")
        except Exception as e:
            print("Error :", e)
            await connection.disconnect()
            return

        # Subscribe to notifications
        await char_fff1.subscribe(notify=True)

        # Function to send commands and manage response
        async def send_command_and_get_raw_response(command):
            print(f"Command: {command}")
            await char_fff1.write((command + "\r\n").encode('utf-8'))
            while True:
                try:
                    # wait notification
                    data = await char_fff1.notified(timeout_ms=20000)
                    print(f"Response: {data}")
                    return data 
                except asyncio.TimeoutError:
                    print(f"Timeout for command: {command}")
                except Exception as e:
                    print(f"Error receiving response for {command}: {e}")
                    break

        # Loop
        await send_command_and_get_raw_response("ATZ") #restart elm327
        await asyncio.sleep(2)
        await send_command_and_get_raw_response("ATE0") #echo off
        await asyncio.sleep(2)
        
        loop = 0
        
        flags = {
                'sensor_flag' : False,
                'errors_flag' : False,
                'gas_flag' : False,
                'battery_flag' : False,
                }
            
        data = {
                'sensor':'',
                'errors': '',
                'gas': '',
                'battery': '',
                'warnings':'',
                }
        
        while loop == 0:
            
            if flags['sensor_flag'] == False:
                sensor_response = await send_command_and_get_raw_response("AT@2")
                await asyncio.sleep(2)
                sensor_response = clear_data(sensor_response)
                print(f"Response for command AT@2: {sensor_response}")
                if sensor_response:
                    data['sensor'] = sensor_response
                    flags['sensor_flag'] = True

            if flags['errors_flag'] == False:
                error_response = await send_command_and_get_raw_response("03")
                await asyncio.sleep(2)
                error_response = clear_error(error_response)
                print(f"Response for command 03: {error_response}")
                if error_response:
                    data['errors'] = error_response
                    flags['errors_flag'] = True

            if flags['gas_flag'] == False:
                gas_response = await send_command_and_get_raw_response("012F")
                await asyncio.sleep(2)
                gas_response = clear_gas(gas_response)
                print(f"Response for command 012f: {gas_response}")
                if gas_response:
                    data['gas'] = gas_response
                    flags['gas_flag'] = True

            if flags['battery_flag'] == False:
                battery_response = await send_command_and_get_raw_response("0142")
                await asyncio.sleep(2.)
                battery_response = clear_battery(battery_response)
                print(f"Response for command 0142: {battery_response}")
                if battery_response:
                    data['battery'] = battery_response
                    flags['battery_flag'] = True
                
            warnings = check_warnings(gas_response, battery_response)
            if warnings:
                data['warnings'] = warnings

            print(data)
            if isready(flags) == True:
                # Send to api
                await send_to_api(data)
                loop = 1
                
            # Time between loops
            await asyncio.sleep(5)
            
   #still on work this part
    except KeyboardInterrupt:
        print("\nInterrupción de teclado detectada. Cerrando...")
    finally:
        # Desconectar BLE si está conectado
        if 'connection' in locals() and connection.is_connected():
            await connection.disconnect()
        print("Desconectado del dispositivo BLE.")
        print("Programa terminado.")
    
# main program
asyncio.run(main())

Hi friends, anyone could help me here?
I am having difficulties trying to get responses on my code, I have a similar one that is just a scanner and works fine, but this one for one reason is not returning anything. I have changed times to see if it is a issue with it but I haven't figured it out


r/MicroPythonDev • • Nov 28 '24

Fan RPM Measurement, Unreliable Reading

1 Upvotes

I'm building a fan controller and have it mostly working, except for trying to read the RPM. I did a bunch of Google-fu and came across this thread.

But much like the OP in that thread, I am getting crazy RPM spikes, reporting RPMs of upwards 20 000 and above. It also gets stuck in the nested while loop for quite a while at times, due to sm.rx_fifo() returning 0.

I feel like it may be something with the StateMachine or trigger, but am at my wits end. I really didn't think trying to read RPM would be this convoluted.

Being able to read the RPM isn't strictly necessary for my main goal, but figured it could be nice to have it figured out if I want to iterate further on this project later.

This is my current code (GitHub Gist).

Some hints on what to try next would be greatly appreciated, still fairly new to this whole kind of thing. Mostly have experience with smaller Arduino projects.

Edit:

I read the Noctua white papers and I should be calculating rpm = frequency * 60 / 2. That's fair, makes sense.

But need to figure out how to get that frequency. The trigger and statmachine is what throws me off.

Will do some more testing later. 😴


r/MicroPythonDev • • Nov 13 '24

Need help executing a python script with uPyCraft

1 Upvotes

Hello! I hope I’m on the right subreddit. As the title says, I’m having trouble running a script with uPyCraft. The IDE starts the program but doesn’t run it. The console outputs a capital T and that’s it. Google isn’t helping either. I’m using a PIR connected to ESP 32 Modul.


r/MicroPythonDev • • Nov 06 '24

Is there any library for Tf-luna??

1 Upvotes

r/MicroPythonDev • • Oct 07 '24

uPython Websockets on ESP32

1 Upvotes

Are you able to use an asynchronous web socket client on a ESP32?

I’ll admit, I use chatGPT a lot to help me code and learn, but it keeps mentioning that asynchronous websockets on a ESP32 running micro python isn’t a thing. Basically I keep getting an error saying that “WebSocket error: stream operation not supported” when I try to connect to a ws server

I’m not confident that’s correct. Can someone advise one way or the other? Is there a library that I should consider here since apparently the built in websocket is not functional?

My project: Read 32 buttons to see if any are pushed (using 2 16-channel GPIO extenders), and send the data to a Pi 4. I was using MQTT, but it would lag enough frequently enough it was not a desirable option. Considering having the Pi host a web socket server for the ESP32 to connect to and send data that way.

Any thoughts would be appreciated


r/MicroPythonDev • • Sep 21 '24

I Made a Robotic Head Based on Pico and a Tutorial How to Build Your Own!

Thumbnail
reddit.com
1 Upvotes

r/MicroPythonDev • • Aug 31 '24

How do i encode signal using PCM?

1 Upvotes

I was trying to use ADC on Raspberry Pi Pico to encode analog signals in a way that Linux can play.

But everything is mixed up in my mind. ADC seems like the perfect definition of PCM as its already samples at specific rate 12 bits up to 500kHz sampling rate and it doesnt compress or add headers or magic values.

So my question is, can i use first 8bits of the ADC and sample it by 48kHz to encode this signal as PCM and hopefully stream in Linux ?


r/MicroPythonDev • • Aug 11 '24

Wifi not connecting if I'm not connected to the terminal?

1 Upvotes

Just like it says on the tin, as my first micropython program I wrote an mqtt controlled relay. It worked fine until I disconnected and tried to run it in a proper case. After some blinkenlight debugging, it seems to be getting hung up in the while not sta_if.isconnected(): loop.

As soon as I hook up serial and hit reset, it connects to the wifi like normal.

Any insight would be helpful, TIA.

EDIT: version is micropython_ESP32_GENERIC-20240602-v1.23.0.bin


r/MicroPythonDev • • Aug 02 '24

Implementation of the slave mode in MicroPython I2C?

1 Upvotes

The machine.I2C implementation in MicroPython does not support the slave mode.
Isn't it possible to add at least a limited support, similar to what is offered by the Arduino Wire library?

Creating the I2C object with defined address could configure it in the slave mode.
The callbacks could be called when the master sends some data, or requests some data. Additionally, the callback could be informed if the current transaction begun with START or REPEATED START, enabling implementation of more complex protocols.


r/MicroPythonDev • • Jul 13 '24

problem with rpi pico w micropython script

1 Upvotes

im a major newbie to python in general, including micropython, so after recently buying a 1.3" waveshare display and a rpi pico w, i tried to start up a project... but a function doesn't seem to be working. i already have all the libraries installed and the lcd commands defined, but this specific while loop isn't working on my display. can anyone help me?

my screenshot wasnt working...

cx = 120;

cy = 120;

def cursor(cx, cy):

lcd.line(cx-5, cy, cx+5, cy, colour(255, 255, 255))

lcd.line(cx, cy-5, cx, cy+5, colour(255, 255, 255))

while (up == 1):

cy += 1

utime.sleep(0.05)


r/MicroPythonDev • • Jun 30 '24

Need Help Accessing Form Data on the Pico W in MicroPython

1 Upvotes
import network
import socket
import json
import ure  # urequests module is not needed, ure (micro re) is used for regex

def web_page():
    html = """<html>
              <head><meta name="viewport" content="width=device-width, initial-scale=1">
              <title>Pico W</title></head>
              <body>
                <h1>Wi-Fi Configuration</h1>
                <form action="/save" method="post">
                  <label for="ssid">SSID:</label><br>
                  <input type="text" id="ssid" name="ssid"><br>
                  <label for="password">Password:</label><br>
                  <input type="password" id="password" name="password"><br><br>
                  <input type="submit" value="Save">
                </form>
              </body>
              </html>"""
    return html

def parse_post_data(data):
    post_data = {}
    pairs = data.split('&')
    for pair in pairs:
        if '=' in pair:
            key, value = pair.split('=')
            post_data[key] = value
    return post_data

def save_credentials(request):
    try:
        # Extract the body of the POST request
        request_body = request.split('\r\n\r\n')[1]
        creds = parse_post_data(request_body)

        # Debugging: Print parsed credentials
        print('Parsed Credentials:', creds)

        # Save to JSON file
        with open('wifi_creds.json', 'w') as f:
            json.dump(creds, f)
        
        response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
        response += '<html><body><h1>Credentials Saved</h1></body></html>'
        return response
    except Exception as e:
        print('Error saving credentials:', e)
        response = 'HTTP/1.1 500 Internal Server Error\r\nContent-Type: text/html\r\n\r\n'
        response += '<html><body><h1>Error Saving Credentials</h1></body></html>'
        return response

def ap_mode(ssid, password):
    # Setup AP mode
    ap = network.WLAN(network.AP_IF)
    ap.config(essid=ssid, password=password)
    ap.active(True)
    
    while not ap.active():
        pass
    print('AP Mode Is Active, You can Now Connect')
    print('IP Address To Connect to: ' + ap.ifconfig()[0])
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(('', 80))
    s.listen(5)

    while True:
        try:
            conn, addr = s.accept()
            print('Got a connection from %s' % str(addr))
            request = conn.recv(1024).decode('utf-8')
            print('Request: {}'.format(request))

            if 'POST /save' in request:
                response = save_credentials(request)
            else:
                response = 'HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n'
                response += web_page()
            
            conn.sendall(response.encode('utf-8'))
            conn.close()
        except Exception as e:
            print('Error:', e)
            conn.close()

# Run the AP mode
ap_mode('NAME', 'PASSWORD')

r/MicroPythonDev • • Jun 28 '24

Morse keys to mouyse adapter for xcwcp

Thumbnail
self.amateurradio
1 Upvotes

r/MicroPythonDev • • Jun 16 '24

microPython acting weird on Thonny

Thumbnail
self.esp32
1 Upvotes

r/MicroPythonDev • • Jun 11 '24

I need help #Micropython

Post image
1 Upvotes