1. Functional description
This article introduces the process of using a knob to control the brightness of an LED. The knob uses a potentiometer, which generates voltage changes when rotated, and then is connected to the ESP32-C3 for ADC sampling. The PWM duty cycle is adjusted based on the sampled value, that is, the voltage value, to achieve the effect of controlling the brightness of the LED.
Figure 3-1 Blue and white potentiometer connection (A0 is connected to ESP32's ADC)
2. ESP32-C3 ADC
The ESP32-C3 datasheet has a description of the pins. In this example, IO5, which is ADC2_CH0, is selected as the analog signal input pin.
The use of ADC in the Arduino-ESP32 framework is very simple. There is no need to initialize IO. You can read the voltage value on the pin by calling the function analogRead(pin). Of course, the reference voltage is 3.3V, and the measurable voltage value is also between 0 and 3.3V. Because it is a 12-bit ADC, the corresponding digital conversion value is 0 to 4095.
Figure 3-2 Screenshot of the pin description table of ESP32-C3
3. Enable the serial port
I started to prepare to enable Serial1 (the usage introduced in the DFROBOT document), but later I wanted to try Serial first. I didn’t expect that the Type-C USB port of the board can be used as a serial port (corresponding to Serial), which saves the need to connect a USB-TTL module.
Of course, I also encountered some pitfalls during the test. Basically, once the board program enables Serial, it can automatically recognize the serial port through Type-C USB after powering on, which saves the need to pull the IO9 pin low. However, it was not clear at the beginning, and this form sometimes could not be recognized, so I spent a lot of time connecting USB-TTL.
The current test phenomenon is: after the Type-C USB is identified as a serial port, using a USB-TTL module to connect the board's 20th and 21st pins (see the pin description as RxD and TxD) has no effect. That is, only the serial port automatically identified by the Type-C USB can be used.
Figure 3-3 Output of the board's Type-C USB automatic identification serial port
4. ADC_PWM case code
#define LED 7 //GPIO7 控制LED
#define Ain 5 //GPIO6 模拟输入
int i = 0;
/*
* 设置PWM参数,采用10位分辨率,这样PWM有效值0~1023
* 和12 bit ADC采样值0~4095呈1:4,方便转化。
*/
const int freq = 5000; //PWM频率
const int ledChannel = 0; //信号生成GPIO
const int resolution = 10;//10位分辨率
void setup() {
/*
* 个人测试,如果启用了Serial,那么Beetle ESP32-C3的USB口可以作为串口使用,
* 而且重启后,即使IO9没有拉低也可以检测到串口(可能有小概率会检测不到)。
*/
Serial.begin(115200);
//设置LEDC通道8频率为5000,分辨率为10位
ledcSetup(ledChannel, freq, resolution);
//设置LEDC通道0在IO7上输出
ledcAttachPin(LED, ledChannel);
}
void loop() {
//读取Ain模拟口的数值(0-3.3V对应0-4095取值)
int n = analogRead(Ain);
//PWM输出,占空比有效值0~1023
ledcWrite(ledChannel, n/4);
delay(1);
i++;
if(i>=2000){
Serial.print("ADC value : ");
Serial.println(n);
i=0;
}
}