说明
在ESP32里产生PWM有个叫LED PWM控制器的东西,它有16个通道,每个通道都能使用代码来配置
使用步骤
- 首先选择一个通道(0-15)
- 设置PWM的频率
- 设置占空比的分辨率,例如8位或者16位
- 将该通道绑定到具体的GPIO上 语句:ledcAttachPin(GPIO, channel)
- 设置通道号和占空比实现PWM 语句:ledcWrite(channel, dutycycle)
示例
使用PWM控制LED的亮度(呼吸灯效果),效果图片就不放上去了
#include <Arduino.h>
const int ledPin = 16; // 连接LED的GPIO 16
const int freq = 5000; // 设置PWM的频率
const int ledChannel = 0; // 设置PWM的通道
const int resolution = 8; // 设置PWM 占空比的分辨率 最大占空比为 2^8 = 256
void setup(){
// PWM初始化
ledcSetup(ledChannel, freq, resolution);
// 绑定PWM通道到GPIO16上
ledcAttachPin(ledPin, ledChannel);
}
void loop(){
// LED渐亮
for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){
// 改变PWM的占空比
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
// LED渐灭
for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
// 改变PWM的占空比
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
}
绑定多个GPIO
我们还可以使用一个PWM通道绑定多个GPIO
#include <Arduino.h>
const int ledPin1 = 16; // 连接LED1的GPIO 16
const int ledPin2 = 17; // 连接LED2的GPIO 17
const int ledPin3 = 18; // 连接LED1的GPIO 18
const int freq = 5000; // 设置PWM的频率
const int ledChannel = 0; // 设置PWM的通道
const int resolution = 8; // 设置PWM 占空比的分辨率 最大占空比为 2^8 = 256
void setup(){
// PWM初始化
ledcSetup(ledChannel, freq, resolution);
// 绑定PWM通道到GPIO16,17,18上
ledcAttachPin(ledPin1, ledChannel);
ledcAttachPin(ledPin2, ledChannel);
ledcAttachPin(ledPin3, ledChannel);
}
void loop(){
// LED渐亮
for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){
// 改变PWM的占空比,GPIO16,17,18产生相同的PWM信号
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
// LED渐灭
for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
// 改变PWM的占空比
ledcWrite(ledChannel, dutyCycle);
delay(15);
}
}
注意
GPIO34、35、36、39不能使用PWM