(Created page with "Category:Arduino Tutorials 680px")
 
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
 
[[Category:Arduino Tutorials]]
 
[[Category:Arduino Tutorials]]
 
[[File:Arduino Interface buzzer.JPG|680px]]
 
[[File:Arduino Interface buzzer.JPG|680px]]
 +
====Code====
 +
<syntaxhighlight>
 +
/*
 +
Make some noise with buzzer
 +
 +
Plays a melody
 +
 +
circuit:
 +
*Buzzer on digital pin 8
 +
 +
*/
 +
#include "pitches.h"
 +
// notes in the melody:
 +
int melody[] = {
 +
  NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
 +
// note durations: 4 = quarter note, 8 = eighth note, etc.:
 +
int noteDurations[] = {
 +
  4, 8, 8, 4,4,4,4,4 };
 +
void setup() {
 +
  // iterate over the notes of the melody:
 +
  for (int thisNote = 0; thisNote < 8; thisNote++) {
 +
    // 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/noteDurations[thisNote];
 +
    tone(8, melody[thisNote],noteDuration);
 +
    // to distinguish the notes, set a minimum time between them.
 +
    // the note's duration + 30% seems to work well:
 +
    int pauseBetweenNotes = noteDuration * 1.30;
 +
    delay(pauseBetweenNotes);
 +
    // stop the tone playing:
 +
    noTone(8);
 +
  }
 +
}
 +
void loop() {
 +
  // no need to repeat the melody.
 +
}
 +
 +
 +
</syntaxhighlight>

Latest revision as of 16:42, 15 September 2014

Arduino Interface buzzer.JPG

Code

  1. /*
  2. Make some noise with buzzer
  3.  
  4. Plays a melody
  5.  
  6. circuit:
  7. *Buzzer on digital pin 8
  8.  
  9. */
  10. #include "pitches.h"
  11. // notes in the melody:
  12. int melody[] = {
  13. NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};
  14. // note durations: 4 = quarter note, 8 = eighth note, etc.:
  15. int noteDurations[] = {
  16. 4, 8, 8, 4,4,4,4,4 };
  17. void setup() {
  18. // iterate over the notes of the melody:
  19. for (int thisNote = 0; thisNote < 8; thisNote++) {
  20. // to calculate the note duration, take one second
  21. // divided by the note type.
  22. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  23. int noteDuration = 1000/noteDurations[thisNote];
  24. tone(8, melody[thisNote],noteDuration);
  25. // to distinguish the notes, set a minimum time between them.
  26. // the note's duration + 30% seems to work well:
  27. int pauseBetweenNotes = noteDuration * 1.30;
  28. delay(pauseBetweenNotes);
  29. // stop the tone playing:
  30. noTone(8);
  31. }
  32. }
  33. void loop() {
  34. // no need to repeat the melody.
  35. }