蜂鳴器是一種一體化結構的電子訊響器,采用直流電壓供電,廣泛應用于計算電子玩具、定時器等電子產品中作發聲器件。蜂鳴器分有源和無源。如果是有源的,單片機只要輸出高低電平就可以,如果是無源的,單片機就要輸出PWM波才可以讓蜂鳴器發聲。
5V有源蜂鳴器,Arduinouno,杜邦線
正極連 ArduinoDigital 4負極連 Arduino GND

int PIN_SPEAKER = 4;int length = 25;char notes[] = "ggagCbggagDCggGECbaffECDC";int beats[] = {1,1,2,2,2,4, 1,1,2,2,2,4, 1,1,2,2,2,2,2, 1,1,2,2,2,4,1};int tempo = 300; void playTone(int tone, int duration) { for (long i = 0; i < duration * 1000L; i += tone * 2) { digitalWrite(PIN_SPEAKER, HIGH); delayMicroseconds(tone); digitalWrite(PIN_SPEAKER, LOW); delayMicroseconds(tone); }} void playNote(char note, int duration) { char names[] = {'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G'}; int tones[] = {1915, 1700, 1519, 1432, 1275, 1136, 1014, 956, 853, 759, 716, 637, 568}; for (int i = 0; i < 12; i++) { if (names[i] == note) { Serial.PRint("value:"); Serial.println(note); playTone(tones[i]*2, duration); } }} void setup() { pinMode(PIN_SPEAKER, OUTPUT);} void loop() { for (int i = 0; i < length; i++) { if (notes[i] == ' ') { delay(beats[i] * tempo); } else { playNote(notes[i], beats[i] * tempo); } delay(tempo / 2); }}(請注意:因各廠商硬件不同,引腳位置可能有差異,具體請見硬件說明書)
新聞熱點
疑難解答