from machine import Pin, PWM, ADC
from time import sleep
# Pin configuration
motor_pin = PWM(Pin(15)) # PWM output to simulate motor (connected to LED)
motor_pin.freq(1000) # Set frequency to 1kHz
pot_pin = ADC(Pin(26)) # Potentiometer connected to ADC0 (GP26)
button_pin = Pin(16, Pin.IN, Pin.PULL_UP) # Button with internal pull-up resistor
motor_running = False # Motor is initially stopped
def toggle_motor(pin):
"""Interrupt callback to toggle motor state."""
global motor_running
motor_running = not motor_running
print("Motor running:", motor_running)
# Attach the button to an interrupt
button_pin.irq(trigger=Pin.IRQ_FALLING, handler=toggle_motor)
while True:
if motor_running:
# Read potentiometer value (0-65535 range in MicroPython)
pot_value = pot_pin.read_u16()
# Map potentiometer value to PWM duty cycle (0-100%)
motor_pin.duty_u16(int(pot_value)) # Scale directly for 16-bit resolution
# Print the current motor "speed"
print(f"Potentiometer: {pot_value} -> Motor running at {int(pot_value / 65535 * 100)}% speed")
else:
motor_pin.duty_u16(0) # Stop the motor
sleep(0.1)