import utime
from machine import Pin
# Define pin for LED or any output device
led = Pin(21, Pin.OUT) # GPIO 15 on Pico Pi W
# Set PWM parameters
frequency = 1000 # Frequency in Hz (1 kHz by default)
duty_cycle = 50 # Initial duty cycle in percentage (0 to 100)
def generate_pwm(frequency, duty_cycle, duration_ms=1000):
# Ensure duty cycle is between 0 and 100
if duty_cycle < 0:
duty_cycle = 0
elif duty_cycle > 240:
duty_cycle = 240
# Calculate period and times in microseconds
period_us = int(1_000_000 / frequency) # Period in microseconds
high_time_us = int(period_us * (duty_cycle / 100)) # HIGH time in microseconds
low_time_us = period_us - high_time_us # LOW time in microseconds
# Generate PWM for the specified duration in milliseconds
start_time = utime.ticks_ms()
while utime.ticks_ms() - start_time < duration_ms:
# Set HIGH
led.value(1)
utime.sleep_us(high_time_us)
# Set LOW
led.value(0)
utime.sleep_us(low_time_us)
# Main loop to generate PWM with changing duty cycle
while True:
duty_cycle=int(input("Enter Duty Cycle (50-240): "))
generate_pwm(frequency, duty_cycle, duration_ms=500)