8.PWM(Pulse Width Modulation)
Last updated
Last updated
The ESP32 used by BiBoard is different from the 328P used by UNO. Because the PWM of ESP32 uses the matrix bus, it can be used on unspecified pins.
The PWM of ESP32 is called LED controller (LEDC). The LED PWM controller is mainly used to control LEDs, and it can also generate PWM signals for the control of other devices. The controller has 8 timers, corresponding to 8 high-speed channels and 8 low-speed channels, totaling 16 channels.
Compared with UNO, directly use "analogWrite()" to input any duty ratio between 0-255. The PWM control of ESP32 on BiBoard is more troublesome. The parameters that need to be controlled are as follows:
Manual selection of PWM channels (0-15) also improves the flexibility of the use of pins
The number of bits of the PWM waveform determines the resolution of the duty cycle of the PWM waveform. The higher the number of bits, the higher the accuracy.
The frequency of the PWM waveform determines the speed of the PWM waveform, the higher the frequency, the faster the speed.
The frequency of the PWM waveform and the number of bits are relative, the higher the number of bits, the lower the frequency. The following example is quoted from the ESP32 programming manual:
For example, when the PWM frequency is 5 kHz, the maximum duty cycle resolution can be 13 bits. This means that the duty cycle can be any value between 0 and 100%, with a resolution of ~0.012% (2 ** 13 = 8192 discrete levels of LED brightness).
The LED PWM controller can be used to generate high-frequency signals, enough to clock other devices such as digital camera modules. Here the maximum frequency can be 40 MHz, and the duty cycle resolution is 1 bit. In other words, the duty cycle is fixed at 50% and cannot be adjusted.
The LED PWM controller API can report an error when the set frequency and duty cycle resolution exceed the hardware range of the LED PWM controller. For example, if you try to set the frequency to 20 MHz and the duty cycle resolution to 3 bits, an error will be reported on the serial port monitor.
As shown above, we need to configure the channel, frequency and number of bits, and select the output pin.
Step 1: Configure the PWM controller
Step 2: Configure the PWM output pins
Step 3: Output PWM waveform
In the demo, we choose IO2 as the output pin, connect IO2 to an LED, and you can observe the effect of the LED breathing light.