from machine import UART, Pin
import time
from machine import Pin, I2C
import math
# Initialize UART2 (TX2 and RX2 on ESP32)
uart = UART(0, baudrate=9600, tx=0, rx=1) # TX2=GPIO17, RX2=GPIO16
def send_command(command, param=0):
"""
Sends a command to the MP3-TF-16P module.
:param command: The command byte.
:param param: The parameter for the command (16-bit value).
"""
packet = bytearray([
0x7E, # Start byte
0xFF, # Version
0x06, # Length
command, # Command
0x00, # Feedback (0x00 = no feedback)
(param >> 8) & 0xFF, # Parameter high byte
param & 0xFF, # Parameter low byte
0xEF # End byte
])
uart.write(packet)
def play_track(track_number):
"""
Plays a specific track from the SD card.
:param track_number: The track number to play (1-based index).
"""
print(f"Playing track: {track_number}")
send_command(0x03, track_number)
def set_volume(volume):
"""
Sets the playback volume.
:param volume: Volume level (0-30).
"""
if 0 <= volume <= 30:
print(f"Setting volume to: {volume}")
send_command(0x06, volume)
else:
print("Volume out of range (0-30)")
def stop_playback():
"""
Stops playback.
"""
print("Stopping playback")
send_command(0x16)
# Example usage
def main():
print("Initializing MP3-TF-16P module")
time.sleep(1) # Allow time for the module to initialize
set_volume(20) # Set volume to a moderate level
time.sleep(1)
play_track(1) # Play the first track
time.sleep(5) # Wait for 5 seconds
stop_playback() # Stop playback
# Run the example
main()
from machine import Pin, I2C
import time
import math
# I2C Setup (ESP32 Standard Pins)
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
MPU_ADDR = 0x68
# MPU6050 aktivieren
i2c.writeto_mem(MPU_ADDR, 0x6B, b'\x00')
# Sound Trigger Pin
sound = Pin(15, Pin.OUT)
sound.value(0)
MOTION_THRESHOLD = 20000
COOLDOWN = 500 # ms
last_trigger = 0
def read_raw_data(addr):
high = i2c.readfrom_mem(MPU_ADDR, addr, 1)[0]
low = i2c.readfrom_mem(MPU_ADDR, addr + 1, 1)[0]
value = (high << 8) | low
if value > 32768:
value -= 65536
return value
while True:
# Gyro Werte lesen
gx = read_raw_data(0x43)
gy = read_raw_data(0x45)
gz = read_raw_data(0x47)
motion = abs(gx) + abs(gy) + abs(gz)
print("Motion:", motion)
if motion > MOTION_THRESHOLD:
if time.ticks_diff(time.ticks_ms(), last_trigger) > COOLDOWN:
print("Swing erkannt!")
sound.value(1) # Sound trigger HIGH
time.sleep_ms(100)
sound.value(0)
last_trigger = time.ticks_ms()
time.sleep_ms(50)