Assignment 7: Musical Instrument

This post is a mirror to the following post: Link

Concept: 

To be frank, we both didn’t really have a mind-blowing, creative inspiration when we got started on this project, which is why we decided to create something that’s simple but also making sure that it will leave enough room for user to be creative with it on our behalf. The idea that we had was to create an instrument that is able to be controlled by the user, such as its beats, pitch, etc., and it consisted of one digital sensor (switch), one analog sensor (potentiometer), and a Piezo speaker, along with the according wires that were needed. Here’s the picture of our initial state that we began with, along with the schematic:

Process/Coding:

While building the circuit itself was fairly easy and efficient since it was just a matter of connecting the wires into the respective places, the coding process was a little bit more complicated as we ran into a few obstacles:

  • Initially, the turn-off function of the switch wasn’t working — this was because of the delay time, so we realized that we had to press on the switch for a while instead of just pressing lightly.
  • We also had to adjust the tone range of our “instrument” — initially it was around 5000, but we later made it to 2000 so that it doesn’t hurt our ears as much even when we turn it up to the maximum tone.
  • Sometimes, the instrument won’t turn off at all even when we pressed down on the switch with enough strength and time; this was due to a small error in the code.

But after a few trials and errors, we were able to fulfill our initial vision for our instrument by controlling both the beat and the pitch either simultaneously or separately.

There was one aspect of the code that was still slightly flawed when we went back to review it, but the final product seemed to work fine despite it so we kept it, which is shown here:

// the loop routine runs over and over again forever:
void loop() {
// read values from potentiometer
int sensorValue = analogRead(potentiometer)/5*5; // <- to mitigate unintended frequency change caused by the sensor
delay(1); // delay in between reads for stability
frequency = map(sensorValue,0,1024,0,2000); // limit frequency range to avoid unpleasant sound
manageOutputPattern(); // determines which sound mode will be played
if (!!outputPattern) { // if outputPattern is 0, idle(). Else make sound.
makeSound();
} else {
idle();
}
// was supposed to do something similar to x 1.3 delay in “ToneMelody” example
// But this is flawed as noteDuration is less than (1300-1000) when BPS is >2.
// However, the product seems to work fine so will not correct this issue.
counter = (counter + 1) % 1300;

To see the entire code, click here.

Final Product: 

Here’s what the final product looked like:

Here’s a brief instruction on how to use the instrument:

  1. When you press on the switch button, the Piezo buzzer will start making sounds.
  2. You can use the potentiometer to control the pitch/tone of the sound and you can use the switch button to control the beat length of each sound. Mind the fact that each time you press on the switch button, the beats will get faster and faster. There will be 5 different beat speed offered.
  3. By pressing the switch button for the 6th time, you will be able to turn off the instrument completely.

…and here’s the video of it running:

Reflection:

Despite some minor hiccups that we’ve faced during the making process, this project was actually pretty manageable and simpler than we thought it’d be! It was exciting to hear how the sound changed as we adjusted the potentiometer/pressed the switch button to create a melody. Potentially creating a song or playing an already existing one by using this instrument that we made will be really fun, and we’re proud of the final product that we ended up with!

Assignment #7: Create Your Own Instrument!

 

Concept: 

To be frank, we both didn’t really have a mind-blowing, creative inspiration when we got started on this project, which is why we decided to create something that’s simple but also making sure that it will leave enough room for user to be creative with it on our behalf. The idea that we had was to create an instrument that is able to be controlled by the user, such as its beats, pitch, etc., and it consisted of one digital sensor (switch), one analog sensor (potentiometer), and a Piezo speaker, along with the according wires that were needed. Here’s the picture of our initial state that we began with, along with the schematic:

Process/Coding:

While building the circuit itself was fairly easy and efficient since it was just a matter of connecting the wires into the respective places, the coding process was a little bit more complicated as we ran into a few obstacles:

  • Initially, the turn-off function of the switch wasn’t working — this was because of the delay time, so we realized that we had to press on the switch for a while instead of just pressing lightly.
  • We also had to adjust the tone range of our “instrument” — initially it was around 5000, but we later made it to 2000 so that it doesn’t hurt our ears as much even when we turn it up to the maximum tone.
  • Sometimes, the instrument won’t turn off at all even when we pressed down on the switch with enough strength and time; this was due to a small error in the code.

But after a few trials and errors, we were able to fulfill our initial vision for our instrument by controlling both the beat and the pitch either simultaneously or separately.

There was one aspect of the code that was still slightly flawed when we went back to review it, but the final product seemed to work fine despite it so we kept it, which is shown here:

// the loop routine runs over and over again forever:
void loop() {
  // read values from potentiometer
  int sensorValue = analogRead(potentiometer)/5*5;  // <- to mitigate unintended frequency change caused by the sensor 
  delay(1);  // delay in between reads for stability
  frequency = map(sensorValue,0,1024,0,2000); // limit frequency range to avoid unpleasant sound

  manageOutputPattern(); // determines which sound mode will be played

  if (!!outputPattern) { // if outputPattern is 0, idle(). Else make sound.
    makeSound();
  } else {
    idle();
  }

  // was supposed to do something similar to x 1.3 delay in "ToneMelody" example
  // But this is flawed as noteDuration is less than (1300-1000) when BPS is >2. 
  // However, the product seems to work fine so will not correct this issue.
  counter = (counter + 1) % 1300;

To see the entire code, click here.
Final Product: 

Here’s what the final product looked like:

Here’s a brief instruction on how to use the instrument:

  1. When you press on the switch button, the Piezo buzzer will start making sounds.
  2. You can use the potentiometer to control the pitch/tone of the sound and you can use the switch button to control the beat length of each sound. Mind the fact that each time you press on the switch button, the beats will get faster and faster. There will be 5 different beat speed offered.
  3. By pressing the switch button for the 6th time, you will be able to turn off the instrument completely.

…and here’s the video of it running:

Reflection:

Despite some minor hiccups that we’ve faced during the making process, this project was actually pretty manageable and simpler than we thought it’d be! It was exciting to hear how the sound changed as we adjusted the potentiometer/pressed the switch button to create a melody. Potentially creating a song or playing an already existing one by using this instrument that we made will be really fun, and we’re proud of the final product that we ended up with!

Week 10: Air Piano

This is a fun instrument that lets you play simple tunes by waving your hands in the air!!

The basic idea is to be able to generate different frequencies of sound based on the position of your hand, which is sensed using an ultra-sonic sensor.

For this to work, the sensor has to be an open space such that there are no obstacles in front of it for at least a meter. Place your palm or any other obstacle in front of the sensor to obtain varying frequencies.

Schematics using Fritzing:

Here’s the code that makes it all work:

#define echoPin 6 
#define trigPin 5 
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
int tones;  
int tim=200;// duration for which one sound pulse will last
int buzzerPin = 8;
int space =500;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  pinMode(buzzerPin, OUTPUT);
  }
  
void loop() {
  
  //Finding distance of obstacle using ultrasonic sensor
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
  distance = duration * 0.034 / 2; // Distance = time*speed/2
  
  //Emitting sound as per the distance
  
  tones =20+distance*5; //calculating the frequency that has to be emitted

   tone(buzzerPin, tones, tim); //emits sound at the specified frequency and for the specified duration
    
   delay (space); //delay between each beat
  
}

Improvements:

In the given code the sounds are emitted at a fixed time interval for a fixed duration. We can play around with this by changing the value of the variables ‘tim’ and ‘space’. Also, we can play around with the way the frequency is calculated from the distance.

Week 9: Digital Input-Output

Ramp Lights!

This week we learned how to control and manipulate digital and analog input/outputs on Arduino IDE. It was interesting how a few lines of code with basic instructions could control a physical output like an LED. For the assignment, I created a ramp light sequence (imagine lights turning on one by one on a ramp, tried to recreate that). The lights turn on sequentially with the rotation of a potentiometer. Here’s a video of how that turned out:

How it works:

The working of this is very simple: the potentiometer has values calibrated with its rotation, so I took those values as input and using if and else if conditions, I changed the state of the LEDs to HIGH or LOW.

The Schematics:

Here’s a diagram of the schematics made using Fritzing:

Arduino IDE code:

int potPin = A5;
int ledPin1 = 2;
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 5;

void setup() {

  pinMode(potPin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  int potValue = analogRead(A5);
  Serial.println(potValue);

  if (potValue < 100) {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }
  
  else if (potValue < 256) {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);

  }

  

  else if (potValue < 512) {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin4, LOW);
  }

  else if (potValue < 768) {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, LOW);
  }

  else if (potValue < 1024) {
    digitalWrite(ledPin1, HIGH);
    digitalWrite(ledPin2, HIGH);
    digitalWrite(ledPin3, HIGH);
    digitalWrite(ledPin4, HIGH);
  }


}

