Tasten Abfragen und Menü: Unterschied zwischen den Versionen
Peter (Diskussion | Beiträge) Die Seite wurde neu angelegt: „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: --- = Tasten und Menü = == 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…“ |
Peter (Diskussion | Beiträge) |
||
| (11 dazwischenliegende Versionen desselben Benutzers werden nicht angezeigt) | |||
| Zeile 1: | Zeile 1: | ||
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: | 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 | |||
--- | --- | ||
= | = Tastenabfrage = | ||
== 4x4 Matrix== | |||
== Tastenabfrage mit fünf Tasten (GPIO 0–4) == | == Tastenabfrage mit fünf Tasten (GPIO 0–4) == | ||
| Zeile 19: | Zeile 24: | ||
* Taste losgelassen → HIGH (1) | * Taste losgelassen → HIGH (1) | ||
=== Beispielcode === <syntaxhighlight lang="python"> | === Beispielcode === | ||
<syntaxhighlight lang="python"> | |||
from machine import Pin | from machine import Pin | ||
import time | import time | ||
| Zeile 27: | Zeile 33: | ||
while True: | while True: | ||
for i, btn in enumerate(buttons): | for i, btn in enumerate(buttons): | ||
if not btn.value(): | if not btn.value(): | ||
print(f"Taste {i} (Pin {button_pins[i]}) gedrückt") | print(f"Taste {i} (Pin {button_pins[i]}) gedrückt") | ||
time.sleep(0.05) </syntaxhighlight> | time.sleep(0.05) | ||
</syntaxhighlight> | |||
=== Verbesserte Entprellung === <syntaxhighlight lang="python"> | === Verbesserte Entprellung === | ||
<syntaxhighlight lang="python"> | |||
from machine import Pin | from machine import Pin | ||
import time | import time | ||
| Zeile 41: | Zeile 49: | ||
while True: | while True: | ||
for i, btn in enumerate(buttons): | for i, btn in enumerate(buttons): | ||
state = btn.value() | state = btn.value() | ||
if state != last_state[i]: | if state != last_state[i]: | ||
time.sleep(0.02) | time.sleep(0.02) | ||
if not btn.value(): | if not btn.value(): | ||
print(f"Taste {i} gedrückt") | print(f"Taste {i} gedrückt") | ||
last_state[i] = state | last_state[i] = state | ||
time.sleep(0.01) </syntaxhighlight> | time.sleep(0.01) | ||
</syntaxhighlight> | |||
=== Variante mit Interrupts === <syntaxhighlight lang="python"> | === Variante mit Interrupts === | ||
<syntaxhighlight lang="python"> | |||
from machine import Pin | from machine import Pin | ||
def button_handler(pin): | def button_handler(pin): | ||
print(f"Taste an Pin {pin.id()} gedrückt") | print(f"Taste an Pin {pin.id()} gedrückt") | ||
buttons = [Pin(i, Pin.IN, Pin.PULL_UP) for i in range(5)] | buttons = [Pin(i, Pin.IN, Pin.PULL_UP) for i in range(5)] | ||
for b in buttons: | for b in buttons: | ||
b.irq(trigger=Pin.IRQ_FALLING, handler=button_handler) </syntaxhighlight> | b.irq(trigger=Pin.IRQ_FALLING, handler=button_handler) | ||
</syntaxhighlight> | |||
--- | --- | ||
| Zeile 78: | Zeile 89: | ||
if not buttons['ok'].value(): | if not buttons['ok'].value(): | ||
print("OK-Taste gedrückt") </syntaxhighlight> | print("OK-Taste gedrückt") | ||
</syntaxhighlight> | |||
--- | --- | ||
| Zeile 92: | Zeile 104: | ||
button_names = ('rauf', 'links', 'ok', 'rechts', 'runter') | button_names = ('rauf', 'links', 'ok', 'rechts', 'runter') | ||
button_pins = [0, 1, 2, 3, 4] | button_pins = [0, 1, 2, 3, 4] | ||
buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP) | buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP) for name, pin in zip(button_names, button_pins)} | ||
for name, pin in zip(button_names, button_pins)} | |||
def wait_for_button(): | def wait_for_button(): | ||
while True: | while True: | ||
for name, btn in buttons.items(): | for name, btn in buttons.items(): | ||
if not btn.value(): | if not btn.value(): | ||
while not btn.value(): | while not btn.value(): | ||
time.sleep(0.01) | time.sleep(0.01) | ||
return name | return name | ||
time.sleep(0.01) | time.sleep(0.01) | ||
def check_buttons(): | def check_buttons(): | ||
for name, btn in buttons.items(): | for name, btn in buttons.items(): | ||
if not btn.value(): | if not btn.value(): | ||
return name | return name | ||
return None | return None | ||
def wait_for(name, block=True): | def wait_for(name, block=True): | ||
btn = buttons.get(name) | btn = buttons.get(name) | ||
if not btn: | if not btn: | ||
raise ValueError("Unbekannter Tastenname:", name) | raise ValueError("Unbekannter Tastenname:", name) | ||
``` | ``` | ||
| Zeile 125: | Zeile 136: | ||
return not btn.value() | return not btn.value() | ||
``` | ``` | ||
</syntaxhighlight> | |||
Verwendung: | |||
<syntaxhighlight lang="python"> | |||
Verwendung: <syntaxhighlight lang="python"> | |||
print("Bitte Taste drücken...") | print("Bitte Taste drücken...") | ||
taste = wait_for_button() | taste = wait_for_button() | ||
| Zeile 134: | Zeile 145: | ||
if wait_for("ok", block=False): | if wait_for("ok", block=False): | ||
print("OK gedrückt") </syntaxhighlight> | print("OK gedrückt") | ||
</syntaxhighlight> | |||
--- | --- | ||
= Menü= | |||
== Textbasiertes Menü == | == Textbasiertes Menü == | ||
| Zeile 187: | Zeile 201: | ||
button_names = ('rauf', 'links', 'ok', 'rechts', 'runter') | button_names = ('rauf', 'links', 'ok', 'rechts', 'runter') | ||
button_pins = [0, 1, 2, 3, 4] | button_pins = [0, 1, 2, 3, 4] | ||
buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP) | buttons = {name: Pin(pin, Pin.IN, Pin.PULL_UP) for name, pin in zip(button_names, button_pins)} | ||
for name, pin in zip(button_names, button_pins)} | |||
def wait_for_button(): | def wait_for_button(): | ||
while True: | while True: | ||
for name, btn in buttons.items(): | for name, btn in buttons.items(): | ||
if not btn.value(): | if not btn.value(): | ||
while not btn.value(): | while not btn.value(): | ||
time.sleep(0.01) | time.sleep(0.01) | ||
return name | return name | ||
time.sleep(0.01) | time.sleep(0.01) | ||
def menu(items): | def menu(items): | ||
index = 0 | index = 0 | ||
top = 0 | top = 0 | ||
visible = 4 | visible = 4 | ||
n = len(items) | n = len(items) | ||
``` | ``` | ||
| Zeile 364: | Zeile 377: | ||
Möchtest du, dass ich dir auch noch eine asynchrone (nicht-blockierende) Version dieses Menüs für gleichzeitige Hintergrundaufgaben ergänze? | Möchtest du, dass ich dir auch noch eine asynchrone (nicht-blockierende) Version dieses Menüs für gleichzeitige Hintergrundaufgaben ergänze? | ||
== Navigation== | |||
[[Hauptseite| Zurück zur Hauptseite]] | |||
Aktuelle Version vom 27. Dezember 2025, 19:29 Uhr
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
---
Tastenabfrage
[Bearbeiten]4x4 Matrix
[Bearbeiten]Tastenabfrage mit fünf Tasten (GPIO 0–4)
[Bearbeiten]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
[Bearbeiten]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
[Bearbeiten]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
[Bearbeiten]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
[Bearbeiten]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
[Bearbeiten]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ü
[Bearbeiten]Textbasiertes Menü
[Bearbeiten]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
[Bearbeiten]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)
[Bearbeiten]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
[Bearbeiten]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?