Arduino ESP32:模拟输出的PWM技术

学习目标:

  • 掌握 ESP32 PWM(模拟输出)。

  • 学习内容:

    使用Arduino开发ESP32产生PWM信号。构建一个简单的电路,使用ESP32的LED PWM控制器对LED进行调光,在不同的GPIO上同时获得相同的PWM信号。

     使用Arduino 通过PWM调光LED必须遵循的步骤:

    1.首先,选择一个PWM通道,从0到15共有16个通道。

    2.然后,设置PWM信号频率。对于LED来说,使用5000 Hz的频率是合适的。

    3. 设置信号的占空比分辨率,分辨率从1到16位。此处将使用8位分辨率,可以使用0到255的值来控制LED亮度(2的8次方)。

    4. 指定信号将出现在哪个或哪些GPIO上。为此,将使用以下函数:

    ledcAttachPin(GPIO, channel)       //输出信号的GPIO,产生信号的通道。

    5. 使用PWM控制LED亮度,可以使用以下函数:

    ledcWrite(channel, dutycycle);       // PWM信号的通道和占空比

    仿真结果:

    仿真网站:Wokwi – Online Arduino and ESP32 Simulator

     实验现象:

    LED灯循环变亮到变暗的过程。

    注意:LED较小的那部分为正极! 


    例程代码:

    // the number of the LED pin
    const int ledPin = 15;  // 15 corresponds to GPIO16
    
    // setting PWM properties
    const int freq = 5000;
    const int ledChannel = 0;
    const int resolution = 8;
     
    void setup(){
      // configure LED PWM functionalitites
      ledcSetup(ledChannel, freq, resolution);
      
      // attach the channel to the GPIO to be controlled
      ledcAttachPin(ledPin, ledChannel);
    }
     
    void loop(){
      // increase the LED brightness
      for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++){   
        // changing the LED brightness with PWM
        ledcWrite(ledChannel, dutyCycle);
        delay(15);
      }
    
      // decrease the LED brightness
      for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--){
        // changing the LED brightness with PWM
        ledcWrite(ledChannel, dutyCycle);   
        delay(15);
      }
    }
    物联沃分享整理
    物联沃-IOTWORD物联网 » Arduino ESP32:模拟输出的PWM技术

    发表评论