P Comp Week 4

This week we began experimenting with assigning tones to a speaker. We were also introduced to a pitches.h library designed by Brett Hagman. I used the examples on the Arduino site to help create this simple melody. I also added an if statement so instead of just initializing the song when the program starts, you can trigger it with the touch sensitive resistor in the loop function. Below I figured out a simple melody for the song Old Town Road by Lil Nas X.

After figuring out the melody I wanted, I input the notes into the Arduino IDE. The code is below.

https://create.arduino.cc/projecthub/wpolitan/p-comp-week-4-bb8fb4

#include "pitches.h"

// notes in the melody:
int melody[] = {
  NOTE_E4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_C4, NOTE_A3, NOTE_A3, NOTE_E4, NOTE_D4, NOTE_C4,0,NOTE_A3,NOTE_G3,NOTE_D4, NOTE_D4, NOTE_E4, NOTE_C4, NOTE_A3, NOTE_A3,
  
};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
  8, 8, 4, 4, 4, 8, 8, 8, 4,8,8,8,8,2,4,4,8,4,4
};
void setup() {
 Serial.begin(9600);

}

 
 void loop() {

   
   // get a sensor reading:
   int sensorReading = analogRead(A0);
   int frequency= map(sensorReading, 0, 1023, 100,880);
   if(sensorReading>600){
       // iterate over the notes of the melody:
  for (int thisNote = 0; thisNote < 19; 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(9, melody[thisNote], noteDuration);

    // 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);
    // stop the tone playing:
    noTone(9);
    
    Serial.println("pressed");
    }
   }
    else {
      Serial.println("not pressed");
      }
   


 }

Below is the final application in use.

Next week I hope to expand on the use of triggering different sounds and LED’s. Eventually I want to create musical applications and hardware, that can interface with the computer in a more intuitive way.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s