Week 10 – Musical Instrument

Concept

For this project, I really wanted to make use of the servo motor in some way to produce sound. After fiddling around for quite some time, I found that the lid of my scented candle was the right place to put the motor. I noticed that it made an interesting sound when it dragged against the lid. This, along with an LDR, pushbutton, and sonar sensor are what I used to create my musical instrument.

Implementation

I wanted some way to control the speed at which the servo motor operated to produce a different background noise that the user could control. I also wanted to make it as convenient as possible for the user to operate it since the other hand was supposed to move in front of the sonar sensor to produce notes. So I decided to use an LDR sensor to control the servo motor’s speed. The brighter it gets, the greater the speed of the motor. Since I wanted to make it convenient, I used my phone’s torch and varied its brightness from a distance to control the speed of the motor. In the meanwhile, my other hand controlled the different notes that were being played on the buzzer.

I used an array of notes to store the different tones I was going to play based on the user’s hand position. The distance from the sensor was mapped to the indices of the notes array.

I also made use of a pushbutton to turn the motor off if the user wanted to. While the button is pressed, the motor won’t run. I did this because the other way around would have been to press the button to make the motor run, which would have been inconvenient for the user since they also have to use the light at the same time to control the motor’s speed.

The code I used for this project can be found below:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position
int servoSpeed = 2; // variable to change servo speed based on light

// variables for sonar sensor
int trig = 10;
int echo = 11;
long duration;
long distance;

// variable for pushbutton position
int buttonPin = 2;
// variable for button HIGH or LOW
int buttonState = 0;

void setup() {
  // attaches the servo on pin 9 to the servo object
  myservo.attach(9);  
  // setting the echo and trig pins of the sonar sensor
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  // setting up the pushbutton
  pinMode(buttonPin, INPUT);
  Serial.begin(9600); // for debugging
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // Serial.println(buttonState);

  //getting distance from the sonar sensor
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
  distance = (duration / 2) * 0.0344;

  // creating an array of frequencies
  // int notes[7] = {261, 294, 329, 349, 392, 440, 494};
  int notes[7] = {523, 587, 659, 698, 784, 880, 988};

  // if the hand is away from the sonar sensor
  if (distance < 0 || distance > 30) {
    // mute the sound
    noTone(12); 
  }

  // else play the tones
  else {
    // map the distance of the hand to the indices of the notes array
    int sound = map(distance, 0, 30, 0, 6);  
    // play the specific note
    tone(12, notes[sound]); 
  }

  // reading from the LDR
  int sensorValue = analogRead(A0);
  // Serial.println(sensorValue);
  // // delay(1);

  // setting the speed of the servo motor based on light intensity
  if (sensorValue < 102) {
    servoSpeed = 1;
  }
  else if (sensorValue < 130) {
    servoSpeed = 2;
  }
  else {
    servoSpeed = 3;
  }

  // making the servo motor move
  if (buttonState == LOW) {
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
      // in steps of 1 degree
      myservo.write(pos); // tell servo to go to position in variable 'pos'
      delay(servoSpeed);  // waits 15ms for the servo to reach the position
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos); // tell servo to go to position in variable 'pos'
      delay(servoSpeed);  // waits 15ms for the servo to reach the position
    }
  }
}


Challenges

The most challenging aspect for me in this project was to decide how to make the instrument operate. The decision to use the LDR to control the motor’s speed, making use of the pushbutton to control whether the motor was running or not, and using the sonar sensor instead of something like a potentiometer. Making the instrument work is one aspect, but putting everything together in a logical manner that would be easy enough to operate and at the same time sound decent enough was somewhat challenging. Nevertheless, I learned a lot about the piezo buzzer and producing sounds in general using the Arduino in this homework, and it was fun to do.

The Instrument

HW 7: Musical Instrument – Irem Naz Celen & Swostik Pati

If you have ever wondered how it would be to a starting DJ, this design is for you!

Alternative link to the video:https://drive.google.com/file/d/1kGo-VwdNhDPFH2HRHXRKaNn54ME_v5gZ/view?usp=sharing

Inspiration

The inspiration for this project comes from a DJ controller. We wanted to design a physical interface that would allow a range of motions by the DJ. Our focus was on an easy and intuitive design that would mimic a basic DJ controller. The 2 requirements that had to be fulfilled were a beat-making mechanism as well as a musical mechanism in which the frequency can be controlled.

Concept

In order to make our inspiration become a reality, we have decided to produce the musical notes in different frequencies of 7 tones through the buzzer while making a beat maker using the servo. A push button connected to the servo slams the handle on the wooden surface imitating the beat sound. On the other side, another button is used to switch between 7 different notes that are played in the buzzer. Potentiometer that feeds back to the buzzer allows the frequency of the tone that the buzzer is playing to go higher when it is twisted right, and lower when twisted left.

Implementation

In the implementation of the project an Arduino Uno, a servo, 2 push buttons, a buzzer, and a potentiometer are used. Servo’s rotating wing is taped to plastic handled screwdriver while the servo itself is fixed on a wooden plate.

The first push-button retains information on the occasions where it is pressed. A push that is recorded prompts the screwdriver that is connected to the rotating wing of the servo to switch from a levitating position to slam on the wooden fixation plate. The sound produced is similar to a beat sound that can be achieved from an electronic device. On the other side of the board, the push button and potentiometer both record information that changes the state of the buzzer. The buzzer is constantly creating sound. The range of sound is modeled from a piano’s octaves, and therefore there are 7 keys in 7 different octaves that can be produced from this buzzer according to the code. The frequencies of these notes are numerically written into the notes double array.  The push button for the buzzer (stationed towards the right side of the breadboard) switches between the 7 notes in the order of B, C,D,E,F,G, and A. Potentiometer on the other hand, switches into higher pitch/frequency of the same note, visually can be thought of as higher octave of the same note on the piano, when turned towards the right. There are again 7 octaves possible, in which the most left position of the potentiometer is the lowest frequency the note exists in while the most right position is the highest frequency of the note.

This is the code for the said implementation.

//Include Servo Library
#include <Servo.h>

//servo
int servoPin = 9;
int pos1 = 40;
int pos2 = 110;
int dt = 100;
Servo myServo;


//pushButton for servo
int pbPin = 13;
bool pbFlag = true;

//pushButton for note change
int notePin = 2;
bool nbFlag = true;
int currNoteI = 0;
int mappedValue;

//potentiometer
int potPin = A0;

//notes array
int tones[7][7] = {{31, 62, 123, 494, 988, 1976, 3951}, {33, 65, 131, 262, 523, 1047, 2093}, {37, 73, 147, 294, 587, 1175, 2349}, {41, 82, 165, 330, 659, 1319, 2637},
  {44, 87, 175, 349, 698, 1397, 2794}, {49, 98, 196, 392, 784, 1568, 3136}, {55, 110, 220, 440, 880, 1760, 3520}
};

//buzzer
int tonePin = 4;

void moveServo() {
  delay(dt);
  myServo.write(pos1);
  delay(dt);
  myServo.write(pos2);
  delay(dt);
}

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

  //  setting up servos
  myServo.attach(servoPin);
  myServo.write(pos2);

  //  setting up pushbutton
  pinMode(pbPin, INPUT);

  //  setting up buzzer
  pinMode(tonePin, OUTPUT);


}

void loop() {
  // put your main code here, to run repeatedly:
  //pushbutton and servo implementation
  int pbVal = digitalRead(pbPin);
  if (pbVal == 1 && pbFlag) {
    //high
    moveServo();
    pbFlag = false;
  }
  else if (pbVal == 0) {
    pbFlag = true;
  }

  //potentiometer implementation
  int potValue = analogRead(potPin);
  mappedValue = map(potValue, 0, 1023, 6, -1);
  //  Serial.println(mappedValue);
  //  Serial.println(potValue);

  //  pushbutton and note change implementation
  int nbVal = digitalRead(notePin);
  if (nbVal == 1 && nbFlag) {
    //high
    if (currNoteI < 6) {
      currNoteI++;
    }
    else {
      currNoteI = 0;
    }
    Serial.print("The current note is: ");
    Serial.println(currNoteI);
    nbFlag = false;
  }
  else if (nbVal == 0) {
    nbFlag = true;
  }

  //buzzer
  tone(tonePin, tones[currNoteI][mappedValue]);

}

 

Schematic Diagram

Challenges

The main challenge that we have come across was making the location of the push buttons and the potentiometer user-friendly while taking wires into consideration. We had to play around with different versions of the breadboard construction multiple times to make sure the musical instrument was approachable and easy to use.

Moreover, we also considered multiple circuit designs for the buzzer in order to control the volume by adding resistors. Upon multiple trials, we have decided not to add a resistor for maximum volume and clarity.

For servo attachment, we looked around for a considerable time to find the most suitable extension to make the optimum beat sound. Before deciding on attaching the screwdriver to the rotational component of the servo, we considered using plastic and wooden extensions. For gaining the right sound of a beat, we realized we needed more weight for the attached piece, hence the final screwdriver extension was chosen. Putting a wooden plate below enhanced the experience, after our trial and error.

Another consideration was given to the response time of the servo, by adjusting the delay time in the moveServo() function. The final adjusted value of the delay was given according to what sounded natural according to the frequency at which the push button of the servo was pushed.

Reflections

Making this project together as a group was very enjoyable, which made the design process more exciting and fun. A part to improve on in the next projects would be in terms of having more power in choosing which tone to play on the buzzer rather than having to follow the set order that is programmed in the current version of the code. On a more general note, we would love to improve our ability to follow up what is happening in the circuit as it gets more complex, and making the schematic together definitely allowed us to work on that.

Week 9 – Musical Instrument

by Ajla and Hana

Concept

This week’s assignment was to create a simple musical instrument using the Arduino. Hana and Ajla decided to create a simplified piano and drum. In order to do so, we utilized switches and a servo motor. We controlled the speed of the servo motor using a potentiometer. The notes are played by pressing the buttons. The buttons stop producing noise when released.

Implementation

To implement our musical instrument, we used a potentiometer, switches, a piezoelectric buzzer, resistors, wires and an Arduino. By connecting the switches in parallel we were able to preserve voltage across all components. Even though it was possible to connect everything on one breadboard, we decided to separate it in order to make the instrument user friendly. Furthermore, since many digital inputs were used, the separation ensured that there would not be any overcrowding while presenting the final product.The sketches below show both the two Arduino setup we used and one Arduino setup.

The code was written for both Arduino. Hana wrote the code for the switches and Ajla wrote the code for the drum. The drum was made using a metal screw, silk ribbon and tape which was attached to the servo hand. By pressing the four switches, notes, stored in an array, were played. The drum hit a piece of cardboard in order to produce noise.

Two Arduino
One Arduino

Here is the code for playing the notes:

// if button1 is pressed, playes first note
  if(button1State==1) {
    tone(9, notes[0]);
  }

// if button2 is pressed, playes second note

  if(button2State==1) {
    tone(9, notes[1]);
  }

// if button3 is pressed, playes third note

  if(button3State==1) {
    tone(9, notes[2]);
  }

// if button4 is pressed, playes fourth note

  if(button4State==1) {
    tone(9, notes[3]);
  }

// if buttons are release, no note is played

  if(button1State==0 && button2State==0  && button3State==0 && button4State==0) {
    noTone(9);
  }
  
  
  delay(1);  // delay in between reads for stability

Here is the code that ran the servo in a 90 degree range:

void loop() {
  int p_value  = analogRead(p_meter);

  int value = map(p_value, 0, 1024, 10, 20);
  for (int i=45; i<90; i += value) {
    pos1 = 0 + (i*2);          // servo1 from 0 to 90 degrees
    myservo1.write(pos1);      // move the servo
    delay(50);  
  }
 
  for (int i=45; i<90; i += value) {
    pos1 = 90 - i*2;           // servo1 from 90 to 0 degrees
    myservo1.write(pos1);      // move the servo
    delay(50);
  }
}

Challenges

The assignment came with a few challenges. Firstly, since the piezoelectric buzzer cannot take multiple inputs at once, it was important to play each note once, without pressing others since that would destroy the quality of the sound. Secondly, the notes play continuously if the button is pressed, even once. That is why we added the last if statement that checks whether all buttons are not pressed, in which case it plays no sound. Thirdly, the servo is quite tricky to use at high speeds. It gets more imprecise as the speed goes up. So, controlling it with the potentiometer was quite hard to do precisely. Lastly, since the angle of motion changes as the speed increases, it was hard to mount the servo on anything as it would immediately fall down once the speed was changed. This became quite frustrating that we decided to just hold the servo in the end to showcase the tempo of the “drum”. All in all, this assignment came with quite a few challenges. Some of them we tried to attempt and won, such as the notes, but some of them remain to be defeated due to the lack of time and materials we had at the time of making this project.

Reflection (Ajla)

I am not very musically inclined. That is why it was quite hard to come up with any ideas for this project and why I wish the theme was a bit more open. However, I have learned quite a bit by attempting this project. The servo, although precise at low speeds, is something that gave me quite a headache when connected to a potentiometer. Since it rotates only 180 degrees, there is a limited amount of freedom I had while working on it which is something I do not like as a Computer Science major. The code could not make up for its shortcomings and I became quite frustrated because of that. However, it is important to learn from such experiences and try again in the future. Although I finished this assignment, I plan to work with theservo more in the future such as to learn how to make up for the drawbacks of its hardware.

Week 9 – BuzzBoard

BuzzBoard By Majid and Hassan

Concept

For our project, we aimed to create a unique musical instrument using distance tracking sensors and buttons. After brainstorming various ideas, we were inspired to design a piano-like instrument that could be played by two hands, one is distance tracked and the other is pressing the buttons. There are 7 notes and 3 different octaves that can be played. The notes are determined by the distance and the octave is based on which button is pressed.

implementation

We decided to use ultrasonic sensor for detecting the hand distance and buttons for controlling different notes of the piano. The Arduino was also connected to a piezo sensor for producing the piano sounds. Once the circuit assembly was complete, we tested the circuit to ensure the sensors and buttons were working and registered properly. Then we programmed the buttons to play different octaves of the notes.

Deciding which note to be played is at the core of our code. We did so through making a list of if conditions. First we checked what was the last button pressed, to decide the octave we are playing the notes in. After that, based on the distance from the ultrasonic sensor, in increments of 3cm, we chose a note to be played. For example, here is how the notes are played if the last button pressed was 2:

  if(lastButton == 2){
  if (distance < 3) {
    tone(8,NOTE_A4,noteDuration);
  } else if (distance >= 3 && distance < 6) {
    tone(8,NOTE_B4,noteDuration);
  } else if (distance >= 6 && distance < 9) {
    tone(8,NOTE_C4,noteDuration);
  } else if (distance >= 9 && distance < 12) {
    tone(8,NOTE_D4,noteDuration);
  }
  else if (distance >= 12 && distance < 15) {
    tone(8,NOTE_E4,noteDuration);
  }
      else if (distance >= 15 && distance < 18) {
    tone(8,NOTE_F4,noteDuration);
  }
      else if (distance >= 18 && distance < 21) {
    tone(8,NOTE_G4,noteDuration);
  }
}

Challenges

One of the main challenges we encountered during the project was calibrating the distance sensors to play different notes. We had to experiment with different threshold values and distances for the different notes and octaves.

The Demo

Week 10 – Musical Instrument

Concept

Our project is a musical instrument that uses an ultrasonic sensor to measure the distance between the sensor and an object and plays different notes based on the distance. A note is played when a push button is pressed. The distance measurement is then mapped to an array of notes to play on a piezo buzzer.

 

IMPLEMENTATION

We have started from setting up a circuit that uses next components: ultrasonic sensor, piezo buzzer, 10 jumper wires, pushbutton, and 10k resistor. The ultrasonic sensor was used to measure the distance of the object from the instrument, and the piezo buzzer was used to play the musical notes based on the measured distance. The pushbutton was used to activate the instrument and play the notes, and the 10k resistor was used as a resistor for the button. We connected all these components using jumper wires to establish a circuit that would form the foundation for the instrument.

We have then moved onto adding a code component. In the setup() function we have set the pinMode for each of the pins used in the circuit. We have also used the Serial.begin() function to start serial communication between the Arduino and the computer, which would allow us to view debug messages.

The first part of the loop function was used to read the distance measurement from the ultrasonic sensor using the pulseIn() function. We then used this distance measurement to calculate which note to play on the piezo buzzer. We mapped the distance to a note by dividing the range of distances by the number of notes we wanted to play (in this case, five).

The code then checked the state of the pushbutton using the digitalRead() function. If the pushbutton was not pressed, the piezo buzzer would not play any sound, and a message would be printed to the serial monitor. If the pushbutton was pressed, the corresponding note would play on the piezo buzzer, and a message indicating the button’s state and the note being played would be printed to the serial monitor.

// 
// Project name: "HW7: Musical Instrument"
// Names: Adina & Aibar
// Class: Intro to IM
// Professor: Michael Shiloh
//

int trigPin = 10;
int echoPin = 11;
int buttonPin = 2;
int buzzerPin = 12;

long duration;
long distance;

int buttonState;

void setup() {
  //distance pins
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  //button pin
  pinMode(buttonPin, INPUT);
  //buzzer pin
  pinMode(buzzerPin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW); //triggers on/off and then reads data
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * .0344; //speed of sound converted into cms

  int notes[5] = {261, 294, 329, 349, 392}; //array of notes
  //          mid  C    D    E    F    G 

  buttonState = digitalRead(buttonPin);
  if (buttonState == 0) { //if not pressed
    noTone(12);
    Serial.println("button not pressed");
  }

  else if ((buttonState == 1)) {  //if pressed
    int sound = map(distance, 0, 30, 0, 5);  //map distance to the array of notes
    tone(buzzerPin, notes[sound]);  //play a note
    //checking if works through serial monitor
    Serial.print("button pressed, ");
    Serial.print(buttonState);
    Serial.print(", ");
    Serial.println(sound);
  }
}

Schematic Diagram

VIDEO DEMO

If the video window doesn’t show, use this link to see the demo of the musical instrument.

 

 

CHALLENGES AND SOLUTIONS

Our biggest challenge was ensuring that the distance reader could detect the object in front of it accurately. When the reader did not detect the object correctly, the instrument played a weird sound that sounded like a very high pitch, which was not the sound we were hoping to achieve. It took several attempts to get the distance reader to work correctly. A solution that we came up with was decreasing the max distance when mapping the sound to the distance and using a solid object like the back of the phone, rather than a hand. By decreasing the maximum distance for the object, we were able to make sure that the distance reader could pick up on the object’s presence.

 

HW7: Musical Instrument

CONCEPT

Our project is a musical instrument that uses an ultrasonic sensor to measure the distance between the sensor and an object and plays different notes based on the distance. A note is played when a push button is pressed. The distance measurement is then mapped to an array of notes to play on a piezo buzzer.

IMPLEMENTATION

We have started from setting up a circuit that uses next components: ultrasonic sensor, piezo buzzer, 10 jumper wires, pushbutton, and 10k resistor. The ultrasonic sensor was used to measure the distance of the object from the instrument, and the piezo buzzer was used to play the musical notes based on the measured distance. The pushbutton was used to activate the instrument and play the notes, and the 10k resistor was used as a resistor for the button. We connected all these components using jumper wires to establish a circuit that would form the foundation for the instrument.

We have then moved onto adding a code component. In the setup() function we have set the pinMode for each of the pins used in the circuit. We have also used the Serial.begin() function to start serial communication between the Arduino and the computer, which would allow us to view debug messages.

The first part of the loop function was used to read the distance measurement from the ultrasonic sensor using the pulseIn() function. We then used this distance measurement to calculate which note to play on the piezo buzzer. We mapped the distance to a note by dividing the range of distances by the number of notes we wanted to play (in this case, five).

The code then checked the state of the pushbutton using the digitalRead() function. If the pushbutton was not pressed, the piezo buzzer would not play any sound, and a message would be printed to the serial monitor. If the pushbutton was pressed, the corresponding note would play on the piezo buzzer, and a message indicating the button’s state and the note being played would be printed to the serial monitor.

// 
// Project name: "HW7: Musical Instrument"
// Names: Adina & Aibar
// Class: Intro to IM
// Professor: Michael Shiloh
//

int trigPin = 10;
int echoPin = 11;
int buttonPin = 2;
int buzzerPin = 12;

long duration;
long distance;

int buttonState;

void setup() {
  //distance pins
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
  //button pin
  pinMode(buttonPin, INPUT);
  //buzzer pin
  pinMode(buzzerPin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW); //triggers on/off and then reads data
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * .0344; //speed of sound converted into cms

  int notes[5] = {261, 294, 329, 349, 392}; //array of notes
  //          mid  C    D    E    F    G 

  buttonState = digitalRead(buttonPin);
  if (buttonState == 0) { //if not pressed
    noTone(12);
    Serial.println("button not pressed");
  }

  else if ((buttonState == 1)) {  //if pressed
    int sound = map(distance, 0, 30, 0, 5);  //map distance to the array of notes
    tone(buzzerPin, notes[sound]);  //play a note
    //checking if works through serial monitor
    Serial.print("button pressed, ");
    Serial.print(buttonState);
    Serial.print(", ");
    Serial.println(sound);
  }
}

 

VIDEO DEMO

If the video window doesn’t show, use this link to see the demo of the musical instrument.

CHALLENGES AND SOLUTIONS

Our biggest challenge was ensuring that the distance reader could detect the object in front of it accurately. When the reader did not detect the object correctly, the instrument played a weird sound that sounded like a very high pitch, which was not the sound we were hoping to achieve. It took several attempts to get the distance reader to work correctly. A solution that we came up with was decreasing the max distance when mapping the sound to the distance and using a solid object like the back of the phone, rather than a hand. By decreasing the maximum distance for the object, we were able to make sure that the distance reader could pick up on the object’s presence.

HW | Musical Instrument

Group: Dariga Shokayeva, Vladimir Sharkovski

Concept

We created a musical instrument which plays beats. Our instrument is very versatile:

  • The distance sensor allows you to easily control the frequency of the tone, without having to touch anything. Therefore you can play both very low tones and very high ones.
  • The potentiometer allows you control the duration of the beats, from 20 milliseconds to half a second. Therefore you can play both a rapidfire almost continual beat, or a slow jazzy beat.
  • The button allows you to shift the frequency of the tone to a higher range while the button is pressed. Therefore you can quickly surprise the listener with your melodies.
