风筝
发表于: 2016-7-25 11:39:38 | 显示全部楼层

音调旋律(Play a Melody using the tone() function)

本示例展示了如何使用tone()命令来产生一些音符。它可以播放一些旋律,你以前可能听过。


所需硬件

-    Arduino或者Genuino开发板

-    蜂鸣器或扬声器

-    导线


电路连接方式

Tone_Fritzing.png

将扬声器的一端连接到数字8脚,另一端连接到地。


原理图

Tone_Schematic.png


代码

下面的程序使用了一个外部文件:pitches.h。该文件包含了所有典型音符的对应音调值。比如NOTE_C4代表中央C,NOTE_FS4代表F#,等等。这个音符表最初是由Brett Hagman编写的,基于 tone()函数的工作原理。每当你想要播放音符的时候,你会发现这个头文件会非常有用。

以下是主要的程序:

  1. /*
  2.   Melody

  3. Plays a melody

  4. circuit:
  5. * 8-ohm speaker on digital pin 8

  6. created 21 Jan 2010
  7. modified 30 Aug 2011
  8. by Tom Igoe

  9. This example code is in the public domain.

  10. http://www.arduino.cc/en/Tutorial/Tone

  11. */
  12. #include "pitches.h"

  13. // notes in the melody:
  14. int melody[] = {
  15.   NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
  16. };

  17. // note durations: 4 = quarter note, 8 = eighth note, etc.:
  18. int noteDurations[] = {
  19.   4, 8, 8, 4, 4, 4, 4, 4
  20. };

  21. void setup() {
  22.   // iterate over the notes of the melody:
  23.   for (int thisNote = 0; thisNote < 8; thisNote++) {

  24.     // to calculate the note duration, take one second
  25.     // divided by the note type.
  26.     //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  27.     int noteDuration = 1000 / noteDurations[thisNote];
  28.     tone(8, melody[thisNote], noteDuration);

  29.     // to distinguish the notes, set a minimum time between them.
  30.     // the note's duration + 30% seems to work well:
  31.     int pauseBetweenNotes = noteDuration * 1.30;
  32.     delay(pauseBetweenNotes);
  33.     // stop the tone playing:
  34.     noTone(8);
  35.   }
  36. }

  37. void loop() {
  38.   // no need to repeat the melody.
  39. }
复制代码
跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1482



手机版|

GMT+8, 2024-4-30 20:40 , Processed in 0.057860 second(s), 8 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

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