ccarman602

Piezo Speaker Twinkle Twinkle Little Star

Jun 3rd, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Lightly modified to simplify the code! */
  2.  
  3. /*
  4. Connections For this application;
  5. Use Freeduino-RichBoard made by www.EmbeddedMarket.com
  6. 1. Connect Digital Pin 9 to Buz pin in Section 9 on Freeduino Board
  7. 2. Connect USB Cable
  8. */
  9.  
  10.  
  11. /* Melody
  12.  * (cleft) 2005 D. Cuartielles for K3
  13.  *
  14.  * This example uses a piezo speaker to play melodies.  It sends
  15.  * a square wave of the appropriate frequency to the piezo, generating
  16.  * the corresponding tone.
  17.  *
  18.  * The calculation of the tones is made following the mathematical
  19.  * operation:
  20.  *
  21.  *       timeHigh = period / 2 = 1 / (2 * toneFrequency)
  22.  *
  23.  * where the different tones are described as in the table:
  24.  *
  25.  * note   frequency   period  timeHigh
  26.  * c          261 Hz          3830  1915  
  27.  * d          294 Hz          3400  1700  
  28.  * e          329 Hz          3038  1519  
  29.  * f          349 Hz          2864  1432  
  30.  * g          392 Hz          2550  1275  
  31.  * a          440 Hz          2272  1136  
  32.  * b          493 Hz          2028  1014  
  33.  * C          523 Hz          1912  956
  34.  *
  35.  * http://www.arduino.cc/en/Tutorial/Melody
  36.  */
  37.  
  38. int speakerPin = 3;
  39.  
  40. int length = 48; // the number of notes
  41.  
  42. //twinkle twinkle little star
  43. char notes[] = "ccggaag ffeeddc ggffeed ggffeed ccggaag ffeeddc "; // a space represents a rest
  44. int tempo = 300;
  45.  
  46. void playTone(int tone, int duration) {
  47.   for (long i = 0; i < duration * 1000L; i += tone * 2) {
  48.     digitalWrite(speakerPin, HIGH);
  49.     delayMicroseconds(tone);
  50.     digitalWrite(speakerPin, LOW);
  51.     delayMicroseconds(tone);
  52.   }
  53. }
  54.  
  55. void playNote(char note, int duration) {
  56.   char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  57.   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
  58.  
  59.   // play the tone corresponding to the note name
  60.   for (int i = 0; i < 8; i++) {
  61.     if (names[i] == note) {
  62.       playTone(tones[i], duration);
  63.     }
  64.   }
  65. }
  66.  
  67. void setup() {
  68.   pinMode(speakerPin, OUTPUT);
  69. }
  70.  
  71. void loop() {
  72.   for (int i = 0; i < length; i++) {
  73.     if (notes[i] == ' ') {
  74.       delay(tempo); // rest
  75.     } else {
  76.       playNote(notes[i], tempo);
  77.     }
  78.    
  79.     // pause between notes
  80.     delay(tempo / 2);
  81.   }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment