Tuesday, May 12, 2015

Playing notes with buzzer

If you turn the voltage on and off hundreds of times a second, the piezo buzzer will produce a tone. And if you string a bunch of tones together, you’ve got music! Here in this improvement, we gave the beats, and notes. We have 2 push buttons in our code. By using the push buttons, we change the frequency of our music.
Berrak Şişman İlker Çam


const int btnPin1 = 3;
const int btnPin2 = 2;
const int potansPin = 0;
const int buzzerPin = 9;

const int songLength = 18;

char notes[] = "cdfda ag cdfdg gf "; // a space represents a rest

int beats[] = {1,1,1,1,1,1,4,4,2,1,1,1,1,1,1,4,4,2};

int tempo = 150;

char btnNotes[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
int note = 0;

void setup()
{
  pinMode(buzzerPin, OUTPUT);
  pinMode(btnPin1,INPUT);
  pinMode(btnPin2,INPUT);
  pinMode(potansPin,INPUT);
  Serial.begin(9600);
}


void loop()
{
  //Serial.write("readValues ex\n");
  int btnState1 = 0,btnState2 = 0, potansValue = 0;
  btnState1 = digitalRead(btnPin1);
  btnState2 = digitalRead(btnPin2);
  potansValue = analogRead(potansPin);

  if(btnState1 == LOW && btnState2 == HIGH){
    tone(buzzerPin, frequency(btnNotes[note++]), 1000);
    note%=8;
    Serial.write("Playing Note\n");
    delay(50);
  }else if(btnState2 == LOW && btnState1 == HIGH){
    tempo = map(potansValue, 0, 1023, 100, 200);
    Serial.println(potansValue);
    playSong();
  }
  delay(100);

}

void playSong(){
 

  int i, duration;

  for (i = 0; i < songLength; i++) // step through the song arrays
  {

    duration = beats[i] * tempo;  // length of note/rest in ms
    if (notes[i] == ' ')          // is this a rest?
    {
      delay(duration);            // then pause for a moment
    }
    else                          // otherwise, play the note
    {
      tone(buzzerPin, frequency(notes[i]), duration);
      delay(duration);            // wait for tone to finish
    }
    delay(tempo/10);              // brief pause between notes
  }
}

int frequency(char note)
{
  // This function takes a note character (a-g), and returns the
  // corresponding frequency in Hz for the tone() function.

  int i;
  const int numNotes = 8;  // number of notes we're storing



  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int frequencies[] = {262, 294, 330, 349, 392, 440, 494, 523};

  // Now we'll search through the letters in the array, and if
  // we find it, we'll return the frequency for that note.

  for (i = 0; i < numNotes; i++)  // Step through the notes
  {
    if (names[i] == note)         // Is this the one?
    {
      return(frequencies[i]);     // Yes! Return the frequency
    }
  }
  return(0);
}

No comments:

Post a Comment