I have an issue with my attached code which is that after I turn on a buzzer when the level is above 4 , then after the level become less than 4 it do not turn off directly. It takes the whole delay time before turned off ! I want to turn it off directly if the level less than 4
'''''''
const int buzzer = 8;
int sensor_value = 0;
int abs_value = 0;
void setup() {
pinMode(buzzer, OUTPUT);
pinMode(sensor_value, INPUT);
Serial.begin(9600);
}
void loop() {
// Read Sound sensor
sensor_value = analogRead(A0);
abs_value = abs(sensor_value);
int level = map(abs_value, 0, 1023, 0, 10);//Map to 0 to 10 level
Serial.println(level);
if (level > 4) {
delay(20000); // waits for 20 second
if (level > 4){
digitalWrite(buzzer,HIGH);
return;
}
else {
digitalWrite(buzzer, LOW);
}
Please read the post at the start of any forum , entitled "How to use this Forum".
This will help with advice on how to present your code and problems.
When you use the delay function, you basically stop the controller for that length of time, it does nothing, not even read inputs or change outputs.
It is termed a blocking function.
You need to look at the Example in the IDE called "Blinkwithoutdelay", it will show how to delay without stopping/blocking you code.
Also look at how you use if statements, you do not need the return statement.
A suggestion, before posting your code, press [ CTRL ] [ T ], this will auto format your code anmd make it easier to use.
You should post code by using code-tags
There is an automatic function for doing this in the Arduino-IDE
just three steps
press Ctrl-T for autoformatting your code
do a rightclick with the mouse and choose "copy for forum"
paste clipboard into write-window of a posting
write down an example with example-numbers that show a typical case
10:00:00 level is 2 (which is below threshold value 4)
10:00:07 level is 6 (which is above threshold value 4) ==> buzzer ON
10:??? ???
10:??? ????
10:??? ????
This list must have an entry for each change of any detail that is important.
By this description your potential helpers get a clear picture of the functionality you want to have.
And only if this is really clear suitable suggestions can be made.