Welcome, Guest. Please Login or Register
Arduino: Forum
06.09.2010 at 04:17:57


Pages: 1
Possible Melody.pde replacement? (Read 1394 times)
dcb
Senior Member
****
Offline



Posts: 421

Possible Melody.pde replacement?
05.12.2008 at 12:13:26
 
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 Smiley

Code:
/* 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);
  }
}
 


Back to top
 
 
View Profile   IP Logged
halley
God Member
*****
Offline

Whatduino

Posts: 1035
Connecticut, US
Re: Possible Melody.pde replacement?
Reply #1 - 09.12.2008 at 00:38:27
 
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.

http://en.wikipedia.org/wiki/Music_Macro_Language
Back to top
 
 
View Profile | WWW   IP Logged
dcb
Senior Member
****
Offline



Posts: 421

Re: Possible Melody.pde replacement?
Reply #2 - 09.12.2008 at 03:12:24
 
Yup, with a scheduler (to schedule the next note) and pwm generating the tones you could even have the equivalent of:  

play "MB"

Smiley
Back to top
 
« Last Edit: 09.12.2008 at 12:33:22 by dcb »  
View Profile   IP Logged
Pages: 1