Saturday, November 21, 2015

Playing with my new Arduino.
I was feeling creative listening to music so I decided to make some sounds.
I went with the song secrets by one republic, a bit inspired by the movie The Sorcerer's Apprentice.

Anyway... This is the result and code:




Code:


#include <pitches.h>

int melody[] = {
  NOTE_D3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_D3, NOTE_FS3, NOTE_D3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_D3, NOTE_FS3, 
  NOTE_CS3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_CS3, NOTE_FS3, NOTE_CS3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_A3, NOTE_FS3, NOTE_CS3, NOTE_FS3, 
  NOTE_B2, NOTE_FS3, NOTE_B3, NOTE_FS3, NOTE_B3, NOTE_FS3, NOTE_B2, NOTE_FS3, NOTE_B2, NOTE_FS3, NOTE_B3, NOTE_FS3, NOTE_B3, NOTE_FS3, NOTE_B2, NOTE_FS3, 
  NOTE_B2, NOTE_G3, NOTE_B3, NOTE_G3, NOTE_B3, NOTE_G3, NOTE_B2, NOTE_G3, NOTE_B2, NOTE_G3, NOTE_B3, NOTE_G3, NOTE_B3, NOTE_G3, NOTE_B2, NOTE_G3, 
};

int noteDurations[] = {
  5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
  5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
  5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
  5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 
};

int leds[] = {
  3, 4, 5, 4, 5, 4, 3, 4, 3, 4, 5, 4, 5, 4, 3, 4,
  3, 4, 5, 4, 5, 4, 3, 4, 3, 4, 5, 4, 5, 4, 3, 4,
  3, 4, 5, 4, 5, 4, 3, 4, 3, 4, 5, 4, 5, 4, 3, 4,
  3, 4, 5, 4, 5, 4, 3, 4, 3, 4, 5, 4, 5, 4, 3, 4,
};

int buttonState = 0;

void setup(){
  Serial.begin(9600); 
  pinMode(2, INPUT);
  pinMode(13, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  
}

void play(){
  for (int thisNote = 0; thisNote < 64; thisNote++) {

    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(13, melody[thisNote], noteDuration);

    digitalWrite(leds[thisNote], HIGH);

    Serial.print(melody[thisNote]);
    Serial.println();

    // to distinguish the notes, set a minimum time between them.
    // the note's duration + 30% seems to work well:
    int pauseBetweenNotes = noteDuration * 1.30;
    delay(pauseBetweenNotes);
    digitalWrite(leds[thisNote], LOW);
    // stop the tone playing:
    noTone(13);
  }
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(2);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    Serial.print(buttonState);
    play();
  } else {
    noTone(13);
  }
}


Hope you enjoy :)




No comments:

Post a Comment