import machine
import utime
import os
import _thread
import ujson
# Pin-Zuweisungen (passe diese an deine Hardware an)
button_relay = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
button_record = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
button_playback = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
relay_pin = machine.Pin(27, machine.Pin.OUT)
# SD-Karte
sd = machine.SDCard()
os.mount(sd, '/sd')
# Globale Variablen
recording = False
sequence = []
filename = 'sequence.json'
# Funktion zum Schalten des Relais
def toggle_relay():
relay_pin.value(not relay_pin.value())
# Funktion zum Aufzeichnen der Sequenz
def record_sequence():
global recording, sequence
while recording:
if button_relay.value() == 0:
sequence.append(utime.ticks_ms())
# Funktion zum Abspielen der Sequenz
def playback_sequence():
global sequence
try:
with open('/sd/' + filename, 'r') as f:
sequence = ujson.load(f)
except OSError:
print("Keine Sequenz gefunden")
return
for timestamp in sequence:
utime.sleep_ms(timestamp - utime.ticks_ms())
toggle_relay()
# Hauptloop
def main():
global recording
while True:
if button_record.value() == 0 and not recording:
recording = True
sequence = []
_thread.start_new_thread(record_sequence, ())
elif button_record.value() == 0 and recording:
recording = False
with open('/sd/' + filename, 'w') as f:
ujson.dump(sequence, f, indent=4)
elif button_playback.value() == 0:
playback_sequence()
main()