-
Notifications
You must be signed in to change notification settings - Fork 0
/
학교종이땡땡땡.ino
47 lines (42 loc) · 1.29 KB
/
학교종이땡땡땡.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 1 "D:\\projects\\arduino\\test\\test.ino"
const int speakerPin = 8; // 연결된 핀 번호
const int octave = 4; // 옥타브
const int noteDuration = 500; // 음표 길이 (단위: ms)
int Melody[100] =
{'G','G','A','A','G','G','E','G','G','E','E','D'};
void setup() {
pinMode(speakerPin, 0x1);
}
void loop() {
for(int i=0; i<100; i++)
{
playTone(Melody[i], octave, noteDuration); // C5 음표를 연주합니다.
}
}
void playTone(char note, int octave, int duration) {
double frequency = getFrequency(note, octave);
int period = 1000000 / frequency;
int pulseWidth = period / 2;
int numPeriods = duration * frequency / 1000;
for (int i = 0; i < numPeriods; i++) {
digitalWrite(speakerPin, 0x1);
delayMicroseconds(pulseWidth);
digitalWrite(speakerPin, 0x0);
delayMicroseconds(pulseWidth);
}
}
double getFrequency(char note, int octave) {
const double baseFrequency = 55.0;
int noteIndex = -10;
switch (note) {
case 'C': noteIndex = 0; break;
case 'D': noteIndex = 2; break;
case 'E': noteIndex = 4; break;
case 'F': noteIndex = 5; break;
case 'G': noteIndex = 7; break;
case 'A': noteIndex = 9; break;
case 'B': noteIndex = 11; break;
default: return 0;
}
return baseFrequency * pow(2.0, octave-1) * pow(2.0, noteIndex/12.0);
}