The BUZ doesn't beep in setup

Hi every one.
The sketch below, the BUZ doesn't beep when put into setup, beep when put into loop, why?
Thanks
Adam

const int buzzer = 12;
const long onDuration = 10;// OFF time for LED
const long offDuration = 5000;// ON time for LED
int BUZState =HIGH;// initial state of LED

long rememberTime=0;// this is used by the code

void setup() {
  // put your setup code here, to run once:
 pinMode(buzzer,OUTPUT);// define buzzer as output
  digitalWrite(buzzer,BUZState);// set initial state

  // Robojax LED blink with millis()

 //  BUZloop(); /// doesn't beep
}

void loop() {
  // put your main code here, to run repeatedly:
  BUZloop();  /// beep
}

void BUZloop() {
  // Robojax LED blink with millis()

 if( BUZState ==HIGH )
 {
    if( (millis()- rememberTime) >= onDuration){   
    BUZState = LOW;// change the state of LED
    rememberTime=millis();// remember Current millis() time
    }
 }
 else
 {   
    if( (millis()- rememberTime) >= offDuration){     
    BUZState =HIGH;// change the state of LED
    rememberTime=millis();// remember Current millis() time
    }
 }

 // Robojax LED blink with millis()
 digitalWrite(buzzer,BUZState);// turn the LED ON or OFF

}// loop ends 

Replace that line in the setup with

1 Like

Thank you Grumpy_Mike.

How do you know?

How can you tell if the noise is coming from the first call in setup and not the calls in loop?

So after calling it in setup, follow it with a three second delay before ending the setup function. Then there should be a sound, then three seconds later you enter the loop function.

1 Like

Thanks.
Yes, I guess it is the noise.

BTW. this sketch control the buz on/off time, is there any other code does this function please?
Best

Like in all of writing code there are many ways of doing this but at the end of the day you just need to present an alternating high and low on the output pin.

The way you have used millis() to define the delay is no difference from using a delay function at all.

However try this:-

void BUZloop() {
 If( (millis() & 0x400) == 0){
   digitalWrite(buzzer,LOW);
}
else {
 digitalWrite(buzzer,HIGH);
      }
 }

This will allow you to do a bit of multitasking. As long as any other stuff in your loop function is over in about half a second or so, this will keep bleeping at the same rate. This will be half a second on and half a second off.

1 Like

Great!
Thank you.
Actually what I'm looking for is a code that control the ON and OFF time separately?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.