from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import utime
# Microbuttons connections to Pico's GPIOs
SW_0 = 7
SW_2 = 9
# OLED I2C connection to Pico's GPIOs
OLED_SDA = 14
OLED_SCL = 15
# Initialize I2C to control the OLED, 8x8 pixel font
i2c = I2C(1, scl=Pin(OLED_SCL), sda=Pin(OLED_SDA), freq=400000)
OLED_WIDTH, OLED_HEIGHT = 128, 64
oled = SSD1306_I2C(OLED_WIDTH, OLED_HEIGHT, i2c, 0x3c, 8)
# UFO position (initialize at the left edge)
ufo_x = 0
# Flags to track button state
sw0_pressed = False
sw2_pressed = False
# Template functions for microbuttons
def button_0(pin):
global ufo_x
global sw0_pressed
sw0_pressed = True
def button_2(pin):
global ufo_x
global sw2_pressed
sw2_pressed = True
# Create microbutton objects and attach the interrupt handlers
but0 = Pin(SW_0, Pin.IN, Pin.PULL_UP)
but2 = Pin(SW_2, Pin.IN, Pin.PULL_UP)
but0.irq(handler=button_0, trigger=Pin.IRQ_FALLING)
but2.irq(handler=button_2, trigger=Pin.IRQ_FALLING)
# Function to draw the UFO on the OLED
def draw_ufo():
oled.fill(0) # Clear the display
oled.text('<=>', ufo_x, OLED_HEIGHT - 8)
oled.show()
try:
draw_ufo() # Initial drawing of the UFO
while True:
if sw0_pressed:
if ufo_x < OLED_WIDTH - 20 - 5:
ufo_x += 5
sw0_pressed = False
draw_ufo() # Reset the flag after moving
elif sw2_pressed:
if ufo_x > 0:
ufo_x -= 5
draw_ufo()
sw2_pressed = False # Reset the flag after moving
except KeyboardInterrupt:
pass # Handle the interruption gracefully, e.g., clean up if necessary
Loading
ssd1306
ssd1306