Circuit Diagram


Video demo
Code
// Pin positions.
const int potPin = A0;
const int buttonPin = 5;
const int trigPin = 6;
const int echoPin = 7;
const int speakerPin = 8;

// Other constants.
const int minDistance = 0;
const int maxDistance = 20;

const int toneDurationMin = 30;
const int toneDurationMax = 500;

const float toneDelayFactor = 1.3f;

void setup() {
  pinMode(potPin, INPUT);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(speakerPin, OUTPUT);
}

long getSensorDistance() {
  // Send pulse.
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Read pulse duration.
  long duration = pulseIn(echoPin, HIGH);
  // Calculate distance from duration.
  long distance = (double)duration * 0.034 / 2.0;

  return distance;
}

void loop() {
  // Get distance and constrain it.
  long distance = getSensorDistance();
  distance = constrain(distance, minDistance, maxDistance);
  
  // Map distance to tone frequency.
  int toneFreqMin, toneFreqMax;
  int buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    toneFreqMin = 20;
    toneFreqMax = 400;
  } else {
    toneFreqMin = 300;
    toneFreqMax = 1500;
  }

  int toneFrequency = map(distance, minDistance, maxDistance, toneFreqMin, toneFreqMax);

  // Calculate time to play the tone based on the potentiometer position.
  int potPosition = analogRead(potPin);
  int toneDuration = map(potPosition, 0, 1023, toneDurationMin, toneDurationMax);

  // Play the tone, then wait some time.
  int waitTime = toneDuration * toneDelayFactor;
  tone(speakerPin, toneFrequency, toneDuration);
  delay(waitTime);
}
Reflection

It was challenging to figure out how the ultrasonic distance sensor worked, because it has 4 pins to set up. We also had to do some math, using the speed of sound, to convert the duration produced by the sensor into a proper distance.

Also, it took a lot of work to figure out the proper ranges for the minimum and maximum frequency for the instrument to play. Too high frequencies were irritating.

One way to improve the instrument is to think about ways to make it easier to use (more accessible). Right now it is a bit awkward to control the potentiometer and button with one hand, while using the other hand with the sensor. Also, it would be convenient to have a way to mute the speaker, or even control its volume.

Music instrument

Group: Dariga Shokayeva, Vladimir Sharkovski

Concept

We created a music instrument which plays beats. Our instrument is very versatile:

  • The distance sensor allows you to easily control the frequency of the tone, without having to touch anything. Therefore you can play both very low tones and very high ones.
  • The potentiometer allows you control the duration of the beats, from 20 milliseconds to half a second. Therefore you can play both a rapidfire almost continual beat, or a slow jazzy beat.
  • The button allows you to shift the frequency of the tone to a higher range while the button is pressed. Therefore you can quickly surprise the listener with your melodies.
Video demo
Circuit diagram
Circuit for the music instrument.
Code
// Pin positions.
const int potPin = A0;
const int buttonPin = 5;
const int trigPin = 6;
const int echoPin = 7;
const int speakerPin = 8;

// Other constants.
const int minDistance = 0;
const int maxDistance = 20;

const int toneDurationMin = 30;
const int toneDurationMax = 500;

const float toneDelayFactor = 1.3f;

