Advertisement
iyera20

Piezo Melody

Jun 22nd, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. /*
  2. Melody
  3.  
  4. Plays a melody
  5.  
  6. circuit:
  7. * 8-ohm speaker on digital pin 8
  8.  
  9. created 21 Jan 2010
  10. modified 30 Aug 2011
  11. by Tom Igoe
  12.  
  13. This example code is in the public domain.
  14.  
  15. http://www.arduino.cc/en/Tutorial/Tone
  16.  
  17. */
  18. #include "pitches.h"
  19.  
  20. // notes in the melody:
  21. int melody[] = {
  22. NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
  23. };
  24.  
  25. // note durations: 4 = quarter note, 8 = eighth note, etc.:
  26. int noteDurations[] = {
  27. 4, 8, 8, 4, 4, 4, 4, 4
  28. };
  29.  
  30. const int photoPin= A0;
  31. const int piezoPin= 8;
  32.  
  33. void setup() {
  34. // iterate over the notes of the melody:
  35. for (int thisNote = 0; thisNote < 8; thisNote++) {
  36.  
  37. // to calculate the note duration, take one second
  38. // divided by the note type.
  39. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  40. int noteDuration = 1000 / noteDurations[thisNote];
  41. tone(piezoPin, melody[thisNote], noteDuration);
  42.  
  43. // to distinguish the notes, set a minimum time between them.
  44. // the note's duration + 30% seems to work well:
  45. int pauseBetweenNotes = noteDuration * 1.30;
  46. delay(pauseBetweenNotes);
  47. // stop the tone playing:
  48. noTone(piezoPin);
  49. }
  50. }
  51.  
  52. void loop() {
  53. // no need to repeat the melody.
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement