Hi everyone, I am pretty new to this arduino programming. I am trying to do the following but I am a bit stuck on how to achieve this result.
I found some code that shows how to play a continuous sound through a speaker. I would like to implement into the code that if a certain switch is on then the sound will play, but if the switch is turned off then the sound wont play. I dont know how to implement this into the code, can someone please offer some guidance.
This is short code, I have seen some longer code with sounds which looks really cool but I cant figure out the switch settings to make the sound play or not.
int triggerPin = 7;
int echoPin = 8;
int pingPin = 5;
void loop()
{
if (digitalRead(pingPin) == HIGH)
{
int duration, distance;
digitalWrite(triggerPin, HIGH);
delay(10);
// my attempt here to check the pin state for the push of a button
if (digitalRead(pingPin) == LOW){ digitalWrite(triggerPin, LOW);}
The speaker is connected to pin3 and 5v-. My switch is connected to pin5 and gnd, switch is actually a jumper wire that i am manually connecting.
The rest of the code is what i have, its a simple example from the arduino examples using the ultrasonic sensor. I saw on another webpage where someone had modified the code and setup and I just went with that and it does make an annoying noise. While its making the noise I just what the noise to stop if I turn the switch off and play noise again if I flip the switch on.
int triggerPin = 7;
int echoPin = 8;
int led = 3;
int pingPin = 5;
int brightness = 0;
int fadeAmount = 5;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
pinMode(triggerPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
if (digitalRead(pingPin) == HIGH)
{
int duration, distance;
digitalWrite(triggerPin, HIGH);
delay(10);
digitalWrite(triggerPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if (distance < 100 )
{
analogWrite(led,75); Serial.print("ON");
}
else {
digitalWrite(led, LOW);
}
Serial.print(distance);
Serial.print("cm");
Serial.println(" ");
delay(500);
}
}
Since this is my first project working with Arduino, I wanted to play some sound out of the speaker and know how to control the sound. The code I have was taken from this article.
It works pretty good, but I didn;t know how to control when on and when off. The only additional item that I added was a jumper wire so I could open and close the connection. Now I am on the hunt for some cool sounds.