# -----------------------------
# Connections
# GP14 --> 1A
# GP15 --> 2A
# GP16 --> EN (PWM)
# -----------------------------
import machine
import utime
utime.sleep(1)
# Direction pins
ch_1A = machine.Pin(14, machine.Pin.OUT)
ch_2A = machine.Pin(15, machine.Pin.OUT)
# PWM on enable pin
pwm = machine.PWM(machine.Pin(16))
pwm.freq(1000)
pwm.duty_u16(0)
# -----------------------------
def stop_motor():
"""Stop the motor safely."""
pwm.duty_u16(0)
ch_1A.value(0)
ch_2A.value(0)
# -----------------------------
def motor_driver(duty, direction):
"""
duty : 0–100 (%)
direction : 0 = CW, 1 = CCW
"""
# Validate inputs
if not (0 <= duty <= 100):
raise ValueError("Duty cycle must be between 0 and 100")
if direction not in (0, 1):
raise ValueError("Direction must be 0 (CW) or 1 (CCW)")
# If duty is zero → stop
if duty == 0:
stop_motor()
return
# Set direction first
if direction == 0: # Clockwise
ch_1A.value(1)
ch_2A.value(0)
else: # Counterclockwise
ch_1A.value(0)
ch_2A.value(1)
# Apply PWM
duty_u16 = int(duty * 65535 / 100)
pwm.duty_u16(duty_u16)
# -----------------------------
# Main program
# -----------------------------
while True:
print("Starting!")
motor_driver(100, 0) # CW, full speed
utime.sleep(2)
stop_motor()
utime.sleep(1)
motor_driver(50, 1) # CCW, half speed
utime.sleep(2)
stop_motor()
utime.sleep(2)