Arduino : 在 bpibit 上使用 LEDC (PWM) (3)

Arduino core for the ESP32 并没有一般 Arduino 中用来输出 PWM 的 analogWrite(pin, value) 方法,取而代之的 ESP32 有一个 LEDC ,设计是用来控制 LED 。
ESP32 的 LEDC 总共有16个路通道(0 ~ 15),分为高低速两组,高速通道(0 ~ 7)由80MHz时钟驱动,低速通道(8 ~ 15)由 1MHz 时钟驱动。

目的

使用 LEDC 实现呼吸灯

配套介绍

编写工具: vscode + platformIO 安装教程

硬件: bpibit

主要函数

  • double ledcSetup(uint8_t channel, double freq, uint8_t resolution_bits)
    设置 LEDC 通道对应的频率和计数位数(占空比分辨率),
    该方法返回最终频率

通道最终频率 = 时钟 / ( 分频系数 * ( 1 << 计数位数 ) );(分频系数最大为1024)

参数 功能
channel 为通道号,取值0 ~ 15
freq 期望设置频率
resolution_bits 计数位数,取值0 ~ 20(该值决定后面 ledcWrite 方法中占空比可写值,比如该值写10,则占空比最大可写1023 即 (1<<resolution_bits)-1 )
  • void ledcWrite(uint8_t channel, uint32_t duty)
    指定通道输出一定占空比波形

  • double ledcWriteTone(uint8_t channel, double freq)
    类似于 arduino 的 tone ,当外接无源蜂鸣器的时候可以发出某个声音(根据频率不同而不同)

  • double ledcWriteNote(uint8_t channel, note_t note, uint8_t octave)
    该方法是上面方法的进一步封装,可以直接输出指定调式和音阶声音的信号

参数 功能
note 调式,相当于do、re、mi、fa……这些,取值为NOTE_C, NOTE_Cs, NOTE_D, NOTE_Eb, NOTE_E, NOTE_F, NOTE_Fs, NOTE_G, NOTE_Gs, NOTE_A, NOTE_Bb, NOTE_B

octave音阶,取值0~7;
乐理相关内容可以参考下面文章:
http://www.360doc.com/content/17/1231/01/47685146_717797647.shtml
https://www.musicbody.net/sns/index.php?s=/news/index/detail/id/406.html

  • uint32_t ledcRead(uint8_t channel)
    返回指定通道占空比的值

  • double ledcReadFreq(uint8_t channel)
    返回指定通道当前频率(如果当前占空比为0 则该方法返回0)

  • void ledcAttachPin(uint8_t pin, uint8_t channel)
    将 LEDC 通道绑定到指定 IO 口上以实现输出

  • void ledcDetachPin(uint8_t pin)
    解除 IO 口的 LEDC 功能

使用示例

#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);
  }
}

总结

在 Arduino core for the ESP32 中并没有像 Arduino 中 用来输出 PWM 的 analogWrite(pin, value) 方法,而是用 LEDC(LED Control)来实现 PWM 功能