//PWM控制
int pwm1 = 21;
//管道esp32有16个管道,0-7为80hz 高速管道  8-16为低速管道
const int channel1 = 0;
//分辨率  2的8次方 256
const int resolution = 8;
//PWM频率
const int freq = 1000;
//初始值 49%
int PwmNow = 125;
//累加数
int fadeAmount = 5;  
void setup(void) {
pinMode(pwm1, OUTPUT);
  ledcSetup(channel1, freq, resolution);
  ledcAttachPin(pwm1, channel1);
  ledcWrite(channel1, PwmNow);
  pinMode(infrared1, INPUT_PULLUP);
  digitalWrite(infrared1, LOW);
}
void loop(void) {
  if(PwmNow<255){
      PwmNow = PwmNow + fadeAmount;
      ledcWrite(channel1, PwmNow);
      int temp=PwmNow*100/255;
      String tempStr=String(temp)+"%";
Serial.println(tempStr);
delay(1000);
  }
//上面这个是旧版的 下面是新版的使用方法
#include <Arduino.h>

int  pwmPin = 4;              //PWM控制
const uint32_t pwmFreq = 1000;   // PWM频率1kHz（1-10kHz适合电机控制）
const uint8_t pwmResolution = 8; // 8位分辨率（0-255）

void setup(void) {
  // 手动选择通道并绑定引脚
  if (ledcAttach( pwmPin,pwmFreq, pwmResolution)) {
    Serial.printf("PWM配置成功：频率=%dHz，分辨率=%dbits\n", pwmFreq, pwmResolution);
  } else {
     Serial.println("PWM配置失败，请检查参数或通道占用情况");
  }
}
ledcWrite(pwmPin,angle);//这个设置占空比