It was fun creating the ramp lights and seeing the lights turn on/off with the turn of my potentiometer!

 

 

Distance musical instrument, Tarek Nabih & Aadil Zakareya

Concept:

We wanted to create a musical instrument that works without touching anything (of course but the switch button). So we used the ultrasonic sensor to control the frequency of the sound outputted by the buzzer. While coding we found it very annoying for the buzzer to run all of the time, without any option to stop it. Hence, we found it critical to add a button that controls whether the ultrasonic sensor and the buzzer are running. We also wanted to make it fancy in a way that you don’t hold the button for it to work but just press on it to start and press again to stop it, and that’s what we did. The ultrasonic measures the distance by the duration of time of the ultrasonic wave takes to come back, and by that controls the frequency of the buzzer. We also created a feedback loop from the serial by which we can know the distance and the frequency outputted.

Code:

The pins were declared:

int buttonPin = 2;

int echo = 6;
int trig = 5;

int speaker = 9;

long duration;
long distance;

bool isPressed = false;

then the ultrasonic trig and echo were settled up to the pins and the serial was set up as well:

void setup() {
  // setup pin modes
  Serial.begin(9600);

  pinMode(speaker, OUTPUT);
  pinMode(trig, OUTPUT); 
  pinMode(echo, INPUT);
  // pinMode(buttonPin, INPUT);
  // pinMode(buttonPin, INPUT_PULLUP);

}

the void loop basically has everything to do with the switch. a global variable was declared so that we save the last state of the ultrasonic and the buzzer, and when the button is pressed it switches the state. so when if the sensor is not running it makes it start running and vice versa. Moreover, I noticed that a delay had to be added because the void loop runs numerous times while the button is being pressed so it basically turns the sensor on and off numerous times giving us a 50% possibility of tuning the sensors on when the button is released. Hence, the delay is crucial for the project to work.

oid loop() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);

  int buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH){
    Serial.println("button pressed");
    // delay(5000);
    if(isPressed == false){
      isPressed = true;
      delay(1000);
      
    }else if(isPressed == true){
      Serial.print("came pressed ");
      noTone(speaker);
      isPressed = false;
      Serial.println(isPressed);
      delay(1000);
    }    
    // blink(2);
  }
  // Serial.println(isPressed);
  if(isPressed == true){
    updateSensor();
  }


}

Finally, the function that makes the sensor work, as in Tarek’s previous project the sensor calculates the distance by measuring the time it takes for the waves to go out and come back to the sensor again. based on that it scales the distance from 0 to 100 cm to the frequencies from 0 to 455. then it makes the buzzer start the sound in that specific frequency.

void updateSensor(){
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = duration * 0.034 / 2; 

  int frequency = ((int)(distance * 4.55) );
  frequency = (frequency > 455)? 455 : frequency;

  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.print(" cm, ");
  Serial.print("frequency: ");
  Serial.println(frequency);

  tone(speaker,frequency);

  delay(200);

}

 

Reflections:

While working on the project we noticed the potential that we have with just this Arduino and minor sensors like the ultrasonic and small gadgets like the buzzer. It also spiked our curiosity to find out what else can be done with such gadgets.

Rusty Trombone

The Muses of Ancient Greece are dead and gone, and I’ve discovered why.

The concept is simple: buttons for tones, distance sensor for modulation.

Schematic:

Code:

/* Name: Jan
   Project: Rusty Trombone

*/

// keeping track of button input pins
int buttonPins[] = {A1, A2, A4, A5};
int buttonRed = A1;
int buttonGreen = A2;
int buttonYellow = A4;
int buttonBlue = A5;

// distance sensor pins
int pinTrigger = 9;
int pinEcho = 8;

// buzzer pins
int buzzer = 12;

// keeping track of base tones {C, E, G, A}
float baseNotes[] = {262, 330, 392, 440};

//difference between semitones, for use with modulation
float semitone = 15;

float modulation = 0;
float inches;
int fret = 1;

void setup() {
  
  Serial.begin(9600);

  //initializing pins
  pinMode(buzzer, OUTPUT);
  
  pinMode(pinTrigger, OUTPUT);
  pinMode(pinEcho, INPUT);

  //setting the buttons to INPUT_PULLUP means i don't have to worry about pull down resistors clogging up my board
  pinMode(buttonRed, INPUT_PULLUP);
  pinMode(buttonGreen, INPUT_PULLUP);
  pinMode(buttonYellow, INPUT_PULLUP);
  pinMode(buttonBlue, INPUT_PULLUP);

}

