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 • • Oct 20 '24

Looking for a good MicroPython C extension project to follow – any recommendations?

8 Upvotes

Hey everyone, I've just finished my first custom MicroPython build and I’m thrilled about the ability to distribute my own libraries as UF2 files! I’m now diving deeper into adding C extensions, but I'm looking for a solid example project to guide me through it.

Ideally, I’d like to follow a project that:

  • Implements a C extension in MicroPython.

  • Uses a clean structure, where not everything is packed into the repo but instead uses external references (so I can learn about manifests and external dependencies).

  • Is beginner-friendly but not too trivial, so I can understand best practices for larger projects.

Any recommendations for something I can use as a reference? Thanks in advance!


r/MicroPythonDev • • Feb 17 '25

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

1 Upvotes

r/MicroPythonDev • • Jan 19 '25

Adding an SD card to your Raspberry Pi Pico project

Post image
11 Upvotes

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 • • Mar 02 '25

pygame

1 Upvotes

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


r/MicroPythonDev • • Oct 12 '24

Read and write ZIP files using micropython-zipfile

10 Upvotes

Ever wanted to read or write .zip archive files in MicroPython? Now there is a module for that: https://github.com/jonnor/micropython-zipfile
It supports the most common subsets of ZIP archives, including DEFLATE compression (when available in the MicroPython firmware build). I ported this from CPython 3.12, and used their quite comprehensive test suite (around 160 test-cases) to guide the development. I removed/skipped out some of the more niche tests though, to focus on core functionality relevant for a MicroPython usecase.

It is the first time I ported non-trivial (but reasonably stand-alone) CPython code to MicroPython, and it was interesting to see what kind of incompatibilities that exist. Many are rather minor, but it all adds up, taking several hours to address them all. Those considering to port other Python code to MicroPython (while still being runnable under CPython), might find some of the strategies interesting. See especially the top of `zipfile.py`, where I try to handle all the differences.

I initially created this because I wanted to support Numpy .npz files (which are ZIP archives). This format is popular for Data Science / Digital Signal Processing / Machine Learning / etc. And I needed it for https://github.com/emlearn/emlearn-micropython/ - a MicroPython library for Machine Learning.
But zip files are used for many purposes, so I hope this can be useful for someone else :)


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 • • Dec 30 '24

Please Help! Stucked in Boot Loop

Thumbnail
reddit.com
1 Upvotes

r/MicroPythonDev • • Feb 04 '25

MicroPython and Pyright

2 Upvotes

Hi,

I'm using a Neovim plugin https://github.com/jim-at-jibba/micropython.nvim

In status line it shows basedpyright linter; the suggested pyrightconfig.json file looks like this:

{

"reportMissingModuleSource": false

}

I get swamped with warnings like

Type annotation is missing for parameter...

Type of "value" is unknown...

I can create type annotation for my own files, but all the libraries lack them. What's the right policy with pyright?


r/MicroPythonDev • • Jan 04 '25

Automatic toothbrushing timer using accelerometer and machine learning

Thumbnail
reddit.com
1 Upvotes

r/MicroPythonDev • • Oct 14 '24

Monitoring noise levels with MicroPython

4 Upvotes

I built a sound level meter and IoT noise monitoring device. It can measure standard acoustical metrics for noise, and transmit them to an IoT dashboard. Code and instructions can be found here: https://github.com/emlearn/emlearn-micropython/tree/master/examples/soundlevel_iir

* For audio input, it uses an I2S digital microphone via the machine.I2S module.
* Running on ESP32
* For processing audio efficiently, this uses emlearn-micropython, a Machine Learning and Digital Signal Processing package for MicroPython: https://github.com/emlearn/emlearn-micropython
* For the IoT dashboard, it uses https://blynk.io/

General discussion thread about emlearn - follow for related news: https://github.com/orgs/micropython/discussions/16004


r/MicroPythonDev • • Jan 02 '25

Reading from stdin by using asyncio approach

Thumbnail
pastebin.com
3 Upvotes

Hi! I need to implement something extremely simple but I did not expect to struggle so long with no results at the end.

I need while main.py is running to read the stdin. Want to use stdin as configuration channel while the WiFi/MQTT/BLE affairs are running in parallel. All my code is written in async-await approach by using asyncio.

The board is ESP32 WROOM with the latest Micropython - v1.24.1 (2024-11-29) .bin

The last code I tried is that one from ChatGPT (attached a link) and I'm constantly hitting a wall after wall with it because of unavailable method in Micropython.

Did someone managed to read stdin with by using asyncio approach?


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 • • Dec 23 '24

lvgl for micropython?

6 Upvotes

Hi there!

I'm new to microcontrollers, having made only a few projects at this time. While looking to start a new project I realized that there aren't a lot of great GUI options with micropython, except lvgl.

I've been trying to install lvgl for days haha (to an esp32 on a windows pc, using Thonny IDE). I'm sure I'm just being foolish or missing an obvious step, but I'm totally at a loss.

Is there anywhere that has a step-by-step guide on this installation (extensive googling has netted me nothing)? The README on the Github is confusing for me, I think it makes too many assumptions of knowledge on my behalf. Or if anyone was willing to donate their time to write a guide and/or help me out I would, of course, be very grateful.

Thanks for your time!


