import machine
import time

# Initialize components
button = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
led = machine.Pin(12, machine.Pin.OUT)
buzzer = machine.PWM(machine.Pin(2))

# Stepper motor pins
stepper_pins = [machine.Pin(21, machine.Pin.OUT),
                machine.Pin(19, machine.Pin.OUT),
                machine.Pin(18, machine.Pin.OUT),
                machine.Pin(5, machine.Pin.OUT)]

# Function to play a simple tone on the buzzer
def play_buzzer(duration_ms):
    buzzer.duty(512)  # Set PWM duty cycle for 50% volume
    time.sleep_ms(duration_ms)
    buzzer.duty(0)  # Turn off the buzzer

# Function to drive the stepper motor
def drive_stepper(steps, delay, sequence):
    for _ in range(steps):
        for step in sequence:
            for i, pin in enumerate(stepper_pins):
                pin.value(step[i])
            time.sleep(delay)

# Function to check battery voltage
def check_battery_voltage():
    battery_pin = machine.ADC(machine.Pin(36))
    voltage = (battery_pin.read_u16() / 65535) * 3.3 * 2
    return voltage

# Main loop
while True:
    buzzer.duty(0)  # Turn off the buzzer
    if not button.value():  # Button pressed
        led.value(1)  # Turn on the LED
        
        voltage = check_battery_voltage()
        if voltage < 1.5:  # Adjust this value based on your battery voltage
            play_buzzer(1000)  # Play buzzer for 1 second
        
        # Forward motion sequence
        forward_sequence = [(1, 0, 1, 0), (0, 1, 1, 0), (0, 1, 0, 1), (1, 0, 0, 1)]
        drive_stepper(100, 0.01, forward_sequence)
        
        time.sleep(5)  # Stop for 5 seconds
        
        # Reverse motion sequence
        reverse_sequence = [(1, 0, 0, 1), (0, 1, 0, 1), (0, 1, 1, 0), (1, 0, 1, 0)]
        drive_stepper(100, 0.01, reverse_sequence)
        
        led.value(0)  # Turn off the LED

    time.sleep(0.1)  # Wait to avoid continuous button reads