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
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.
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.
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.