Create menu with buttons to tap when motion detected

Hi there,

Trying to have my pyportal titano show up 6 buttons when it detects motion. I’m sure I can figure out the action assignment (MQTT to Home Assistant) however I’ve obtained the following code from ChatGPT but when installing it as a file (and the bitmap files) to the device with the respective libraries installed, it just comes up with a Ctrl-D option to restart and not working at all. Any assistance would be excellent!
Code I have as follows:

import time
import board
import digitalio
import adafruit_imageload
import displayio
from adafruit_pyportal import PyPortal

# Configuration for the PyPortal display
DISPLAY_WIDTH = 480
DISPLAY_HEIGHT = 320

# Path to image files for action buttons
BUTTON_IMAGE_PATHS = [
    "button1.bmp",
    "button2.bmp",
    "button3.bmp",
    "button4.bmp",
    "button5.bmp",
    "button6.bmp",
]

# Initialize the PyPortal
pyportal = PyPortal(default_bg=None)

# Set up PIR motion sensor
motion_sensor = digitalio.DigitalInOut(board.D13)
motion_sensor.direction = digitalio.Direction.INPUT

# Load the button images
button_images = [None] * len(BUTTON_IMAGE_PATHS)
for idx, button_path in enumerate(BUTTON_IMAGE_PATHS):
    button_images[idx] = adafruit_imageload.load(button_path)

# Function to display the action buttons
def display_buttons():
    group = displayio.Group()
    for idx, image in enumerate(button_images):
        sprite = displayio.Sprite(image, x=80 + (idx % 2) * 200, y=60 + (idx // 2) * 100)
        group.append(sprite)
    pyportal.splash.append(group)

# Function to remove the action buttons from the display
def remove_buttons():
    pyportal.splash.pop()

while True:
    if motion_sensor.value:
        # Motion detected, display the action buttons
        display_buttons()
        # Wait for a short time to debounce the motion sensor
        time.sleep(0.5)
        while motion_sensor.value:
            # Wait until motion is no longer detected
            time.sleep(0.1)
        # Motion stopped, remove the action buttons
        remove_buttons()
    
    # Small delay to avoid busy-waiting
    time.sleep(0.1)

Hi Tom,

AI is great, but in this case you don’t even need to reach for it! Adafruit have written a full guide on displayio, the library used to assemble graphics for your screen:

At a glance, it seems like the chatgpt code isn’t actually writing to the pyportal, just assembling things in a displayio buffer.

image
Above is an excerpt from the relevant guide:

1 Like

Thanks James! I’ll take a proper look at this over the weekend and see how I go :slight_smile: