Lesson 20: Melody player
Trang này cần trình duyệt gần đây (hỗ trợ SharedArrayBuffer). Vui lòng cập nhật Chrome, Edge, Firefox hoặc Safari lên phiên bản mới nhất.
English
A song in a list
- A song is a list of notes. Each note has a pitch (how high) and a length (how long).
- An array keeps a list of numbers under one name, so a
forloop can play them one after another. - With two arrays, one for pitch and one for length, the Arduino can play any tune.
Words for this lesson
| Word | Meaning |
|---|---|
| melody | a tune: notes one after another |
| pitch | how high or low a note is, in Hz |
| array | a list of values with one name, like notes |
| index | the position in an array; the first one is 0 |
| scale | notes going up step by step: C D E F G … |
English
Notes and their numbers
| Note | C | D | E | F | G | A |
|---|---|---|---|---|---|---|
| Hz | 262 | 294 | 330 | 349 | 392 | 440 |
- A higher number is a higher note. A is 440 Hz: musicians tune their instruments to it.
English
Reading an array
| i | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
notes[i] |
262 | 294 | 330 | 349 | 392 |
int notes[] = {262, 294, 330, 349, 392};makes the array. The computer counts the 5 values for you.for (int i = 0; i < 5; i++)gives i = 0, 1, 2, 3, 4: one index for each value. There is nonotes[5].
int notes[] = {262, 294, 330};
void setup() {
Serial.begin(9600);
for (int i = 0; i < 3; i++) {
Serial.print("notes[");
Serial.print(i);
Serial.print("] = ");
Serial.println(notes[i]);
}
}
void loop() {
}
- The Serial Monitor shows
notes[0] = 262,notes[1] = 294andnotes[2] = 330.
English
How long is the tune?
- Each note takes its length plus 50 ms of quiet. Six notes of 400 ms and one of 800 ms: 6 × 450 + 850 = 3550 ms, about 3.5 s.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
The array notes keeps five notes of a scale. The for loop goes through them, but it plays the first note five times. Use i to play each note once: notes[i]. Every note sounds for 300 ms, then 100 ms of quiet.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Play the start of "Twinkle, Twinkle, Little Star": C C G G A A G. The last note is long. Make a second array lengths with the time of each note in ms: 400 for the first six notes and 800 for the last. Then use lengths[i] in the delay. After each note keep 50 ms of quiet.
Nhấn Chạy để xem kết quả ở đây.