'how can I stop the song in the buzzer when there is a bright light coming in ldr sensor?
I tried doing the if else statement for the buzzer. But it finishes the song code first before the else statement runs. I tried running the code and it starts to simulate but the song does not immediately stop if there is a bright light. The bright light only stops the song after the birthday song ends and the song will start again if we put off the bright light. Is there any wrong in the if else statements?
const int sensorPin = A0; // select the input pin for ldr
int sensorValue = 0; // variable to store the value coming from the sensor
const int buzz = 2; // buzzer digital pin
void setup() {
pinMode(buzz, OUTPUT); //pin connected to the buzzer
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
if(sensorValue < 800){ //setting a threshold value
delay(100);
tone(buzz, 131);
delay(250);
noTone(buzz);
delay(125);
tone(buzz, 131);
delay(250);
tone(buzz, 147);
delay(500);
tone(buzz, 131);
delay(500);
tone(buzz, 175);
delay(500);
tone(buzz, 165);
delay(1000);
tone(buzz, 131);
delay(250);
noTone(buzz);
delay(125);
tone(buzz, 131);
delay(250);
tone(buzz, 147);
delay(500);
tone(buzz, 131);
delay(500);
tone(buzz, 196);
delay(500);
tone(buzz, 175);
delay(1000);
tone(buzz, 131);
delay(250);
noTone(buzz);
delay(125);
tone(buzz, 131);
delay(250);
tone(buzz, 262);
delay(500);
tone(buzz, 220);
delay(500);
tone(buzz, 175);
delay(500);
tone(buzz, 165);
delay(500);
tone(buzz, 147);
delay(500);
tone(buzz, 233);
delay(250);
noTone(buzz);
delay(125);
tone(buzz, 233);
delay(250);
tone(buzz, 220);
delay(500);
tone(buzz, 175);
delay(500);
tone(buzz, 196);
delay(500);
tone(buzz, 175);
delay(1000);
noTone(buzz);
delay(100);
}
else {digitalWrite(buzz,LOW);} //turn buzzer OFF
}
Solution 1:[1]
Instead of tone() and delay() steps create a new function something like playTone(int pin, int freq, int del) where you will first test sensor pin and based on results run tone(pin, freq) and delay(del).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nino |