How can I make the active buzzer sound for 5 seconds?

I've been trying to make this IR Alarm which should sound for 5 seconds but don't know how to start.

#define led 4            // led at pin 4
#define buzzer 5      // buzzer at pin 5
#define sensor 6      // ir sensor at pin 6
int sound=400;         // set buzzer sound
void setup()
{
Serial.begin(9600);
pinMode(sensor,INPUT);
pinMode(led,OUTPUT);
pinMode(buzzer,OUTPUT);
}

void loop()
{

int detect=digitalRead(sensor);   // read status of sensor
if(detect==HIGH)               // if sensor detects obstacle
{
digitalWrite(led,LOW);         // led OFF
noTone(buzzer);            // buzzer OFF
}
else{
digitalWrite(led,HIGH);
tone(buzzer,sound);
}
delay(300);
}

Take a look at the example code, in the IDE, named "Blink without delay".

  • Always show us a good schematic of your proposed circuit.
  • Show us good images of your ‘actual’ wiring.
  • Give links to components.

tone(pin, frequency, duration)

An active buzzer should not need tone()..
You can simply use digitalWrite(pinNr, HIGH);

1 Like

Move the delay inside the "else" (when the sensor detects something)

#define led 4    // led at pin 4
#define buzzer 5 // buzzer at pin 5
#define sensor 6 // ir sensor at pin 6
int sound = 400;
void setup()
{
  Serial.begin(9600);
  pinMode(sensor, INPUT_PULLUP); // use this setting or pullup resistor
  pinMode(led, OUTPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  int detect = digitalRead(sensor);
  if (detect == HIGH) {
    digitalWrite(led, LOW);
    noTone(buzzer);
  }
  else {
    digitalWrite(led, HIGH);
    tone(buzzer, sound);
    delay(5000); // move delay inside "else"
  }
}

For active buzzer:

#define led 4            // led at pin 4
#define buzzer 5      // buzzer at pin 5
#define sensor 6      // ir sensor at pin 6
void setup()
{
Serial.begin(9600);
pinMode(sensor,INPUT);
pinMode(led,OUTPUT);
pinMode(buzzer,OUTPUT);
}

void loop()
{

int detect=digitalRead(sensor);   // read status of sensor
if(detect==HIGH)               // if sensor detects obstacle
{
digitalWrite(led,LOW);         // led OFF
digitalWrite(buzzer,LOW);            // buzzer OFF
}
else{
digitalWrite(led,HIGH);
digitalWrite(buzzer,HIGH);
delay(5000);
digitalWrite(led,LOW);
digitalWrite(buzzer,LOW);
}
delay(300);
}

Hi, @flaramel
Welcome to the forum.

To determine if your buzzer is active or not;
Connect it directly to the 5V and gnd supply, if it buzzes or beeps then it is an active buzzer and you only need to activate the controller output to make it work.
If it just makes a single tick noise. then it is not an active buzzer and you will need to use tone or similar to quickly switch it on/off/on/off so it sounds like a beep or buzz.

Tom.. :smiley: :+1: :coffee: