🐻 Tutorial 10 - Potentiometer

A potentiometer, or pot for short, is an electronic component that allows you to adjust the resistance of a circuit by turning a knob. In the case of controlling LED brightness using Raspberry Pi Pico, you would use a potentiometer to adjust the duty cycle of a pulse-width modulation (PWM) signal, which in turn controls the brightness of an LED.

To use a potentiometer with Raspberry Pi Pico to control PWM to an LED, you would need to connect it to an analog input pin and use the Python programming language to read the analog value and adjust the PWM signal accordingly.

Here are the steps to set up a circuit that uses a poten

Components Needed

ComponentQuantity
Raspberry Pi Pico W1
Micro USB Cable1
Breadboard1
WiresSeveral
LED1
Resistor1 - 220Ω
Potentiometer1

Fritzing Diagram

Code

import machine
import utime

potentiometer = machine.ADC(28)
led = machine.PWM(machine.Pin(15))
led.freq(1000)

while True:
    value=potentiometer.read_u16()
    print(value)
    led.duty_u16(value)
    utime.sleep_ms(200)

Code Explanation

  1. Importing necessary modules:
import machine
import utime

The code imports the machine module, which is typically used for interacting with hardware on microcontrollers, and the utime module, which is used for time-related operations.

  1. Setting up the potentiometer and LED pins:
potentiometer = machine.ADC(28)
led = machine.PWM(machine.Pin(15))
led.freq(1000)

The code sets up a potentiometer and an LED. It creates an ADC (Analog-to-Digital Converter) object for the potentiometer using pin number 28 and a PWM (Pulse Width Modulation) object for the LED using pin number 15. It also sets the frequency of the LED PWM signal to 1000 Hz using the freq() method.

  1. Reading potentiometer value and controlling LED duty cycle:
while True:
    value = potentiometer.read_u16()
    print(value)
    led.duty_u16(value)
    utime.sleep_ms(200)

The code enters an infinite loop and reads the value of the potentiometer using the read_u16() method, which reads the analog value as a 16-bit unsigned integer. It stores the value in the value variable. The code then sets the duty cycle of the LED PWM signal using the duty_u16() method, passing the potentiometer value as the duty cycle value. This means the brightness of the LED will be controlled by the value of the potentiometer. Finally, the code sleeps for 200 milliseconds using the utime.sleep_ms() method, providing a delay to avoid continuous reading and processing of potentiometer values.