Creating Buzzer Tones and Conflict with Blynk (delays)

Hi all,

I have a buzzer connected to my nodemcu and I want to generate different “tones”, something like this:

void warning_tone()
{
  for (byte j = 1; j <= 3; j++)
  {
    for (byte i = 1; i <= 12; i++)
    {
      digitalWrite(BUZZER_PIN, HIGH);
      delay(i*10); 
      digitalWrite(BUZZER_PIN, LOW); 
      delay(i*10); 
    }
  delay(1000);
  }
}

We all know that delays are forbidden when using Blynk.
I do need BLYNK to be alive during the tone.
I need some ideas on how I could implement such a mechanism for 2-3 different tones.

Thanks, Andreas

Not really a Blynk related issue :wink: but the dreaded "NO delay()", can confuse new Arduino users… so …

Use PWM analogWrite() instead of any convoluted for loops.

https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

Thank you Gunner for your time.
I think the no delay() is something important for all Blynk users so this cannot harm.

I do believe that if you try to make a variable tone in time (not a constant one - something like a melody) then you have to call digitalWrite() or analogWrite() in specific times in order change the tone and the melody to have a “constant” rhythm. Problem is that if put Blynk.run() between the “frequency changes”, this adds a delay that is not always constant (as blynk.run() execution time varies from call to call ) and this changes the tone all time.

The issue is not very important but I would like to know if somebody already found a workarraound,

Thanks
Andreas

Did you try the analogWrite()?

You didn’t mention the MCU type, but Arduino does have very limited tone generator code… sharing timing with Blynk (or any constant WiFi link) will ALWAYS be an issue, but should be no problem for simple beeps and tones.

Longer “music” or tunes can be processed with MCU controlled standalone players pulling data from SD cards.

MCU = nodemcu.

You gave me the idea of an external device handling that.

thx
Andreas

1 Like