void loop() {
  fret = 0;
  bool buttonPressed = 0;
  inches = getDistance();
  for (int i = 0; i < 20; i+=2) {
    fret++;
    if (inches < i) {
      modulation = semitone * fret;
      break;
    }
  }

  if (digitalRead(buttonRed) == LOW) {      //if the first key is pressed
    tone(buzzer, 262 + modulation); 
    Serial.println(inches);                 
  }
  else if (digitalRead(buttonGreen) == LOW) { //if the second key is pressed
    tone(buzzer, 330 + modulation);                   
  }
  else if (digitalRead(buttonYellow) == LOW) { //if the third key is pressed
    tone(buzzer, 392 + modulation);                    
  }
  else if (digitalRead(buttonBlue) == LOW) {
    tone(buzzer, 440 + modulation);
  }
  
  else {
    noTone(buzzer);                        //if no key is pressed turn the buzzer off
  }
}


float getDistance()
{
  float echoTime;                   //variable to store the time it takes for a ping to bounce off an object
  float calculatedDistance;         //variable to store the distance calculated from the echo time

  //send out an ultrasonic pulse that's 10ms long
  digitalWrite(pinTrigger, HIGH);
  delayMicroseconds(1);
  digitalWrite(pinTrigger, LOW);

  echoTime = pulseIn(pinEcho, HIGH);      //use the pulsein command to see how long it takes for the
                                          //pulse to bounce back to the sensor

  calculatedDistance = echoTime / 148.0;  //calculate the distance of the object that reflected the pulse (half the bounce time multiplied by the speed of sound)


  return calculatedDistance;              //send back the distance that was calculated
}

Evidence of My Crimes

Reflections: Code as is requires a lot of fine-tuning for the buzzer not to sound like it’s gently caressing a combine harvester. More specifically, changing the changes in tone from continuous to discrete kept the buzzing down. Tweaking the distance intervals at which the tone goes up or down a semitone keeps it from oscillating too much, as might changing how often the tone sounds. The equation for calculating distance from the sensor also has a lot of room for tuning, but I have not the hubris to claim to be a master of time nor space. Fun project though, had a blast.

Unusual Instrument – Daniel & Sara

Concept

For this week’s assignment, [Daniel] and I constructed a musical instrument that measures the distance between the ultrasonic sensor and anything placed in front of it (i.e., your hand). Depending on how far you place your hand/ an object from the sensor, the piezo buzzer will play one of 8 different notes we inputted into the code.

To do this, we used a force sensing resistor that you had to press on whenever you wanted the ultrasonic sensor to detect your hand, and a piezo buzzer that would play the sound as output.

Arduino: How to Make an Instrument

Schematic and Images

Here is the schematic for the circuit:

Code (or code highlight?)

int trig = 10; // digital 10
int echo = 11; // digital 11
long duration;
long distance;
int force;
 
 
void setup() {
 // runs once
 pinMode(echo, INPUT); // digital 11 
 pinMode(trig, OUTPUT); // digital 10
 Serial.begin(9600); // open serial monitor to track
}
 
void loop() {
 // runs repeatedly
 digitalWrite(trig, LOW);
 delayMicroseconds(2);
 digitalWrite(trig, HIGH);
 delayMicroseconds(10);
 digitalWrite(trig, LOW);
 duration = pulseIn(echo, HIGH);
 distance = (duration / 2 * 0.0344);
 
 int notes[7] = {233, 261, 293, 311, 349, 392, 440};
 //              Bb    C   D     Eb    F   G   A    
 
 force = analogRead(A0); // analog 0
 
 if (distance < 0 || distance > 50 || force < 100){
   noTone(12);
 
 } else if (force > 100){
   int sound = map (distance, 0, 50, 0, 7);
   tone(12, notes[sound]);
  
 }
}

The notes were based on the key of Bb, as we intended to make Bohemian Rhapsody first, the notes and values are:

Bb: 233

C: 261

D: 293

Eb: 311

F: 349

G: 392

A: 440

Video:

Here I’m playing Twinkle Twinkle Little Star using the instrument.

Reflection and improvements:

  • The ultrasonic sensor was very sensitive to movement very close to it, but the farthest note (A), was very hard to detect just because it was so far away from the sensor. This made the sound laggy when it came out of the piezo buzzer, which made the song sound very untuned and the note inconsistent.
  • It may also be because of the quality of the sensor, but the range seemed too limited and not so accurate. If we tried to make it a shorter distance between frequencies, then it would have a lot of sliding, and if we wanted to keep the same distance apart we would have needed to move it further and cause a much more unstable sound

 

