esp32使用ledcWrite實現呼吸燈

ESP32 沒有Arduino輸出 PWM 的 analogWrite(pin, value) 方法,取而代之的 ESP32 有一個 LEDC ,設計是用來控制 LED 。

ESP32 的 LEDC 總共有16個路通道(0 ~ 15),分爲高低速兩組,高速通道(0 ~ 7)由80MHz時鐘驅動,低速通道(8 ~ 15)由 1MHz 時鐘驅動。

#include <Arduino.h>

int freq = 2000;    // 頻率
int channel = 0;    // 通道
int resolution = 8;   // 分辨率

const int led = 18;
void setup()
{

  ledcSetup(channel, freq, resolution); // 設置通道
  ledcAttachPin(led, channel);  // 將通道與對應的引腳連接
}

void loop()
{
  // 逐漸變亮
  for (int dutyCycle = 0; dutyCycle <= 255; dutyCycle = dutyCycle + 5)
  {
    ledcWrite(channel, dutyCycle);  // 輸出PWM
    delay(20);
  }

  // 逐漸變暗
  for (int dutyCycle = 255; dutyCycle >= 0; dutyCycle = dutyCycle - 5)
  {
    ledcWrite(channel, dutyCycle);  // 輸出PWM
    delay(20);
  }
}

參考:https://blog.csdn.net/weixin_43474408/article/details/90743082

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章