A MicroPython fading blink for ESP32

Below is a fading blink program I created for a Wemos Lolin32 Lite clone but it may be modified for other ESP32 boards by changing the LED_PIN value.

The CYCLE_TIME value sets the duration of a complete fade cycle in seconds.

The STEPS_PER_CYCLE value is set at a multiple of 50 to prevent beating with UK mains lighting. If your locality uses 60Hz mains frequency you might wish to make this a multiple of 60 (perhaps 480).

The cos function was chosen because the Wemos Lolin32 Lite has active-low LED drive. For boards with active-high LED drive an inverted cos function could be used instead.

import machine, math, time

LED_PIN = 22
CYCLE_TIME = 4

STEPS_PER_CYCLE = 400
STEPS_INTERVAL = CYCLE_TIME / STEPS_PER_CYCLE

pwm_led = machine.PWM(machine.Pin(LED_PIN), int(1 / STEPS_INTERVAL))

def set_fade(step):
    pwm_led.duty(int(511.5 * math.cos(2 * math.pi * step / STEPS_PER_CYCLE) + 512))
    time.sleep(STEPS_INTERVAL)

while True:
    for i in range(STEPS_PER_CYCLE):
        set_fade(i)

UPDATE: Remove the named parameter from PWM function call for newer versions of MicroPython.