Night-Light Daniel Basurto

concept

The idea for this concept comes from a point of laziness,  as in my room, when I want to turn the lights off, I need to immediately go to sleep, as I don’t have a nightlight for when I want to sleep.

Therefore, with my little understanding of Arduino hardware and coding, I decided to do a simple enough project but also being functional.

When making the circuit I needed help, and I was looking into many YouTube videos in order to find a way to properly understand it, I took what I could from the videos and made my circuit and code accordingly.

Circuit

Here is the schematic for the circuit:

And here is the project in action:

There weren’t many problems with the circuit working, however, I do wish I could have added more to make it more complex, however that will only come as I get more experienced with Arduino and coding for it.

Code

I was lost as to how to write the code, and found a code in one of the videos I found.

/*
  LDR sensor
              BY STUPIDCREATIVITY
*/

void setup() {
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}
void loop() {
  float sensorValue = analogRead(A0);
  // Reads the analog input ranging from 0 to 1023
  Serial.println(sensorValue);
  if(sensorValue<=400)
  {
    digitalWrite(13,HIGH);
  }
  else
  digitalWrite(13,LOW);
}

Now that I am looking back to the project after days of making it, I realize that the code is not as complex as I thought as the beginning. I do comprehend it now, however at the time I made the circuit I did not know.

Further Improvements

I would have preferred for this project to have taken less time, however I am satisfied with what I did. Maybe I’d like to add a kill-switch or a way for the circuit to end after amount of time.

 

Week 8: Unusual Switch- Productivity Detector!

Idea:

The objective of this week’s assignment was to create a hands-free switch in a simple circuit. For this, I came up with an idea to create a circuit that with a led that turns on when I close my laptop lid. My laptop battery drains when the lid is open, even if the screen is asleep. Sometimes, I would go to bed without closing my laptop lid and my laptop would die in the morning without me even using it. Hence, a led to detect that!

To implement this, I used tiny thin strips of aluminum foil on my laptop deck and the top of the laptop screen and aligned them so that they touch each other when the lid is closed. The aluminum strips are connected to the jumper and the circuit is completed on the breadboard.

Things to improve:

With code, I could create a more functional circuit which would be red when the lid is opened signaling battery drain and would turn green when the lid is closed.

Musical Instrument (Pseudo-Theremin)

A theremin is an electronic musical instrument which is played by the performer without physical contact. By the use of the hands suspended in the air over antennas, one hand controls the volume and the other controls the pitch or frequency.  The player plays different frequency ranges  at different volumes by moving the hands at different distances.

My idea was to mimic a pseudo-theremin by using ultrasonic sensors and a buzzer. I arranged two ultrasonic sensors at different orientations to track the distance of the hand. I then mapped the two ultrasonic sensors to frequency and volume by mapping the values read from the sensors to specific frequency and volume ranges.

The schematic and code:

/*
Name: Mbebo Nonna
Date: 10/14/2022
Project: Pseudo-theremin build

input: (2,3) (6,7)
2 ultrasonic sensors 

output: (9,10)
buzzer 

*/

#include <NewPing.h>
#include <toneAC.h>

//defining the max_distance of the theremin
const int max_d = 35;

//ultrasonic sensor to control frequency;
const int trig_f = 3;
const int vol_f = 2;

//ultrasonic sensor to control volume;
const int trig_v = 6;
const int vol_v = 7;

NewPing freq(trig_f, vol_f, max_d);
NewPing vol(trig_v, vol_v, max_d);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  //read the distance from the ultrasonic sensor for frequency
  int f = freq.ping_cm();
  Serial.print("freq ");
  Serial.println(f);

  //read the distance from the ultrasonic sensor for volume
  int v = vol.ping_cm();
  Serial.print("vol ");
  Serial.println(v);

  //map the values to specific ranges
  int volume = map(v, 0, 15, 0, 10);
  int frequency = map(f, 5, 30, 1000, 15000);

  //play the sound on the buzzer with the frequency and volume
  toneAC(frequency, volume);

  //delay for 200ms
  delay(200);

}

Video of me playing the pseudo-theremin:

Reflections:

I used two new libraries, NewPing.h and toneAC.h. NewPing makes working with ultrasonic sensors easy and toneAC makes working with buzzers or speakers simple. In generally, it was really fun playing the instrument and experimenting with different delays and frequency ranges.