void setup() {
  pinMode(potPin, INPUT);
  pinMode(buttonPin, INPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(speakerPin, OUTPUT);
}

long getSensorDistance() {
  // Send pulse.
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Read pulse duration.
  long duration = pulseIn(echoPin, HIGH);
  // Calculate distance from duration.
  long distance = (double)duration * 0.034 / 2.0;

  return distance;
}

void loop() {
  // Get distance and constrain it.
  long distance = getSensorDistance();
  distance = constrain(distance, minDistance, maxDistance);
  
  // Map distance to tone frequency.
  int toneFreqMin, toneFreqMax;
  int buttonState = digitalRead(buttonPin);

  if (buttonState == LOW) {
    toneFreqMin = 20;
    toneFreqMax = 400;
  } else {
    toneFreqMin = 300;
    toneFreqMax = 1500;
  }

  int toneFrequency = map(distance, minDistance, maxDistance, toneFreqMin, toneFreqMax);

  // Calculate time to play the tone based on the potentiometer position.
  int potPosition = analogRead(potPin);
  int toneDuration = map(potPosition, 0, 1023, toneDurationMin, toneDurationMax);

  // Play the tone, then wait some time.
  int waitTime = toneDuration * toneDelayFactor;
  tone(speakerPin, toneFrequency, toneDuration);
  delay(waitTime);
}
Reflection

It was challenging to figure out how the ultrasonic distance sensor worked, because it has 4 pins to set up. We also had to do some math, using the speed of sound, to convert the duration produced by the sensor into a proper distance.

Also, it took a lot of work to figure out the proper ranges for the minimum and maximum frequency for the instrument to play. Too high frequencies were irritating.

One way to improve the instrument is to think about ways to make it easier to use (more accessible). Right now it is a bit awkward to control the potentiometer and button with one hand, while using the other hand with the sensor. Also, it would be convenient to have a way to mute the speaker, or even control its volume.

HW 6: Automating the Chrome Dinosaur Game

Have you ever played the Google Chrome Dinosaur Game while waiting for your internet connection to be restored? It’s a simple game that can become addicting as you try to beat your high score. But what if you could take it to the next level by automating the game with an Arduino circuit?

Link to Video

Inspiration

I was inspired to automate the Chrome Dinosaur Game after seeing similar projects on YouTube and other online platforms. I was fascinated by the idea of using an Arduino circuit to control a physical object in response to the game. It was a great opportunity to practice my programming and electronics skills while having fun.

Concept

The concept of my project was to automate the game using a light sensor and a servo motor. The light sensor detects changes in pixel brightness on the screen when obstacles like cacti show up. When an obstacle is detected, the servo motor presses the spacebar key on the laptop to make the dinosaur jump over the obstacle. A push button was added to the circuit to start and stop the entire automation process. Additionally, I added a red LED to indicate the circuit is on and a blue LED to track the progress of the game.

Implementation

To implement my project, I used an Arduino Uno board, a light-dependent resistor (LDR) as my light sensor, a push button, a red LED, a blue LED, and a servo motor.

The push button provides input digitally to turn on or off the circuit. As soon as the circuit is turned on, the red led starts glowing. digitalWrite is used for this operation. The light sensor which is stuck to the laptop screen at an appropriate position to detect obstacles in the path of the chrome dinosaur game, starts reading light intensity values. As soon as an obstacle passes by the light sensor detects a value above (because my browser is in dark mode) the set threshold (which it ideally should be), it sends a signal to the servo to rotate a specific angle in order to hit press the spacebar. This causes the running dino to jump and cross over the obstacle. The blue light glows more brighter with each passing jump symbolising the progress through the game.

This is the code for the said implementation.

 

//Dinosaur Chrome Automation - Analog and Digital IO

//Include Servo Library
#include <Servo.h>

// initializing global variables
int servoPin = 9;
int pos1 = 40;
int pos2 = 110;
int dt = 100;
int count = 0;
int lightInt = 0;
int pushbuttonPin = 13;
int pushbuttonState = 0;
int redLED = 12;
int blueLED = 6;
int blueBr = 0;
int lSPin = A2;
int val;
int thres = 110;
int a;

bool switchONOFF = false;
bool flag = true;
bool switchFlag = true;

Servo myServo;

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

  //  setting up servos
  myServo.attach(servoPin);
  myServo.write(pos2);

  //  setting pinModes
  pinMode(lSPin, INPUT);
  pinMode(pushbuttonPin, INPUT);
  pinMode(redLED, OUTPUT);
  pinMode(blueLED, OUTPUT);
}

//controls the movement of the servo
void spaceBarServo() {
  delay(dt );
  myServo.write(pos1);
  delay(dt);
  myServo.write(pos2);
  delay(dt);
}

void loop() {
  // checks for when the button is pressed
  pushbuttonState = digitalRead(pushbuttonPin);
  //  filters out only button clicks and removes button being continuously pressed
  if (pushbuttonState == 1 && switchFlag) {
    //    states of switch on or off
    if (count % 2 == 0) {
      switchONOFF = true;;
    }
    else {
      switchONOFF = false ;
    }
    count++;
    switchFlag = false;
  }
  else if (pushbuttonState == 0) {
    switchFlag = true;
  }

  if (switchONOFF == true)
  {
    //    denotes that the ciruit is ON and listening to obstacles
    digitalWrite(redLED, HIGH);

    //reads the light sensor value
    val = analogRead(lSPin);
    //    debugging output on screen
    Serial.println(val);
    //    checking for if the light sensor value crossed the threshold - denoting obstacle detected on screen
    if (val > thres and flag) {

      // incrementing the brightness of the blue led
      if (blueBr + 2 < 255) {
        blueBr += 2;
      }
      // calling the servo function to hit the spacebar
      spaceBarServo();
      // turning on the blue LED with the specific intensity
      analogWrite(blueLED , blueBr);
      //      flag is used to avoid multiple increments on one jump above the threshold
      flag = false;
    }
    else if (val < thres) {
      flag = true;
    }
  }
  else {
    //    resetting everything if the light is turned off
    blueBr = 0;
    analogWrite(blueLED , blueBr);
    digitalWrite(redLED, LOW);

  }

}

