"""
Alumno: Nava Villagrana Brian Ulises
No. Control: 19211692
Practica: Menu OLED
"""
from machine import Pin, I2C
from os import listdir
from ssd1306 import SSD1306_I2C
from time import sleep
# I2C variables
id = 0
sda = Pin(0)
scl = Pin(1)
i2c = I2C(id=id, scl=scl, sda=sda)
# Screen Variables
width = 128
height = 64
line = 1
highlight = 1
shift = 0
list_length = 0
total_lines = 6
# create the display
oled = SSD1306_I2C(width=width, height=height, i2c=i2c)
oled.init_display()
# Setup the buttons
button_next = Pin(16, Pin.IN, Pin.PULL_UP) # Button to navigate to the next item
button_prev = Pin(17, Pin.IN, Pin.PULL_UP) # Button to navigate to the previous item
button_select = Pin(18, Pin.IN, Pin.PULL_UP) # Button to select an item
# for tracking the button state
button_down = False
def get_files():
""" Get a list of Python files in the root folder of the Pico """
files = listdir()
menu = []
for file in files:
if file.endswith(".py"):
menu.append(file)
return menu
def show_menu(menu):
""" Shows the menu on the screen"""
global line, highlight, shift, list_length
# Clear the display
oled.fill_rect(0, 0, width, height, 0)
# Shift the list of files so that it shows on the display
list_length = len(menu)
short_list = menu[shift:shift + total_lines]
for idx, item in enumerate(short_list, 1):
if highlight == idx:
oled.fill_rect(0, (idx - 1) * 10, width, 10, 1)
oled.text(">", 0, (idx - 1) * 10, 0)
oled.text(item, 10, (idx - 1) * 10, 0)
else:
oled.text(item, 10, (idx - 1) * 10, 1)
oled.show()
def launch(filename):
""" Launch the Python script <filename> """
global file_list
# Clear the screen
oled.fill_rect(0, 0, width, height, 0)
oled.text("Launching", 1, 10)
oled.text(filename, 1, 20)
oled.show()
sleep(3)
exec(open(filename).read())
show_menu(file_list)
# Get the list of Python files and display the menu
file_list = get_files()
show_menu(file_list)
# Repeat forever
while True:
if button_next.value() == False:
if highlight < total_lines and highlight < len(file_list) - shift:
highlight += 1
elif shift + total_lines < len(file_list):
shift += 1
show_menu(file_list)
if button_prev.value() == False:
if highlight > 1:
highlight -= 1
elif shift > 0:
shift -= 1
show_menu(file_list)
if button_select.value() == False and not button_down:
button_down = True
if 0 < highlight <= len(file_list) - shift:
print("Launching", file_list[highlight - 1 + shift])
# execute script
launch(file_list[highlight - 1 + shift])
print("Returned from launch")
# Debounce button
if button_select.value() == True and button_down:
button_down = False