I have an issue that I can't solve so any help is appreciated!
The code includes a function with two variables (number of repetition and duration).
The idea is for the active buzzer to play a different sequence depending on the character ('p' or 's') that is entered in the serial monitor by the user.
However, this doesn;t work as indented. If I press "p" or "s" I get a continuous beeping until I press again the same key where it stops beeping. More like an ON/OFF toggle.
I also included a wokwi but with a LED instead of an active buzzer but the begviour is the same of course. Thanks!
const int buzzerPin = A5; // Pin that the buzzer is connected to
char pyInput;
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
void setup() {
Serial.begin(9600);
pinMode(buzzerPin, OUTPUT); // Set Buzzer Pin A5 to OUTPUT.
Serial.println("Hello Arduino\n");
}
void loop() {
if (Serial.available() > 0) {
pyInput = Serial.read();
switch (pyInput) {
case 'p':
buzzerBeep(2, 300); // Beep once for 300ms
break;
case 's':
buzzerBeep(8, 80); // Beep 4 times for 80ms each time
break;
}
}
}
// Function for buzzer's sequence/ beeps
void buzzerBeep(int rep, long buzzer_interval) {
static int buzzer_toggleCount = 0;
static int buzzer_currentState = LOW;
if (buzzer_toggleCount < rep) {
currentMillis = millis();
if (currentMillis - previousMillis >= buzzer_interval) {
if (buzzer_currentState == LOW) {
digitalWrite(buzzerPin, HIGH);
buzzer_currentState = HIGH;
} else {
digitalWrite(buzzerPin, LOW);
buzzer_currentState = LOW;
}
previousMillis = currentMillis;
buzzer_toggleCount++;
}
}
}