from machine import Pin, PWM
from utime import sleep
# Initialize variables
value = "Mac " + "and " + "Cheese"
print(value)
# Pin setup
gled = Pin(3, Pin.OUT) # LED Pin
servo_pin = Pin(19, Pin.OUT) # Servo Pin
# Initialize PWM for servo control (50Hz frequency)
servo = PWM(servo_pin, freq=50)
# Button setup (with pull-down resistor)
bp = Pin(28, Pin.IN, Pin.PULL_DOWN)
# Function to set servo angle
def set_servo_angle(angle):
duty = int(40 + (angle / 180) * 115) # Convert angle to PWM duty cycle
servo.duty(duty)
# Initialize button press state flag
button_pressed = False
while True:
if bp.value() == 1 and not button_pressed: # If button is pressed and not already handled
print("Button pressed! Moving servo to 90 degrees.")
gled.value(1) # Turn on LED
set_servo_angle(90) # Move servo to 90 degrees
sleep(1) # Wait for servo to move
# Reset button press state after moving servo to 90 degrees
button_pressed = True
sleep(0.3) # Debounce time to prevent multiple triggers
elif bp.value() == 0 and button_pressed: # If button is released and we had a previous press
print("Button released! Moving servo to 0 degrees.")
gled.value(0) # Turn off LED
set_servo_angle(0) # Move servo to 0 degrees
sleep(1) # Wait for servo to move
# Reset button press state after moving servo to 0 degrees
button_pressed = False
sleep(0.3) # Debounce time to prevent multiple triggers
sleep(0.1) # Short delay to check button state periodically