#T2 M3- Week 14 โดย Ray Taladua
from machine import Pin, ADC, PWM
import time
# ---------- PIN SETUP ----------
POT_PIN = 34
SERVO_PIN = 32
LED_PINS = [18, 5, 16] # 3 LEDs
BTN_ON = 12 # Servo ON button
BTN_OFF = 13 # Servo OFF button
# ---------- POTENTIOMETER ----------
pot = ADC(Pin(POT_PIN))
pot.atten(ADC.ATTN_11DB)
pot.width(ADC.WIDTH_12BIT)
# ---------- SERVO ----------
servo = PWM(Pin(SERVO_PIN))
servo.freq(50)
MIN_US = 500
MAX_US = 2500
PERIOD_US = 20000
# ---------- LED SETUP ----------
leds = [Pin(pin, Pin.OUT) for pin in LED_PINS]
# ---------- BUTTON SETUP ----------
btn_on = Pin(BTN_ON, Pin.IN, Pin.PULL_UP)
btn_off = Pin(BTN_OFF, Pin.IN, Pin.PULL_UP)
# ---------- FUNCTIONS ----------
def angle_to_duty(angle):
angle = max(0, min(180, angle))
pulse = MIN_US + (MAX_US - MIN_US) * angle / 180
return int(pulse * 65535 / PERIOD_US)
def read_pot_smooth(samples=10):
total = 0
for _ in range(samples):
total += pot.read()
time.sleep_ms(2)
return total // samples
def update_leds(angle):
leds[0].value(1 if angle >= 60 else 0)
leds[1].value(1 if angle >= 120 else 0)
leds[2].value(1 if angle >= 180 else 0)
def turn_off_leds():
for led in leds:
led.value(0)
# ---------- MAIN LOOP ----------
servo_on = False
last_angle = -1
while True:
# --- BUTTON CONTROL ---
if not btn_on.value():
servo_on = True
time.sleep_ms(300) # debounce
if not btn_off.value():
servo_on = False
servo.deinit() # stop servo signal
turn_off_leds()
time.sleep_ms(300)
# --- SERVO ACTIVE ---
if servo_on:
adc_value = read_pot_smooth()
angle = int(adc_value * 180 / 4095)
if angle != last_angle:
servo.init(freq=50)
servo.duty_u16(angle_to_duty(angle))
update_leds(angle)
last_angle = angle
time.sleep_ms(40)