arduino 有源 蜂鸣器_Arduino教程——蜂鸣器发声

本文档是一篇关于如何使用Arduino控制有源蜂鸣器播放音乐的教程。通过定义不同音符和节拍,实现简单旋律的播放。在`setup()`函数中配置蜂鸣器引脚为输出,在`loop()`函数中遍历音符并调用`playNote()`和`playTone()`函数来播放音乐。
摘要由CSDN通过智能技术生成

int speakerPin = 9;

int length = 15; // the number of notes

char notes[] = "ccggaagffeeddc "; // a space represents a rest

int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };

int tempo = 300;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

digitalWrite(speakerPin, HIGH);

delayMicroseconds(tone);

digitalWrite(speakerPin, LOW);

delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

// play the tone corresponding to the note name

for (int i = 0; i < 8; i++) {

if (names[i] == note) {

playTone(tones[i], duration);

}

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

if (notes[i] == ' ') {

delay(beats[i] * tempo); // rest

} else {

playNote(notes[i], beats[i] * tempo);

}

// pause between notes

delay(tempo / 2);

}

}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值