(arduino框架)ESP32学习笔记1: 如何输出可调频率和占空比的pwm波
(1)esp32使用pwm波的函数在esp32-hal-ledc.h文件当中定义,其中共有16个通道可配置
//channel 0-15 resolution 1-16bits freq limits depend on resolution
//初始化设置通道频率和分辨率
double ledcSetup(uint8_t channel, double freq, uint8_t resolution_bits);
//设置通道的占空比
void ledcWrite(uint8_t channel, uint32_t duty);
//设置通道的频率
double ledcWriteTone(uint8_t channel, double freq);
//输出需要的音阶
double ledcWriteNote(uint8_t channel, note_t note, uint8_t octave);
//读取某个通道的占空比
uint32_t ledcRead(uint8_t channel);
//读取通道的频率
double ledcReadFreq(uint8_t channel);
//将通道和引脚绑定
void ledcAttachPin(uint8_t pin, uint8_t channel);
//解绑通道和引脚的关系
void ledcDetachPin(uint8_t pin);
(2)其中ledcWriteNote函数为输出一些音阶,可以接上蜂鸣器发出一些简单的音频, 函数如下:
double ledcWriteNote(uint8_t chan, note_t note, uint8_t octave){
const uint16_t noteFrequencyBase[12] = {
// C C# D Eb E F F# G G# A Bb B
4186, 4435, 4699, 4978, 5274, 5588, 5920, 6272, 6645, 7040, 7459, 7902
};
if(octave > 8 || note >= NOTE_MAX){
return 0;
}
double noteFreq = (double)noteFrequencyBase[note] / (double)(1 << (8-octave));
return ledcWriteTone(chan, noteFreq);
}
(3)代码:在Arduino环境下用esp32输出pwm波(基于platform io)
所用开发板是安信可的NodeMCU-32S核心开发板
代码:
#include <Arduino.h>
#define LED 2
#define LED_OFF digitalWrite(LED,High) //关灯
#define LED_ON digitalWrite(LED, LOW) //开灯
int freq = 2000; //设置PWM波的频率
int channel = 0; //设置通道,共16个通道,0~15
int resolution = 10; //分辨率,取值0~20 duty的最大值为 2^resolution-1
bool val = 0;
void setup() {
// put your setup code here, to run once:
ledcSetup(channel,freq,resolution); //设置通道0
ledcAttachPin(LED,channel); //将通道0和gpio_pin连接起来
}
void loop() {
// put your main code here, to run repeatedly:
// led逐渐变暗
for (int i = 0; i < 1023; i=i+5)
{
ledcWrite(channel,i);
delay(5);
}
// led逐渐变亮
for (int i = 1023; i >= 0 ; i=i-5)
{
ledcWrite(channel,i);
delay(5);
}
}