# Exercise No. 5 - Control of MK II Servo
# Libraries...
from machine import Pin, PWM, ADC
import time
# Pins...
servo = PWM(Pin(0), freq=50) # Set GP 0 as PWM pin.
bt1 = Pin(16, Pin.IN, Pin.PULL_DOWN) # Button to position at 0°.
bt2 = Pin(17, Pin.IN, Pin.PULL_DOWN) # Button to position at 180°.
converter = ADC(0) # Pin to connect the potentiometer to the converter.
# Variables...
control = 0 # Control for functions.
high_time = 0 # High time of the PWM.
aux_1 = 0 # Control to enable or disable the potentiometer.
aux_2 = 90 # Default position for the servo.
# Functions...
def button_1(pin):
global control
control = 1
def button_2(pin):
global control
control = 2
# Interrupts...
bt1.irq(handler=button_1, trigger=Pin.IRQ_RISING) # Trigger on button 1 press.
bt2.irq(handler=button_2, trigger=Pin.IRQ_RISING) # Trigger on button 2 press.
# Main...
print("Limit set to ", aux_2, "°.")
while True:
if control == 1: # If button 1 is pressed.
if aux_1 == 0:
aux_1 = 1
print("DISABLE POTENTIOMETER")
# servo.deinit() # Optional: De-initialize servo.
elif aux_1 >= 1:
aux_1 = 0
print("ENABLE POTENTIOMETER")
# servo.deinit() # Optional: De-initialize servo.
control = 0 # Reset control.
if control == 2: # If button 2 is pressed.
if aux_2 == 90:
aux_2 = 180
print("180°.")
elif aux_2 >= 180:
aux_2 = 90
print("90°.")
control = 0 # Reset control.
else:
if aux_1 == 0: # If potentiometer is enabled.
potentiometer = int(converter.read_u16() * aux_2 / 65535) # Convert ADC resolution to degrees.
high_time = (potentiometer + 45) * 100000 / 9 # Convert degrees to time (ns).
servo.duty_ns(int(high_time)) # Set the PWM high time for the servo.
time.sleep(0.002) # Small delay.
if aux_1 == 1: # If potentiometer is disabled.
servo.duty_u16(1310) # Fix servo at 0° - Duty cycle = 2%.
time.sleep(0.002) # Small delay.