ESP8266-Arduino编程实例-蜂鸣器驱动

蜂鸣器驱动

1、蜂鸣器介绍

蜂鸣器或蜂鸣器是一种音频信号装置, 可以是机械的、机电的或压电的(简称压电)。其主要功能是将信号从音频转换为声音。 一般通过直流电压供电,用于定时器、报警器、打印机、报警器、电脑等。根据不同的设计,它可以产生不同的声音,如闹钟、音乐、铃声和警笛。

蜂鸣器又分为有源蜂鸣器和无源蜂鸣器。

2、硬件准备

  • ESP8266 NodeMCU开发板一块
  • 蜂鸣器模块一个
  • 面板板一个
  • 杜邦线若干
  • 数据线一条

硬件接线如下:

在这里插入图片描述

3、软件准备

  • Arduino IDE或VSCode + PlatformIO

在前面的文章中,对如何搭建ESP8266开发环境做了详细的介绍,请参考:

ESP8266 NodeMCU的引脚介绍在前面的文章中做了详细的介绍,请参考:

4、代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
int buzzerPin=D5; // 蜂鸣器引脚
const int songLength = 18;
char notes[] = "cdfda ag cdfdg gf ";
int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};
int tempo = 150;


void setup()
{
pinMode(buzzerPin, OUTPUT);
}


void loop()
{
int i, duration;

for (i = 0; i < songLength; i++) // step through the song arrays
{
duration = beats[i] \* tempo; // length of note/rest in ms

if (notes[i] == ' ') // is this a rest?
{
delay(duration); // then pause for a moment
}
else // otherwise, play the note
{
tone(buzzerPin, frequency(notes[i]), duration);
delay(duration); // wait for tone to finish
}
delay(tempo/10); // brief pause between notes
}

while(true){}

}


int frequency(char note)
{

int i;
const int numNotes = 8; // number of notes we're storing
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};


for (i = 0; i < numNotes; i++) // Step through the notes
{
if (names[i] == note) // Is this the one?
{
return(frequencies[i]); // Yes! Return the frequency
}
}
return(0);
}

文章来源: https://iotsmart.blog.csdn.net/article/details/126398906