Thursday, February 25, 2010

Sound project (music)

So here is a video clip of my project.





Here is the code that I used.

------------------------------------
#include "pitches.h"

const int buttonPin = 4; // the number of the pushbutton pin

int potPin = 2; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int val = 0; // variable to store the value coming from the sensor
int ledPin2 = 8;

int buttonState = 0; // variable for reading the pushbutton status

int melody[] = {
NOTE_B2,0, NOTE_B2,0, NOTE_E2,0, NOTE_E2, NOTE_E2,0, NOTE_F1,0, NOTE_F1,0, NOTE_B2,0,0};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
8, 8, 8, 8,8,16,16,16,16, 8,8,8,8,8,8,4};


void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT

// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop() {
val = analogRead(potPin); // read the value from the sensor
digitalWrite(ledPin, HIGH); // turn the ledPin on
delay(val); // stop the program for some time
digitalWrite(ledPin, LOW); // turn the ledPin off
delay(val); // stop the program for some time
for (int thisNote = 0; 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);
}
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
for(int fadeValue = 0 ; fadeValue <= 255; fadeValue +=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin2, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30); // stop the program for some time
} }
else {
// turn LED off:
for(int fadeValue = 255 ; fadeValue >= 0; fadeValue -=5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin2, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30); // stop the program for some time
}}
}

-----------------------

I did the best I could, but I still didn't get it working the way I wanted to. I am able to control the speaker: on and off. Fading the sound I don't know if it really work or not. Sometimes it sound that it faded but other times it doesn't. Another problem I faces was the buzzer. I can hear the buzzer buzz, but it is really low. It is adjustable with the potentiometer: beating faster and slower. However, you could barely hear it unless you are up close to it.