Example Code for Arduino - PWM Output (Basic Tutorial)
The ESP32-S3 PWM can be freely mapped to other ports to output. The sample code below demonstrates the steps for configuring that. The LED will show a fade-in/fade-off effect when everything is set up.
Hardware Preparation
FireBeetle 2 ESP32-S3 AI Board with OV2640 Camera x 1
Software Preparation
When you use the ESP32 for the first time, you need to know the following steps:
-
Add the ESP32 development board in Arduino IDE (How to add the ESP32 board to Arduino IDE?)
-
Select the development board and serial port
-
Burn the program
Basic APIs
The PWM function of ESP32-S3 needs to be declared in advance.
-
ledcSetup(Channel, freq, resolution)
-
Description: set the PWM signal properties
-
Parameter:
-
LedChannel: the channel that generates PWM signal
-
freq: PWM frequency
-
resolution: PWM resolution
-
-
-
ledcAttachPin(GPIO, Channel)
-
Description: specify which GPIO the signal will appear upon
-
Parameter:
-
GPIO: the GPIO that will output the signal
-
Channel: the channel that will generate the signal
-
-
-
ledcWrite(Channel, dutyCycle)
-
Description:output PWM signal
-
Parameter:
-
Channel: the channel that generates PWM signal
-
dutyCycle: PWM value
-
-
Sample Code
/*LED fading example
*
*/
const int ledPin = 21; // Actual LED pin for outputting PWM signal
//Setting PWM properties
const int freq = 5000;//PWM frequence
const int ledChannel = 0;//Channel that generates pwm signal
const int resolution = 8;//8-bit resolution
void setup(){
//Configure LED PWM functionalitites
ledcSetup(ledChannel, freq, resolution);
//Attach the channel to the GPIO to be controlled
ledcAttachPin(ledPin, ledChannel);
}
void loop(){
//LED fade in
for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
//LED fade off
for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
// changing the LED brightness with PWM
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
}
Was this article helpful?
