Group Project – Music Box

Our task this week was to work with one other person from class and make a musical instrument. Sara and I decided to make a music box.

The materials we used on our Arduino are as follows:

  • two servo motors (one for the rotating figurine, one for the lid opener)
  • one buzzer (for tone)
  • a potentiometer (to switch the music box on)
  • a wooden box
  • a small figurine

First, we stuck the servo boxes using velcro into the box, and then we added the buzzer. One servo was to just open the box and the other one was to turn the figurine around.

The building process: 

Our Code:

#include <Servo.h>
 
Servo servo;
Servo servo2;

//PINS
int speakerPin = 8;
int servoPin = 10;
int servo2Pin = 9;
int potentioPin = A2;
int length = 15; // the number of notes
char notes[] = "ccggaagffeeddc "; // a space represents a rest
int beats[] = { 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
int tempo = 300;



//FOR SERVO
const int MAX_DISTANCE = 160;
//const int MED_DISTANCE = 90;
const int MIN_DISTANCE = 20;
int degree = 10;
int pos = 50;
int pos2;

//FOR POTENTIOMETER
int potentioValue = 0;

int i = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(servoPin);
  servo2.attach(servo2Pin);
  pinMode(speakerPin, OUTPUT);
  servo2.write(20);
  servo.write(20);
}

void playTone(int tone, int duration) {
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
  }
}

void playNote(char note, int duration) {
  char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };

  // play the tone corresponding to the note name
  for (int i = 0; i < 8; i++) {
    if (names[i] == note) {
      playTone(tones[i], duration);
    }
  } 

   pinMode(speakerPin, OUTPUT);
}
 
void loop() {

  potentioValue = analogRead(potentioPin);
  Serial.println(potentioValue);
  delay(1000);

  pos2 = map(potentioValue, 0, 1023, 50, 180);
  servo.write(pos2);
  //delay(1000);

  if (pos2 < 90)
  {
 
    pos = pos + degree;
  
    if (pos < MIN_DISTANCE || pos > MAX_DISTANCE)
    {
      degree = -degree;
    }
  
    servo2.write(pos);

    if (notes[i] == ' ') {
      delay(beats[i] * tempo); // rest
    } else {
      playNote(notes[i], beats[i] * tempo);
    }

    i++;555;

    if (i > length)
    {
      i = 0;
    }
    // pause between notes
    delay(tempo / 2); 
  }
  else
  {
    pos = 50;
    servo2.write(pos);
    //no tone
  }
}

 

Leave a Reply