Tasten Abfragen und Menü
Ich habe gerade einen interessanten Chat mit Chatgpt.com zum Thema Tasten Abfragen und Menü erstellen und nutzen geführt. Den möchte ich hier für die weitere Bearbeitung festhalten:
Hier der Link: https://chatgpt.com/c/68e7912c-45ec-8331-bc80-494f5c2e6ec5
---
Tasten
4x4 Matrix
Tastenabfrage mit fünf Tasten (GPIO 0–4)
Jede Taste wird an einen Eingangspin angeschlossen, der den internen Pull-Up-Widerstand nutzt.
Schaltung:
- Eine Seite des Tasters → GND
- Andere Seite → GPIO 0 bis 4
Damit gilt:
- Taste gedrückt → LOW (0)
- Taste losgelassen → HIGH (1)
Beispielcode
from machine import Pin
import time
button_pins = [0, 1, 2, 3, 4]
buttons = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in button_pins]
while True:
for i, btn in enumerate(buttons):
if not btn.value():
print(f"Taste {i} (Pin {button_pins[i]}) gedrückt")
time.sleep(0.05)Verbesserte Entprellung
from machine import Pin
import time
button_pins = [0, 1, 2, 3, 4]
buttons = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in button_pins]
last_state = [1] * len(buttons)
while True:
for i, btn in enumerate(buttons):
state = btn.value()
if state != last_state[i]:
time.sleep(0.02)
if not btn.value():
print(f"Taste {i} gedrückt")
last_state[i] = state
time.sleep(0.01)Variante mit Interrupts
from machine import Pin
def button_handler(pin):
print(f"Taste an Pin {pin.id()} gedrückt")
buttons = [Pin(i, Pin.IN, Pin.PULL_UP) for i in range(5)]
for b in buttons:
b.irq(trigger=Pin.IRQ_FALLING, handler=button_handler)---
Abfrage mit Tasternamen
Mit sprechenden Tasternamen wie „ok“, „links“, „rechts“ usw.
from machine import Pin
button_names = ('rauf', 'links', 'ok', 'rechts', 'runter')
button_pins = [0, 1, 2, 3, 4]
# Dictionary Name → Pin
buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP)
for name, pin in zip(button_names, button_pins)}
if not buttons['ok'].value():
print("OK-Taste gedrückt")---
Komfortfunktionen für Tasten
Hier sind drei nützliche Funktionen zur flexiblen Tastenabfrage:
from machine import Pin
import time
button_names = ('rauf', 'links', 'ok', 'rechts', 'runter')
button_pins = [0, 1, 2, 3, 4]
buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP) for name, pin in zip(button_names, button_pins)}
def wait_for_button():
while True:
for name, btn in buttons.items():
if not btn.value():
while not btn.value():
time.sleep(0.01)
return name
time.sleep(0.01)
def check_buttons():
for name, btn in buttons.items():
if not btn.value():
return name
return None
def wait_for(name, block=True):
btn = buttons.get(name)
if not btn:
raise ValueError("Unbekannter Tastenname:", name)
```
if block:
while btn.value():
time.sleep(0.01)
while not btn.value():
time.sleep(0.01)
return True
else:
return not btn.value()
```Verwendung:
print("Bitte Taste drücken...")
taste = wait_for_button()
print("Gedrückt:", taste)
if wait_for("ok", block=False):
print("OK gedrückt")---
Menü
Textbasiertes Menü
Ein einfaches, rein textbasiertes Menü für die serielle Konsole:
def menu(items):
index = 0
n = len(items)
```
def redraw():
print("\n--- Menü ---")
for i, item in enumerate(items):
prefix = ">" if i == index else " "
print(f"{prefix} {item}")
redraw()
while True:
taste = wait_for_button()
if taste == "rauf":
index = (index - 1) % n
elif taste == "runter":
index = (index + 1) % n
elif taste == "ok":
print(f"Ausgewählt: {items[index]}")
return items[index]
redraw()
```---
Menü auf 0.42"-OLED-Display mit Scrollen
Für ein 0.42"-Display (z. B. SSD1306) mit 4 Zeilen à 9 Zeichen.
from machine import Pin, I2C
import time
from ssd1306 import SSD1306_I2C
WIDTH = 72
HEIGHT = 40
i2c = I2C(0, scl=Pin(7), sda=Pin(6))
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
button_names = ('rauf', 'links', 'ok', 'rechts', 'runter')
button_pins = [0, 1, 2, 3, 4]
buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP) for name, pin in zip(button_names, button_pins)}
def wait_for_button():
while True:
for name, btn in buttons.items():
if not btn.value():
while not btn.value():
time.sleep(0.01)
return name
time.sleep(0.01)
def menu(items):
index = 0
top = 0
visible = 4
n = len(items)
```
def redraw():
oled.fill(0)
for i in range(visible):
pos = top + i
if pos < n:
prefix = ">" if pos == index else " "
text = (prefix + " " + items[pos])[:9]
oled.text(text, 0, i * 10)
oled.show()
redraw()
while True:
taste = wait_for_button()
if taste == "rauf":
index = (index - 1) % n
if index < top:
top = index
elif taste == "runter":
index = (index + 1) % n
if index >= top + visible:
top = index - visible + 1
elif taste == "ok":
oled.fill(0)
oled.text("Wähle:", 0, 0)
oled.text(items[index][:9], 0, 10)
oled.show()
time.sleep(0.5)
return items[index]
redraw()
```---
Modulares Menümodul (menu.py)
Dieses Modul kannst du als menu.py speichern und in jedem Projekt verwenden.
# menu.py
from machine import Pin, I2C
import time
from ssd1306 import SSD1306_I2C
WIDTH = 72
HEIGHT = 40
I2C_SCL = 7
I2C_SDA = 6
BUTTON_NAMES = ('rauf', 'links', 'ok', 'rechts', 'runter')
BUTTON_PINS = [0, 1, 2, 3, 4]
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA))
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP)
for name, pin in zip(BUTTON_NAMES, BUTTON_PINS)}
def wait_for_button():
while True:
for name, btn in buttons.items():
if not btn.value():
while not btn.value():
time.sleep(0.01)
return name
time.sleep(0.01)
def run(items, title="Menü"):
index = 0
top = 0
visible = 4
n = len(items)
```
def redraw():
oled.fill(0)
if title:
oled.text(title[:9], 0, 0)
for i in range(visible):
pos = top + i
if pos < n:
prefix = ">" if pos == index else " "
text = (prefix + " " + items[pos])[:9]
y = (i + 1) * 10
oled.text(text, 0, y)
oled.show()
redraw()
while True:
taste = wait_for_button()
if taste == "rauf":
index = (index - 1) % n
if index < top:
top = index
elif taste == "runter":
index = (index + 1) % n
if index >= top + visible:
top = index - visible + 1
elif taste == "ok":
oled.fill(0)
oled.text("Wähle:", 0, 0)
oled.text(items[index][:9], 0, 10)
oled.show()
time.sleep(0.5)
return items[index]
redraw()
```Verwendung:
import menu
eintraege = [
"LED an",
"LED aus",
"Temperatur",
"Reset",
"WiFi Info",
"Status",
"Version",
"Abschalten"
]
auswahl = menu.run(eintraege, title="Hauptmenü")
print("Ausgewählt:", auswahl)---
Menü mit Funktionsobjekten
Menüpunkte können direkt Funktionen enthalten, die bei Auswahl ausgeführt werden.
import menu
def led_an():
print("LED eingeschaltet")
def led_aus():
print("LED ausgeschaltet")
def info():
print("Infoanzeige...")
eintraege = [
("LED an", led_an),
("LED aus", led_aus),
("Info", info),
]
aktion = menu.run(eintraege, title="Aktionen")
if callable(aktion):
aktion()---
Möchtest du, dass ich dir auch noch eine asynchrone (nicht-blockierende) Version dieses Menüs für gleichzeitige Hintergrundaufgaben ergänze?