(Created page with "Category:Arduino Tutorials 680px")
 
Line 1: Line 1:
 
[[Category:Arduino Tutorials]]
 
[[Category:Arduino Tutorials]]
 
[[File:Arduino Interface buzzer.JPG|680px]]
 
[[File:Arduino Interface buzzer.JPG|680px]]
 +
====Code====
 +
<syntaxhighlight>
 +
/*
 +
  Melody
 +
 +
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>

Revision as of 00:00, 13 September 2014

Arduino Interface buzzer.JPG

Code

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