티스토리 뷰

OS/Arduino

Arduino - 버저, 피에조 스피커(Piezo Buzzer)

파란크리스마스 2017. 9. 16. 18:30
728x90

출처 : All I want to do is BEEP! to show that the program - Arduino Forum
버저, 피에조 스피커로 음악 연주 (슈퍼마리오 배경음악) | Hard Copy Arduino

Arduino - 버저, 피에조 스피커(Piezo Buzzer)

Spec.

전압 : 5V
직경 : 12mm
핀길이 : 6.5mm
높이 : 8.5mm

배선

BEEP음 출력 소스

#define SPKR 2 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

피에조 스피커로 음악 연주 (슈퍼마리오 배경음악)

출처 : 버저, 피에조 스피커로 음악 연주 (슈퍼마리오 배경음악) | Hard Copy Arduino

pitches.h(링크) 파일은 아두이노 사이트에서 받을 수 있습니다.

#include "pitches.h"
 
#define melodyPin 2
 
unsigned long prevPlayTime = 0;
unsigned long playDuration = 0;
int currentMelody = 0;
 
//Mario main theme melody
int melodySize = 55;
int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7, 0, NOTE_C7, NOTE_E7, 0, NOTE_G7, 0, 0,  0, NOTE_G6, 0, 0, 0, 
  NOTE_C7, 0, 0, NOTE_G6, 0, 0, NOTE_E6, 0, 0, NOTE_A6, 0, NOTE_B6, 0, NOTE_AS6, NOTE_A6, 0, 
  NOTE_G6, NOTE_E7, NOTE_G7, NOTE_A7, 0, NOTE_F7, NOTE_G7, 0, NOTE_E7, 0,NOTE_C7, NOTE_D7, NOTE_B6, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6, 0, 0, NOTE_E6, 0, 0, NOTE_A6, 0, NOTE_B6, 0, NOTE_AS6, NOTE_A6, 0, 
  NOTE_G6, NOTE_E7, NOTE_G7, NOTE_A7, 0, NOTE_F7, NOTE_G7, 0, NOTE_E7, 0,NOTE_C7, NOTE_D7, NOTE_B6, 0, 0
};

//Mario main them tempo
int tempo[] = {
  12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 
  12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 
  9, 9, 9, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  9, 9, 9, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
};

void sing() {
    if(millis() < prevPlayTime + playDuration) {
        // music is playing. do nothing
        return;
    }
    // stop the tone playing:
    noTone(8);
    
    if(currentMelody >= melodySize)
        currentMelody = 0;
    // 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/tempo[currentMelody];
 
    tone(melodyPin, melody[currentMelody], noteDuration);
    prevPlayTime = millis();
    playDuration = noteDuration * 1.30;
    
    currentMelody++;
}

void setup() {
  pinMode(melodyPin, OUTPUT);
}

void loop() {
  // play music
  sing();
}


댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/11   »
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
글 보관함