Arduino 控制蜂鸣器播放《小星星》歌曲 – Arduino 实验室

您所在的位置:网站首页 天空的星星歌曲播放 Arduino 控制蜂鸣器播放《小星星》歌曲 – Arduino 实验室

Arduino 控制蜂鸣器播放《小星星》歌曲 – Arduino 实验室

2024-07-08 14:53| 来源: 网络整理| 查看: 265

Arduino 控制蜂鸣器播放《小星星》歌曲

2016年12月26日 Arduino 实验室 未分类 0

这里使用的是无源蜂鸣器。 直接上程序:Arduino 控制蜂鸣器播放《小星星》

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

将蜂鸣器输入接在Arduino9号数字IO上,输出接地,便可听到小星星播放曲了。

再献上一例程:通过模拟电位器模块控制蜂鸣器发声频率

void setup() {   Serial.begin(9600);  // 初始化串口通信 }   void loop() {   int sensorReading = analogRead(A0);// 从A0口读模拟传感器的值   Serial.println(sensorReading);//串口输出独到的传感器的值     int thisPitch = map(sensorReading, 400, 1000, 120, 1500); //输入的模拟值范围以一比例转换到适合值 (此为400—1000) // 音律范围为 (120 - 1500Hz)   tone(9, thisPitch, 10);// 播放音频  接arduino9号端口,thispitch为播放频率,10为维持时间   delay(1); }

打开串口可显示A0口独到的模拟值,同时旋转模拟电位器便可改变蜂鸣器发声平率。

你还可以: 查看系列教程中的其他文章 购买本教程所用到的 Arduino 套件

11,935 文章标题:Arduino 控制蜂鸣器播放《小星星》歌曲 - Arduino 实验室 固定链接:https://arduino.nxez.com/2016/12/26/arduino-control-buzzer-play-little-star-song.html arduinolevel3教程编程蜂鸣器音频


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3