Monday, June 13, 2016

Piezo Buzzer: Code and Fritzing

On this Page:

  • Helpful Links
  • Example Code in Video
  • Fritzing Electrical Diagram
  • Harder but more Efficient code with For Loop


Copy and paste code into Arduino IDE

Note: if you want to play different pitches on multiple pins, you need to call noTone() on the pin playing before using tone() on the next pin





Helpful Links: 
-Arduino Code a Melody 
-Sparkfun Piezo Experiment Guide
-Arduino Tone() Info

Example Code in Video:

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

void loop() {
  tone(12, 261); //Middle C
  delay(1000);

  tone(12, 277); //C#
  delay(1000);

  tone(12, 294); //D
  delay(1000);

  tone(12, 311); //D#
  delay(1000);

  tone(12, 330); //E
  delay(1000);
 
  tone(12, 349); //F
  delay(1000);

  tone(12, 370); //F#
  delay(1000);

  tone(12, 392); //G
  delay(1000);

  tone(12, 415); //G#
  delay(1000);

  tone(12, 440); //A
  delay(1000);
  // put your main code here, to run repeatedly:

}


Fritzing Electrical Diagram:




















Harder but Efficient Code with For Loop:



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

void loop() {
  int notes[10]={261, 277, 294, 311, 330, 349, 370, 392, 415, 440};
  //            mid C  C#   D    D#   E    F    F#   G    G#   A

  for(int i = 0; i < 10; i++){
    tone(12, notes[i]); //accesses spots on the array.
    delay(1000);
  }


}



5 comments: