Possible Melody.pde replacement?

Inspired by the need for an annoying tune player here I thought I would add this embellishment that uses a piezo on pwm pin 10 (other piezo lead goes to ground) to generate the tones and adds attack and decay in the loop for a super cheesey trumpet effect. Enjoy :slight_smile:

/* PWM Melody via DCB*/

//pin 10 pwm sound with pitch and volume control
#define piezoPin 10 
#define minVol 1
#define maxVol 128 

void setup(){
  pinMode(piezoPin,OUTPUT);
  pinMode(9,OUTPUT);
  TCCR1A = (1 << COM1A1) | (1 << COM1B1 | 1 << WGM10);// sets timer control bits to PWM Phase and Frequency Correct mode
  TCCR1B = 0x12; // sets timer control bits to Prescaler N = 8
  analogWrite(piezoPin, 127); //something less than full volume
}

int length = 15; // the number of notes
char notes[] = "ccggaagffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 450;

void playNote(char note, int duration) {
  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', ' ' };
  int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 958, 30 };
  int d = duration;
  // play the tone corresponding to the note name
  for (int i = 0; i < 9; i++) {
    if (names[i] == note) {
      OCR1A=tones[i];
      
      //attack
      for(int x = minVol; x < maxVol;x*=2){ 
        analogWrite(piezoPin, note == ' '?minVol:x);
        delay(10);
        d-=10;
      }

      //decay
      int x = maxVol;      
      while(d >= 2){
        analogWrite(piezoPin, note == ' '?minVol:x);
        x-=1;
        if(x<minVol) x = minVol;
        delay(5);
        d-=5;
      }
      
      analogWrite(piezoPin, minVol);
      delay(2);
    }
  }
}


void loop() {
  for (int i = 0; i < length; i++) {
     playNote(notes[i], beats[i] * tempo);
  }
}

The old embedded BASIC languages of the first home computers used to have a common "PLAY" string language that is similar to this. One ASCII string could describe a whole song, with multi-octave support and rests and durations specified in the same string. After a bit of googling, I find "Music Macro Language" documented. Looks like you'd be well-served by such a function in Arduino-land.

Yup, with a scheduler (to schedule the next note) and pwm generating the tones you could even have the equivalent of:

play "MB"

:slight_smile: