KRITSADA

Play Note on Mbit pin26

Jan 11th, 2022
1,473
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int speakerPin = 26;
  2. int length = 15; // the number of notes
  3. char notes[] = "ccggaagffeeddc "; // a space represents a rest
  4. int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
  5. int tempo = 300;
  6.  
  7. void playTone(int tone, int duration) {
  8.   for (long i = 0; i < duration * 1000L; i += tone * 2) {
  9.     digitalWrite(speakerPin, HIGH);
  10.     delayMicroseconds(tone);
  11.     digitalWrite(speakerPin, LOW);
  12.     delayMicroseconds(tone);
  13.   }
  14. }
  15.  
  16. void playNote(char note, int duration) {
  17.   char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  18.   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
  19.  
  20.   // play the tone corresponding to the note name
  21.   for (int i = 0; i < 8; i++) {
  22.     if (names[i] == note) {
  23.       playTone(tones[i], duration);
  24.     }
  25.   }
  26. }
  27.  
  28. void setup() {
  29.   pinMode(speakerPin, OUTPUT);
  30. }
  31.  
  32. void loop() {
  33.   for (int i = 0; i < length; i++) {
  34.     if (notes[i] == ' ') {
  35.       delay(beats[i] * tempo); // rest
  36.     } else {
  37.       playNote(notes[i], beats[i] * tempo);
  38.     }
  39.  
  40.     // pause between notes
  41.     delay(tempo / 2);  
  42.   }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment