9. Chapter Potentiometer & LED
Earlier we have learned the use of ADC and PWM. In this chapter, we will learn how to use a potentiometer to control the brightness of an LED.
9.1. Project Soft Light
In this project, we will make a soft light. We will use an ADC Module to read ADC values of a potentiometer and map it to duty cycle of the PWM used to control the brightness of a LED. Then you can change the brightness of a LED by adjusting the potentiometer.
9.1.1. Component List
ESP32-S3 WROOM x1
|
GPIO Extension Board x1
|
|||
Breadboard x1
|
||||
LED x1 |
Resistor 220Ω x1
|
Jumper M/M x2
|
Rotary potentiometer x1 |
|
9.1.2. Circuit
Schematic diagram |
|---|
|
Hardware connection. If you need any support, please feel free to contact us via: support@freenove.com |
|
9.1.3. Code
Move the program folder “Freenove_Basic_Starter_Kit_for_ESP32_S3/Python/Python_Codes” to disk(D) in advance with the path of “D:/Micropython_Codes”.
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “Soft_LED” and double click “Soft_LED.py”.
9.1.3.1. Soft_LED
Click “Run current script”. Rotate the handle of potentiometer and the brightness of LED will change correspondingly.
The following is the code:
1from machine import Pin,PWM,ADC
2import time
3
4pwm =PWM(Pin(14,Pin.OUT),1000)
5adc=ADC(Pin(1))
6adc.atten(ADC.ATTN_11DB)
7adc.width(ADC.WIDTH_12BIT)
8
9def remap(value,oldMin,oldMax,newMin,newMax):
10 return int((value)*(newMax-newMin)/(oldMax-oldMin))
11
12try:
13 while True:
14 adcValue=adc.read()
15 pwmValue=remap(adcValue,0,4095,0,1023)
16 pwm.duty(pwmValue)
17 print(adcValue,pwmValue)
18 time.sleep_ms(100)
19except:
20 adc.deinit()
21 pwm.deinit()
22
23
24
25
In the code, read the ADC value of potentiometer and map it to the duty cycle of PWM to control LED brightness.
9.2. Project Soft Colorful Light
In this project, 3 potentiometers are used to control the RGB LED and in principle it is the same as the Soft Light project. Namely, read the voltage value of the potentiometer and then convert it to PWM used to control LED brightness. Difference is that the original project only controlled one LED, but this project required (3) RGB LEDs.
9.2.1. Component List
ESP32-S3 WROOM x1
|
GPIO Extension Board x1
|
|||
Breadboard x1
|
||||
RGBLED x1 |
Resistor 220Ω x1
|
Jumper M/M x13
|
Rotary potentiometer x3 |
|
9.2.2. Circuit
Schematic diagram |
|---|
|
Hardware connection. If you need any support, please feel free to contact us via: support@freenove.com |
|
9.2.3. Code
Open “Thonny”, click “This computer” -> “D:” -> “Micropython_Codes” -> “Soft_Colorful_Light” and double click “Soft_Colorful_Light.py”.
9.2.3.1. Soft_Colorful_Light
Click “Run current script” and control the change of RGBLED color by rotating the handles of three rotary potentiometers.
The following is the program code:
In the code, read the ADC value of 3 potentiometers and map it into PWM duty cycle to control the control 3 LEDs with different color of RGBLED, respectively.











