1. 自動撥音樂(整首小蜜蜂)
int speakerPin = 9;
int length = 24; // the number of notes
char notes[] = "geefddcdefggggeefddceggc "; // a space represents a rest
int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1,
2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4};
int tempo = 300;
void playTone(int tone, int duration) {
for (long i = 0; i < duration * 1000L; i += tone * 2) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(tone);
digitalWrite(speakerPin, LOW);
delayMicroseconds(tone);
}
}
void playNote(char note, int duration) {
char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
// play the tone corresponding to the note name
for (int i = 0; i < 8; i++) {
if (names[i] == note) {
playTone(tones[i], duration);
}
}
}
void setup() {
pinMode(speakerPin, OUTPUT);
}
void loop() {
for (int i = 0; i < length; i++) {
if (notes[i] == ' ') {
delay(beats[i] * tempo); // rest
} else {
playNote(notes[i], beats[i] * tempo);
}
// pause between notes
delay(tempo / 2);
}
}
2.可用按鍵彈音階
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;
const int buttonPin4 = 5;
const int buttonPin5 = 6;
int speakerPin = 9;
int buttonState1 = 0; // variable for reading the pushbutton status
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
int buttonState5 = 0;
void setup() {
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
}
void loop() {
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);
buttonState3 = digitalRead(buttonPin3);
buttonState4 = digitalRead(buttonPin4);
buttonState5 = digitalRead(buttonPin5);
int duration;
if (buttonState1 == HIGH) tone(speakerPin, 261,duration); //tone(pin, frequency, duration)
else if (buttonState2 == HIGH) tone(speakerPin, 294,duration);
else if (buttonState3 == HIGH) tone(speakerPin, 329,duration);
else if (buttonState4 == HIGH) tone(speakerPin, 349,duration);
else if (buttonState5 == HIGH) tone(speakerPin, 392,duration);
else {
noTone(speakerPin);
}
}
3.心得
這節課教我們用 Arduino 撥放音樂,還有搭配按鈕彈音階, 讓我想到可以做鋼琴的小遊戲。
而且他的程式碼跟原裡沒有很難,董元李後就可以延伸很多不同的曲子。
可惜這節課當時沒有借到手機或相機,沒有把接出來的執行樣子拍攝下來,
有機會再用得獎的Arduino 再接一次~
沒有留言:
張貼留言