ohmymymy 发表于 2014-10-23 17:42:02

新手笔记 - 让Arduino也唱小苹果

今天看的示例是toneMelody
/*
Melody

Plays a melody

circuit:
* 8-ohm speaker on digital pin 8

created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

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

*/
#include "pitches.h"

// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};

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

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

    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000/noteDurations;
    tone(8, melody,noteDuration);

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

void loop() {
// no need to repeat the melody.
}首先看到的是#include "pitches.h" 并且这个文件会同时打开,
看一看先, 里面有#define NOTE_C5523, 结合tone函数定义,发现这里面其实是定义的音调的发声频率
而523正好是C大调的Do , 那么对于 1=C 的 Do,Re,Mi,Fa,Sol,La,Si, 分别对应 NOTE_C5, NOTE_D5,NOTE_E5,NOTE_F5,NOTE_G5,NOTE_A5,NOTE_B5
再往下 , 发现noteDuration是发声时长 , int noteDurations[] = { 4, 8, 8, 4,4,4,4,4 }; 第一个音调发是1000/4 ms, 这几个可以看做是 4分音符, 8分音符, 8分音符, 4分音符...
也就是说
int melody[] 定义了音调
int noteDurations[] 定义了节奏
楼主基本可以看懂简谱, 下面省去楼主扒谱的一个多小时,


#include "pitches.h"
// pin8 接限流电阻再接蜂鸣器
// reset 按一下唱一遍
int melody[] = {
NOTE_E6,NOTE_C6,NOTE_D6,NOTE_A5,
NOTE_E6,NOTE_D6,NOTE_C6,NOTE_D6,NOTE_A5,
NOTE_E6,NOTE_C6,NOTE_D6,NOTE_D6,
NOTE_G6,NOTE_E6,NOTE_B5,NOTE_C6,NOTE_C6,NOTE_B5,
NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_G5,
NOTE_A6,NOTE_G6,NOTE_E6,NOTE_E6,NOTE_D6,
NOTE_C6,NOTE_D6,NOTE_E6,NOTE_D6,NOTE_E6,NOTE_D6,NOTE_E6,NOTE_G6,
NOTE_G6,NOTE_G6,NOTE_G6,NOTE_G6,NOTE_G6,NOTE_G6,

NOTE_E6,NOTE_C6,NOTE_D6,NOTE_A5,
NOTE_E6,NOTE_D6,NOTE_C6,NOTE_D6,NOTE_A5,
NOTE_E6,NOTE_C6,NOTE_D6,NOTE_D6,NOTE_D6,
NOTE_G6,NOTE_E6,NOTE_B5,NOTE_C6,NOTE_C6,NOTE_B5,
NOTE_A5,NOTE_B5,NOTE_C6,NOTE_D6,NOTE_G5,
NOTE_A6,NOTE_G6,NOTE_E6,NOTE_E6,NOTE_D6,
NOTE_C6,NOTE_D6,NOTE_E6,NOTE_D6,NOTE_G5,
NOTE_A5,NOTE_A5,NOTE_C6,NOTE_A5 };

int noteDurations[] = {
4,4,4,4,
8,8,8,8,2,
4,4,4,4,
8,8,4,4,8,8,
4,8,8,4,4,
8,8,4,3,8,
4,8,8,8,8,8,16,16,
4,8,8,8,8,4,

4,4,4,4,
8,8,8,8,2,
4,4,4,8,8,
8,8,4,4,8,8,
4,8,8,4,4,
8,8,4,3,8,
4,8,8,4,4,
4,8,8,2 };

void setup() {
for (int thisNote = 0; thisNote < 82; thisNote++) {

    int noteDuration = 1000/noteDurations;
    tone(8, melody, noteDuration);

    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);

    noTone(8);
}
}

void loop() {
}



页: [1]
查看完整版本: 新手笔记 - 让Arduino也唱小苹果