r/MicroPythonDev • • Jun 18 '23

Thonny having issues uploading to esp on Windows

2 Upvotes

I uploaded all 3 sizes of micro Python to this esp8266 and a model 01. Thonny says it was a successful install yet this happens everytime and makes the thonny terminal spit junk.


r/MicroPythonDev • • Jun 27 '23

[Errno 21] EISDIR, cant find anything online about it. HELP!

1 Upvotes

r/MicroPythonDev • • Mar 03 '24

Solving the CORS error in Javascript with MicroPython

2 Upvotes

I was building a project in which some Javascript code needed to access my Raspberry Pi Pico wich was programmed with micropython. And I could not get the data from the Pico. By examining the Javascript console I saw there was a CORS error. This error occurs when a different computer tries to access your webserver.
I found out how to solve this and that may be handy for you all:

http://lucstechblog.blogspot.com/2024/03/solving-cors-error-in-micropython.html


r/MicroPythonDev • • Aug 06 '22

Basic equivalent functionality seems to be missing in MicroPython

5 Upvotes

I've been playing with Arduino for a decade now and I am trying to make the switch to MicroPython. I love the CLI, WebREPL, Thonny. I really fanboy over things like using the SPI flash chip on the ESP32 for storing my .py files.

However, I'm disappointed at the lack of cross over in some areas from the Arduino world. For example, changing the hostname on an ESP device so when it connects to my local DHCP, it has an intelligible name. I mean I have dozens of ESPs on my network, they can't all be ESP_A7GH2 or whatever, that's dumb. In the docs there is a slight mention of the hostname field in the WLAN section, but it only works in AP mode, not STA mode.

I googled and there's some forum posts from 2016 talking about someone needing to add this to the main branch of MicroPython. Yet it's still an issue. Seems like a simple enough addition. If I had a clue what I was doing, I would add it myself, but this sort of manipulation is beyond my available time right now.

My next headache involves WiFi UDP communication. For whatever reason, the python socket library forces UDP to be a one for one just like TCP. Normally in Arduino libraries I could deal with this by clearing the buffer of stored messages to get the latest real time data. However that functionality just doesn't exist. Maybe that's a flaw in python or socket. A friend of mine suggested some sort of LIFO array data type. I'm trying to pursue that now.

Right now, to deal with all this, I am attempting to compile Arduino code into .mpy files. I didn't find a lot on google about doing this. We'll see how it goes.

I just keep finding myself running into walls like this. Am I alone?


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 • • Sep 15 '23

Micropython as a task stm32

1 Upvotes

Hi,

Did anyone succeed in implementing micropython as a task (freertos) ? Because I cant figure it out on my stm32l4x6 ( I saw the esp32 and cc3200).

I Saw many questions on différent forum but no real exemple. I'm trying a basic micropython as task + led blink task.

Can someone share a minimalistic code or changes for the stm32 port ?


r/MicroPythonDev • • May 31 '23

remount on-board flash to a different filepath?

1 Upvotes

so how can i remount the onboard 2mb flash to "/flash/" instead of "/"


r/MicroPythonDev • • Feb 23 '24

Wlan.Scan updated docs?

1 Upvotes

I'm using Wlan.scan to look for networks. It works very well but the documentation lists these for security

#security:

#0 – open

#1 – WEP

#2 – WPA-PSK

#3 – WPA2-PSK

#4 – WPA/WPA2-PSK

The problem is I frequently get a 5 or a 7 for this field. Anyone know what that means? Is there updated documentation somewhere?

Here's the page I'm currenly using:

https://docs.micropython.org/en/latest/library/network.WLAN.html


r/MicroPythonDev • • May 15 '24

Simple timer-based input debouncing routine

3 Upvotes

I have seen a few different debouncing routines for MicroPython. Today I needed to implement debouncing immediately for ESP32. Below are the results of such a fresh attempt. I think that it may be interesting for somebody due to its simplicity.

print("Debouncing demo")
import machine as m
settling_time = 20 # Set to 1000 to see how does it work
p1=m.Pin(32,m.Pin.IN, m.Pin.PULL_UP)
p2=m.Pin(33,m.Pin.IN, m.Pin.PULL_UP)
t1 = m.Timer(1)
t2 = m.Timer(2)
def t1_cb(t):
    print('pin 1 change to ', p1.value())
    # Of course, you may add here your own code
def p1_cb(p):
    t1.init(mode=m.Timer.ONE_SHOT, period=settling_time, callback=t1_cb)
def t2_cb(t):
    print('pin 2 change to ', p2.value())
    # Of course, you may add here your own code
def p2_cb(p):
    t2.init(mode=m.Timer.ONE_SHOT, period=settling_time, callback=t2_cb)
p1.irq(trigger=m.Pin.IRQ_RISING | m.Pin.IRQ_FALLING, handler=p1_cb)    
p2.irq(trigger=m.Pin.IRQ_RISING | m.Pin.IRQ_FALLING, handler=p2_cb)

After running the above code, the correctly debounced values of the pins are printed after you press or release a button connected to 32 or 33 GPIO. You may add another code here (for example, in my final code I send the appropriate event codes to a queue). I have tested it in wokwi on ESP32 (https://wokwi.com/projects/397948297142838273 , use Q and W keys to control buttons).