I am new to programming in general and to Arduino as well. I am working on a small project to improve my ability to write complete and kind of useful programming sketches.
I am facing a problem. I am using a few things in my circuit like 7-segment display and relays and several indicating LEDs and a buzzer.
Let's sat that when a condition occurs I want one LED to blink while everything still works fine and sends data to the display and controls relays, and I solved that with the millis
function.
But the problem came when I tried to implement the same concept to the buzzer (which in my case I want to buzz for a pre-set amount of time, and then stop, without keeping buzzing all the time which might be too long), without using the delay
function.
I tried many many code but nothing would work for me so far. Here is the simple code of my sketch. I hope you guys will help me find a solution
const byte buzzer = 13; // buzzer_PIN
const byte switch1 = 3; // PUSH-BUTTON PIN
/* please NOTE:
that the switch in my project will actually represent a condition to start the buzzer alarm, then maybe that condition will not exist, and after that the condition might come back and need the buzzer again
*/
unsigned const int delaytime = 500; // delay time needed between on and off states for the buzzer
unsigned long previousBuzz = 0; // Variable for millis
unsigned long currentTime = millis();
boolean buzzPreState = true; // Boolean made to avoid repetition for the buzzer when not needed
void setup() {
pinMode(buzzer,OUTPUT);
pinMode(switch1,INPUT_PULLUP);
}
void loop() {
unsigned long currentTime = millis();
int switchVal = digitalRead(switch1);
if (switchVal == LOW && currentTime - previousBuzz > delaytime && buzzPreState == true) {
previousBuzz = currentTime;
buzzPreState = false;
buzzerStart(5);
buzzPreState = true;
}
}
void buzzerStart(int repeat) {
for (byte i=0; i<repeat; i++) {
digitalWrite(buzzer, !digitalRead(buzzer)); // to switch buzzer ON and OFF alternatively
}
}
tone()
function where you can specify the duration. it doesn't block execution. arduino.cc/reference/en/language/functions/advanced-io/tonebuzzerStart()
? Doesn't make much sense to me. An active buzzer just has to be turned on and off (viadigitalWrite()
). So you could replacebuzzerStart(5)
with a singledigitalWrite(buzzer, !digitalRead(buzzer);