//------------------- speaker_freq_dur --------------------------
// ------ Plays a pitch thru a speaker and lights an LED ------
//- Set up: > Attach a piezo speaker between ground and Digital 6 (pin 12)
//---------------------------------------------------------------
int long_note = 450;
int short_note = 200;
void setup(){
pinMode(6, OUTPUT); // Define Speaker pin as output
}
void loop(){
digitalWrite(7, HIGH); // Turn on LED
play_pitch(523, long_note); // Run function with frequency & duration
play_pitch(523, long_note);
play_pitch(523, short_note);
play_pitch(587, short_note);
play_pitch(659, long_note);
digitalWrite(7, LOW); // Turn off LED
delay(1000); // delay one second
}
//---- Here we define a function called "play_pitch()" that takes 2 arguments:
void play_pitch(int freq, int duration){
int i; // Create variable for counting iterations
long period; // Create floating point variable
long pulse; // Create floating point variable
long cycles; // variable for number of cycles (duration)
period = 1000000/freq; // Calculate period
pulse = (period / 2 ); // Calculate pulse
cycles = duration * (freq / 1000.00); // Calculate duration
for(i = 0; i < cycles; i++){ // Loop for number of cycles
digitalWrite(6, HIGH); // Set speaker Pin high
delayMicroseconds(pulse); // delay for our calculated frequency
digitalWrite(6, LOW); // Set speaker Pin low
delayMicroseconds(pulse); // delay for our calculated frequency
} // end loop
} // end function definition
|