from machine import Pin, PWM
import time

# Define GPIO pins for the H-bridge
IN1 = Pin(16, Pin.OUT)
IN2 = Pin(17, Pin.OUT)
PWM_PIN = Pin(18, Pin.OUT)

# Set up PWM
pwm = PWM(PWM_PIN)
pwm.freq(1000)  # Set PWM frequency to 1 kHz
pwm.duty_u16(0)  # Start with 0% duty cycle

def motor_forward(speed):
    IN1.on()
    IN2.off()
    pwm.duty_u16(speed)  # Set speed

def motor_backward(speed):
    IN1.off()
    IN2.on()
    pwm.duty_u16(speed)

def motor_stop():
    IN1.off()
    IN2.off()
    pwm.duty_u16(0)  # Stop the motor

try:
    while True:
        # Move forward at half speed
        motor_forward(32768)  # 50% of 65535
        time.sleep(2)
        
        # Move backward at half speed
        motor_backward(32768)  # 50% of 65535
        time.sleep(2)
        
        # Stop the motor
        motor_stop()
        time.sleep(2)

except KeyboardInterrupt:
    motor_stop()  # Ensure motor is stopped on exit
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT