Why do the speakers beep every time the ping sensor is in use?
pin 4 is the speaker
unsigned long echo = 0;
int ultraSoundSignal = 7;
unsigned long ultrasoundValue = 0;
int ledPin1 = 1;
void setup()
{
pinMode(ledPin1, OUTPUT);
pinMode(ultraSoundSignal,OUTPUT);
pinMode(4, OUTPUT);
}
void music()
{
if(ultrasoundValue < 50)
{
digitalWrite(ledPin1, HIGH);
buzz(4, 2500, 500);
}
else // otherwise
{
digitalWrite(ledPin1, LOW);
digitalWrite(4, LOW);
}
}
void loop() {
ping();
music();
}
void buzz(int targetPin, long frequency, long length) {
long delayValue = 1000000/frequency/2; // calculate the delay value between transitions
//// 1 second's worth of microseconds, divided by the frequency, then split in half since
//// there are two phases to each cycle
long numCycles = frequency * length/ 2000; // calculate the number of cycles for proper timing
//// multiply frequency, which is really cycles per second, by the number of seconds to
//// get the total number of cycles to produce
for (long i=0; i < numCycles; i++){ // for the calculated length of time...
digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram
delayMicroseconds(delayValue); // wait for the calculated delay value
digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram
delayMicroseconds(delayValue); // wait againf or the calculated delay value
}
}
unsigned long ping(){
pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff
pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
echo = pulseIn(ultraSoundSignal, HIGH); //Listen for echo
ultrasoundValue = (echo / 58.138) * .39; //convert to CM then to inches
return ultrasoundValue;
}
The code itself works great with what i made... except the constant beeping.
Thanks!