Please correct your post above and add code tags around your code. [code] // your code here [/code]
. it should look like this:// your code here
Also before pasting code, press ctrl-T in the IDE so that the lines are indented.
two options for your code:
Option one is just to add delay for 3 minutes after turning on the buzzer and then turning it LOW.
if (smoke_level > 70) { //
digitalWrite(buzzerPin, HIGH);
delay(180000ul); // note the ul to ensure we pass an unsigned long to the function
digitalWrite(buzzerPin, LOW);
} // no need for else, the buzzer pin is LOW by default all the time
this is very simple and can do the job if you don't want to do anything else in the code. this is called an ACTIVE WAIT. you are stuck in the delay() and have no way to check other things while the buzzer is buzzing. can be painful if you want to turn it off for example...
An alternative approach is to manage state (a very simple state machine). Basically you have two states in your program, one is the Alarm is Off and one is the Alarm is On. The default state is Alarm is OFF and you transition the state Alarm is ON when the smoke detector level is above 70. you return to the state Alarm OFF after 3 minutes (regardless of the state of Smoke detector during those 3 minutes).
That approach has the merit to incur no active wait, the code just check in which state it is and decides what to do if one of the condition to transition state is reached. but then you can do other things of interest like blinking a led or whatever even while the buzzer is ON because there is no active wait.
here is what it could look like (not tested, justed typed in here)
const int sensorPin = 0;
const int buzzerPin = 13;
int smoke_level;
enum {ALARM_OFF, ALARM_ON} alarmStatus;
unsigned long alarmStartTime;
const unsigned long alarmDuration = 3ul * 60ul * 1000ul; // 3 minutes in ms. using 'ul' to force unsigned long calculation
void setup() {
Serial.begin(115200); //
pinMode(sensorPin, INPUT);//the smoke sensor will be an input to the arduino
pinMode(buzzerPin, OUTPUT);//the buzzer serves an output in the circuit
alarmStatus = ALARM_OFF;
}
void loop() {
if (alarmStatus == ALARM_OFF) {
// alarm is OFF, checks if we need to turn it ON
smoke_level = analogRead(sensorPin); //arduino reads the value from the smoke sensor
Serial.println(smoke_level);//prints just for debugging purposes,
if (smoke_level > 70) {
alarmStatus = ALARM_ON;
alarmStartTime = millis();
digitalWrite(buzzerPin, HIGH);
}
} else {
// alarm is ON, checks if we need to turn it OFF
if (millis() - alarmStartTime >= alarmDuration) {
digitalWrite(buzzerPin, LOW);
alarmStatus = ALARM_OFF;
}
}
}
Now - the code can do other things, like checking a button to stop the Alarm. That would just add a new transition condition, if Alarm is ON and I press on the button, then move to the state alarm OFF. --> I let you implement this and show us the code you get. (you need to do a bit of work!)