CLOSE

Service Design

Interaction Logic

Physical Computing

Main Portfolio

Arduino Lab - Sound

Changing the volume of sound using variables & creating different notes.


int speakerPin = 10;//the pin that buzzer is connected to

void setup()
{
    pinMode(speakerPin, OUTPUT);//set the output pin for the speaker
}

void loop()
{

    play('g', 2);       //ha
    play('g', 1);       //ppy
    play('a', 4);       //birth
    play('g', 4);       //day
    play('C', 4);       //to
    play('b', 4);       //you

    play(' ', 2);       //pause for 2 beats

    play('g', 2);       //ha
    play('g', 1);       //ppy
    play('a', 4);       //birth
    play('g', 4);       //day
    play('D', 4);       //to
    play('C', 4);       //you

    play(' ', 2);       //pause for 2 beats

    play('g', 2);       //ha
    play('g', 1);       //ppy
    play('G', 4);       //birth
    play('E', 4);       //day
    play('C', 4);       //dear
    play('b', 4);       //your
    play('a', 6);       //name

    play(' ', 2);       //pause for 2 beats

    play('F', 2);       //ha
    play('F', 1);       //ppy
    play('E', 4);       //birth
    play('C', 4);       //day
    play('D', 4);       //to
    play('C', 6);       //you

    while (true) {}     //get stuck in this loop forever so that the song only plays once
}


void play( char note, int beats)
{
    int numNotes = 14; 

    char notes[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C', 'D', 'E', 'F', 'G', 'A', 'B', ' '};
    int frequencies[] = {131, 147, 165, 175, 196, 220, 247, 262, 294, 330, 349, 392, 440, 494, 0};

    int currentFrequency = 0;    
    int beatLength = 150;

    for (int i = 0; i < numNotes; i++){
        if (notes[i] == note){
            currentFrequency = frequencies[i];
        }
    }
    tone(speakerPin, currentFrequency, beats * beatLength);
    delay(beats * beatLength); 
    delay(50);                 

}

/* CHART OF FREQUENCIES FOR NOTES IN C MAJOR
    Note      Frequency (Hz)
    c        131
    d        147
    e        165
    f        175
    g        196
    a        220
    b        247
    C        262
    D        294
    E        330
    F        349
    G        392
    A        440
    B        494
*/