找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 2657|回复: 0
打印 上一主题 下一主题
收起左侧

关于自制的音乐播放器的一个小实验

[复制链接]
跳转到指定楼层
楼主
本实验用到的是无源蜂鸣器传感器模块(Arduino拓展板盾板以及杜邦线每个实验都要用,所以不再重复说明)。
如下图所示,我们将蜂鸣器模块的GND、VCC、以及IO口与Arduino拓展盾板的GND.+5V以及串口6相连接。

                              
然后接上USB连接线,导入程序。
  1. int speakerPin = 9;

  2. int length = 15; // the number of notes
  3. char notes[] = "ccggaagffeeddc "; // a space represents a rest
  4. int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
  5. int tempo = 300;

  6. void playTone(int tone, int duration) {
  7.   for (long i = 0; i < duration * 1000L; i += tone * 2) {
  8.     digitalWrite(speakerPin, HIGH);
  9.     delayMicroseconds(tone);
  10.     digitalWrite(speakerPin, LOW);
  11.     delayMicroseconds(tone);
  12.   }
  13. }

  14. void playNote(char note, int duration) {
  15.   char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  16.   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

  17.   // play the tone corresponding to the note name
  18.   for (int i = 0; i < 8; i++) {
  19.     if (names[i] == note) {
  20.       playTone(tones[i], duration);
  21.     }
  22.   }
  23. }

  24. void setup() {
  25.   pinMode(speakerPin, OUTPUT);
  26. }

  27. void loop() {
  28.   for (int i = 0; i < length; i++) {
  29.     if (notes[i] == ' ') {
  30.       delay(beats[i] * tempo); // rest
  31.     } else {
  32.       playNote(notes[i], beats[i] * tempo);
  33.     }

  34.     // pause between notes
  35.     delay(tempo / 2);
  36.   }
  37. }
复制代码

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享淘帖 顶 踩
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表