Schematic Diagram

Challenges

One of the biggest challenges I faced during this project was getting the light sensor to accurately detect the obstacles. I had to experiment with different threshold values to make sure the sensor was triggered at the right time. It took a lot of trial and error to adjust the sensor and threshold values to my ambient conditions. Switching off a light in the room caused some noticeable changes in its behavior.

Additionally, I had to ensure the servo motor was placed in the perfect place so that it was firmly pressing the spacebar key at the right time while making sure that it didn’t damage it.

A very weird challenge that I hadn’t ever expected to encounter was the inconvenience of working on the computer as soon as I struck the servo and the light sensor on my laptop. It took a lot of time to navigate around this but finally I was able to get the work done.

Reflections

This project was a great learning experience for me. I learned a lot about programming and electronics, and it was fun to see my circuit in action. I was also surprised at how well my circuit worked in the end. The thing that I would like to improve on would be to make cleaner circuits so as to prevent bugs in my future works.

Assignment 6: Handshake-meter

Concept

The concept of this project comes purely from my desire to use a analog sensor that we have not used before. For this reason I wanted utilize the temperature sensor we have. For the ways which I could integrate the sensor first i though about a mechanism like alarm clock which would stop ringing if you placed your hand over it (due to immediate temperature difference) however since we had to use one digital sensor and 2LED s still, I had to choose another sensor. So I decided to switch that can be used to switch from an LED to another one.

 

Implementation

For this project, I first connected the temperature sensor. Since it takes time for the sensor to relay information on the temperature change I decided to put delay information. For the conversion of the read value from the sensor to the intelligible temperature value, this link can be used. When the jump level for the temperature is achieved, the red LED is turned on. On the other hand, when the switch is pushed the green LED is on until there is a significant drop on the temperature sensor again.

int tempPin = A0; //the temperature pin
int gLed = 3;
int rLed = 4;
int buttonPin = 8;
int ctr = 0;
int data1;
float temperature1;

void setup() {
  // Init serial at 9600 baud
  Serial.begin(9600);
}

void loop() {
  if (ctr == 0) {
    //initial temperature is recorded only once at the start and stored for use
    data1 = analogRead(tempPin);
    temperature1 =  100 * ((data1 * 5.0 / 1024.0) - 0.5);
    //the temperature recorded can be seen at the monitor
    Serial.print("Temperature: ");
    Serial.print(temperature1);
    Serial.println(" *C");
    ctr++;
  }

  //reads pure temp sensor data
  int data2 = analogRead(tempPin);
  // conversion to temperature from the data
  float temperature2 = 100 * ((data2 * 5.0 / 1024.0) - 0.5);;

  //the difference is recorded
  float difference = temperature2 - temperature1;

  //difference from the current to the initial temperature is mapped for the green LED
  analogWrite(gLed, map(difference, 0, 3, 0, 255));

  //red LEDis lit up according to the button pressed
  int buttonState = digitalRead(buttonPin);
  digitalWrite(rLed, buttonState);

  //difference pattern observed in the monitor
  Serial.print("Difference: ");
  Serial.print(difference);
  Serial.println(" *C");
  delay(800); // wait a second between readings
}

Schematic Diagram

Challenges

It was quite hard to do trial and error on the temperature data, as it was quite experimental. I had to watch through the relayed data some time to figure out which data cutoffs to use, as well as delay. It is still open to changes and the whole effect of the project would change according to these values that are arbitrarily determined. The project had similar challenges to plans that were not brought into reality before. Its in soul similar to Simone Giertz’s projects.

On the other hand, the mechanism of having it on my hand, and making sure that it didn’t move and was still usable was also very hard. I experimented with a couple of materials to make sure that the cables did not slip away, or the temperature sensor didn’t give faul values.

Reflections

This was a completely experimental project and even its purpose is questionable. I wanted to make a commentary on the social construct of what is a required amount to handshake and how we view it as weird if it is too long etc. I made the LEDs work in reverse, as red when you are waiting for it, and green if you handshake for too long (measured in temperature). It was quite fun and frankly purposeless and I feel like that’s why I enjoyed building this project.