LED Fade Effect Using Built-in LED (PWM)

LED Blink using built-in LED - with and without a delay

Main Diagram

Hardware Required

  • PICUNO Microcontroller board (built-in LED on GPIO 14)
  • USB cable (for power and programming)

Description

The PWM is used to control the brightness of the built-in LED. By gradually increasing the duty cycle from 0 to 255 and then decreasing it back to 0, the LED appears to smoothly fade in and out. This is done continuously in a loop.

Circuit Diagram

Circuit

  • Connect the PICUNO board to the computer using a USB cable.
  • No external wires or breadboard are required.
  • The built-in LED is internally connected to GPIO 14, which supports PWM.
  • The PWM signal is used to vary the brightness of the LED by changing the duty cycle.

Schematic

This project uses the built-in LED on GPIO 14 of the PicUNO board. No additional circuit components are required.

Code - C

int ledPin = 14;  // Built-in LED pin (PWM capable)

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // Fade in
  for (int brightness = 0; brightness <= 255; brightness += 5) {
    analogWrite(ledPin, brightness); // Set LED brightness
    delay(30); // Wait for a short time
  }
  // Fade out
  for (int brightness = 255; brightness >= 0; brightness -= 5) {
    analogWrite(ledPin, brightness); // Set LED brightness
    delay(30); // Wait for a short time
  }
}
int ledPin = 14 - Assigns GPIO 14 to control the LED.

pinMode(ledPin, OUTPUT) - Configures the pin as an output.

analogWrite(ledPin, brightness) - Sets PWM output with a value from 0 to 255.

delay(30) - Adds a small pause to make the fade effect smooth.

Code - Micropython

from machine import Pin, PWM
import time

led = PWM(Pin(14))  # PWM on pin 14 (onboard LED)
led.freq(1000)      # Set PWM frequency to 1kHz

while True:
    # Fade in
    for duty in range(0, 65536, 2048):  # step = 2048
        led.duty_u16(duty)
        time.sleep(0.05)
    # Fade out
    for duty in range(65535, -1, -2048):
        led.duty_u16(duty)
        time.sleep(0.05)
PWM(Pin(14)) - Sets GPIO 14 to work as a PWM output.

led.freq(1000) - Sets the PWM frequency to 1kHz.

led.duty_u16(duty) - Sets the PWM duty cycle from 0 to 65535.

time.sleep(0.05) - Adds a small pause for smooth fading transitions.