(Reference) Speakers / Piezo Buzzers

Speakers / Piezo Buzzers

Piezo Buzzer

Buzzer

Wiring

1570925594505

Wiring: Polarity

  • The buzzer will have a + on the bottom or side
  • + goes to Argon pin capable of PWM
  • - goes to Ground

buzzer polarity buzzer polarity

Operation

  • Uses PWM to generate square waves tones up to about 2 KHz

Code: tone()

  • The tone() function produces tones from the buzzer

Syntax

tone(<<PIN>>, <<FREQUENCY>>, <<DURATION>>);
  • tone() generates a square wave using PWM (50% duty cycle)

  • pin is connected the speaker

  • frequency is sound frequency in Hz (20Hz to 20KHz)

  • duration is the length of tone in milliseconds

Code

Example

const int PIN_SPEAKER = D2;

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

void loop() {
  tone(PIN_SPEAKER, 500, 1500);	// play 500Hz tone for 1000ms (1 sec)
  // delay(1500);       // it may be necessary to add equal length delay
}

Optional: Controlling Volume

  • It is possible to add a potentiometer which can be used to control the volume of the buzzer. See full class notes on buzzers for more information
  • tone() requires a pin that supports PWM

Optional: Playing Melodies

Musical Notes

  • Musical notes can represented as constants
  • Add this file (pitches.h) to your src folder and then add #include "pitches.h" to your sketch

  • You can then refer to music notes with constants like NOTE_C4 which is “middle C” on a piano

Musical Note Lengths

  • Tone lengths can be represented as musical beats
  • Using an array for notes and an array for lengths, you can then create melodies with similar to using musical notation
  • You can include can include the musical note

Code

#include "pitches.h"	// you need to download this file to your SRC folder

const int PIN_SPEAKER = D2;

// notes in the melody:
int melody[] = {NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3,
                 NOTE_G3, 0,       NOTE_B3, NOTE_C4};

// note lengths: 4 = quarter note, 8 = eighth note, etc.:
int noteLengths[] = {4, 8, 8, 4, 4, 4, 4, 4};

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

void loop() {
  for (int currentNote = 0; currentNote < 8; currentNote++) {
    // 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 currentNoteLength = 1000 / noteLengths[currentNote];
    tone(PIN_SPEAKER, melody[currentNote], currentNoteLength);

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = currentNoteLength * 1.30;
    delay(pauseBetweenNotes);
  }
}

References

Updated: