8. PWM
Last updated
Was this helpful?
Last updated
Was this helpful?
Was this helpful?
const int freq = 5000; // PWM frequency
const int ledcChannel = 0; // ledc channel, 0-15
const int resolution = 8; // resolution of PWM,8bit(0~255)
ledcSetup(ledcChannel, freq, resolution);ledcAttachPin(ledPin, ledcChannel);ledcWrite(ledcChannel, dutyCycle);/* In this demo, we show how to use PWM in BiBoard(ESP32)
* It's different from the Arduino UNO based on the ATMega328P
*/
// define the PWM pin
const int ledPin = 2; // 16 corresponds to GPIO16
// setting PWM properties
const int freq = 5000; // PWM frequency
const int ledcChannel = 0; // ledc channel, in ESP32 there're 16 ledc(PWM) channels
const int resolution = 8; // resolution of PWM
void setup(){
// configure ledc functionalitites
// channels 0-15, resolution 1-16 bits, freq limits depend on resolution
// ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);
ledcSetup(ledcChannel, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(ledPin, ledcChannel);
}
void loop(){
// increase the LED brightness
for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){
// changing the LED brightness with PWM
ledcWrite(ledcChannel, dutyCycle);
delay(15);
}
// decrease the LED brightness
for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
// changing the LED brightness with PWM
ledcWrite(ledcChannel, dutyCycle);
delay(15);
}
}