Skip to content

Instantly share code, notes, and snippets.

@enrmx
Last active May 19, 2025 08:17
Show Gist options
  • Select an option

  • Save enrmx/231ef1486d7319aa40867d07f4efaff8 to your computer and use it in GitHub Desktop.

Select an option

Save enrmx/231ef1486d7319aa40867d07f4efaff8 to your computer and use it in GitHub Desktop.

馃И Pr谩cticas con Raspberry Pi Pico W en Wokwi

Este documento describe dos pr谩cticas distintas realizadas con la Raspberry Pi Pico W utilizando MicroPython y simuladas en Wokwi. Se cubren los aspectos de hardware, software y l贸gica implementada.


馃Л Pr谩ctica 1: Men煤 Interactivo en Pantalla OLED

馃幆 Objetivo

Dise帽ar un men煤 interactivo usando una pantalla OLED SSD1306 y botones f铆sicos para navegar y seleccionar opciones.

馃敡 Componentes

  • Raspberry Pi Pico W
  • Pantalla OLED SSD1306 (I2C, direcci贸n 0x3C)
  • 3 Botones (Up, Down, Select)
  • Wokwi Simulator

馃攲 Conexiones

Componente Pin Pico Funci贸n
OLED VCC 3V3 Alimentaci贸n
OLED GND GND Tierra
OLED SCL GP1 I2C Clock
OLED SDA GP0 I2C Data
Bot贸n "Up" GP2 Subir opci贸n
Bot贸n "Down" GP3 Bajar opci贸n
Bot贸n "Select" GP4 Selecci贸n

馃摳 Diagrama

Image

馃搫 C贸digo MicroPython

from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import time

i2c = I2C(0, scl=Pin(1), sda=Pin(0))
oled = SSD1306_I2C(128, 64, i2c)

btn_up = Pin(2, Pin.IN, Pin.PULL_DOWN)
btn_down = Pin(3, Pin.IN, Pin.PULL_DOWN)
btn_select = Pin(4, Pin.IN, Pin.PULL_DOWN)

menu = ["Opci贸n 1", "Opci贸n 2", "Opci贸n 3"]
index = 0

def mostrar_menu():
    oled.fill(0)
    for i, item in enumerate(menu):
        prefix = ">" if i == index else " "
        oled.text(prefix + item, 0, i * 10)
    oled.show()

while True:
    mostrar_menu()
    if btn_up.value():
        index = (index - 1) % len(menu)
        time.sleep(0.2)
    if btn_down.value():
        index = (index + 1) % len(menu)
        time.sleep(0.2)
    if btn_select.value():
        oled.fill(0)
        oled.text("Seleccionado:", 0, 0)
        oled.text(menu[index], 0, 20)
        oled.show()
        time.sleep(2)

馃寪 Pr谩ctica 2: Conexi贸n a WiFi y Consulta a la API de OpenAI

馃幆 Objetivo

Conectar la Raspberry Pi Pico W a una red WiFi, enviar un prompt a la API de OpenAI y mostrar la respuesta en consola, con un l铆mite de 50 caracteres.

馃敡 Componentes

  • Raspberry Pi Pico W
  • WiFi (en este caso, red: TecNM-ITT)
  • API Key de OpenAI
  • Librer铆as: network, urequests, json

馃搫 C贸digo MicroPython

import network
import urequests
import time
import json

SSID = 'TecNM-ITT'
OPENAI_API_KEY = "sk-proj-T0NHwPvcIA..."

def connect_wifi(ssid):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print("Conectando a WiFi...")
        wlan.connect(ssid)
        while not wlan.isconnected():
            time.sleep(0.5)
    print("WiFi conectado:", wlan.ifconfig())
    return wlan

def openai_chat(prompt):
    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + OPENAI_API_KEY
    }
    data = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {"role": "system", "content": "Eres un asistente creativo que responde en m谩ximo 50 caracteres."},
            {"role": "user", "content": prompt}
        ],
        "max_tokens": 50,
        "temperature": 0.7
    }
    try:
        response = urequests.post(url, headers=headers, data=json.dumps(data))
        if response.status_code == 200:
            content = response.json()['choices'][0]['message']['content']
            return content[:50] + "..." if len(content) > 50 else content
        else:
            return "Error HTTP: " + str(response.status_code)
    except Exception as e:
        return "Error: " + str(e)

def main():
    connect_wifi(SSID)
    prompt = "Dame una receta o un chiste divertido en m谩ximo 50 caracteres."
    respuesta = openai_chat(prompt)
    print("Respuesta OpenAI:")
    print(respuesta)

if __name__ == "__main__":
    main()

馃搶 Conclusi贸n General

Estas pr谩cticas demuestran el potencial del Raspberry Pi Pico W como dispositivo de interacci贸n embebida e IoT.

  • La Pr谩ctica 1 se enfoca en interfaz de usuario b谩sica con botones y pantalla.
  • La Pr谩ctica 2 muestra conectividad y uso de APIs modernas como OpenAI desde un microcontrolador.

Estas bases pueden integrarse para crear un asistente inteligente con men煤 f铆sico, expandiendo sus funciones con sensores u otras salidas.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment