LED brightness control using potentiometer (Analog read)

LED brightness control using potentiometer (Analog read)

Main Diagram

HARDWARE REQUIRED:

  • PICUNO Microcontroller board
  • 1 × LED
  • 1 × 220Ω resistor
  • 1 × 10kΩ Potentiometer
  • Breadboard
  • Jumper wires
  • USB cable

DESCRIPTION:

This project demonstrates to read an Analog voltage from a potentiometer and use it to control the brightness of an LED using PWM (Pulse Width Modulation). As the potentiometer is rotated, the Analog input value changes, and this is used to adjust the duty cycle of the PWM signal to the LED.

CIRCUIT DIAGRAM:

[Fritzing image to be added here]

  • Connect the PICUNO board to the computer using a USB cable.
  • Insert the LED on the breadboard.
  • Connect the Anode of the LED to one terminal of a 220Ω resistor.
  • Connect the other terminal of the resistor to GPIO pin 6.
  • Connect the Cathode of the LED to GND.
  • Connect outer terminals of the potentiometer to VCC and GND, centre terminal to Analog pin A0 (Pin 26 in PICUNO)

SCHEMATIC:

GPIO 6 → 220Ω Resistor → LED Anode

LED Cathode → GND

Potentiometer Outer Terminals → VCC, GND

Potentiometer Centre Terminal → A0

CODE -- C:

int potPin = A0;
int ledPin = 6; // PWM-capable pin

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int analogValue = analogRead(potPin);
  int pwmValue = map(analogValue, 0, 1023, 0, 255);

  analogWrite(ledPin, pwmValue);

  Serial.print(\"Analog Value: \");
  Serial.print(analogValue);
  Serial.print(\" PWM Value: \");
  Serial.println(pwmValue);

  delay(100);
}
analogRead(potPin) - Reads the potentiometer value (0--1023).

map(...) - Converts it to a PWM value (0--255).

analogWrite(ledPin, pwmValue) - Adjusts the brightness of the LED using PWM.

Serial.println(...) - Displays analog and PWM values.

CODE -- PYTHON:

from machine import ADC, Pin, PWM
import time

pot = ADC(0)
led = PWM(Pin(6))
led.freq(1000)

while True:
    analog = pot.read_u16()
    duty = analog // 256 # Convert 0--65535 to 0--255
    led.duty_u16(duty * 256) # Scale back to 0--65535

    print(\"Analog:\", analog, \" PWM Duty:\", duty)

    time.sleep(0.1)
ADC(0) - Reads analog voltage.

analog // 256 - Converts analog range to 0--255.

duty_u16(...) - Updates LED brightness accordingly.