Tuesday, May 1, 2012
Ryan & Dave - A simple musical instrument
This week we played around with a new actuator - a piezo speaker. Using the softpot like the fingerboard of a string instrument, we read an analog value and used it to control the frequency output of the piezo element. The piezo is wired between ground and pin 9. The softpot is wired between +5v and ground with the wiper connected to an analog input (A0). A momentary switch was added to be able to turn off the output due to extraneous static in the speaker.
The code is extremely simple:
//A simple musical instrument
int speakerPin = 9; //Set speaker to pin 9
int val = 0; //Set the analog input to 0
void setup(){
pinMode(speakerPin, OUTPUT); //Declair the pin at
//speakerPin to be an output
}
void loop(){
val = analogRead(0); // read the value from the sensor
tone(speakerPin, 2.5*val-500); //Generate a tone using m*x+b
//where m sets the range and b
//adjusts the pitch.
}
No comments:
Post a Comment