1 电路连接

蜂鸣器

ESP32

正极

D33

负极

GND

2 实物连接图

esp32频谱灯制作教程(ESP32实例七)(1)

3 程序如下,编译器visual studio code main. Cpp

#include <Arduino.h> #define buz 33 typedef struct data { note_t note;//音符 uint8_t level;//音阶 uint16_t interval;// 节拍 } note; note tones[]={ {NOTE_C,4,500},// NOTE_C 是1 {NOTE_C,4,500}, {NOTE_G,4,500}, {NOTE_G,4,500}, {NOTE_A,4,500}, {NOTE_A,4,500}, {NOTE_G,4,1000}, {NOTE_F,4,500}, {NOTE_F,4,500}, {NOTE_E,4,500}, {NOTE_E,4,500}, {NOTE_D,4,500}, {NOTE_D,4,500}, {NOTE_C,4,1000} }; byte toneSize=sizeof(tones)/sizeof(note); void setup() { // put your setup code here, to run once: ledcSetup(0,20000,10);// initialize pwm port,0 port, total 16 port ledcAttachPin(buz,0); } void loop() { // put your main code here, to run repeatedly: for(int i=0;i<toneSize;i ){ ledcWriteNote(0,tones[i].note,tones[i].level); delay(tones[i].interval); } }

4 效果确认

ESP32使用蜂鸣器播放小星星歌曲 - 西瓜视频 (ixigua.com)

,