Play Piezo Buzzer without delay

How can I make a piezo buzzer play without delay?

This is my current approach but it doesn't function.

What I'm trying to do is wait 5 seconds, play sound, stop sound after 1 second

unsigned long Timer1 = 0;
unsigned long Timer2 = 0;

boolean hitObs = false;

boolean sPlay = false;


void loop(){

  unsigned long currentMillis = millis();
  
  if(currentMillis-Timer1 >= 5000){
    Timer1 = currentMillis;
    Serial.println(currentMillis);
    sPlay = true;
    analogWrite(speakerPin,20);
  }
  
  if(currentMillis - Timer2 >= 1000 && sPlay){
    Timer2 = currentMillis;
    Serial.println(currentMillis);
    sPlay = false;
    analogWrite(speakerPin,0);
  }
  
}

BruceBerrios: How can I make a piezo buzzer play without delay?

A passive piezo speaker that needs to be driven by a tone frequency?

Try that:

const byte speakerPin=9;
unsigned long lastPeriodStart;
const int onDuration=1000;
const int periodDuration=6000;

void setup()
{}

void loop()
{
  if (millis()-lastPeriodStart>=periodDuration)
  {
    lastPeriodStart+=periodDuration;
    tone(speakerPin,550, onDuration); // play 550 Hz tone in background for 'onDuration'
  }
}

Thank you!

hello... i was wondering can you help me with the code.. i tried using the code and modified it so that it can produce 2 tone but it becomes weird ! the frequency keeps on repeating itself. i need buzzer code without delay function that can produce two tone and stop . i tried putting it on setup () but it doesnt produce any tone. im very new to arduino :(

const byte speakerPin=9; unsigned long lastPeriodStart; unsigned long lastPeriodStart1; const int onDuration=1000; const int periodDuration=1000;

void setup() {}

void loop() { if (millis()-lastPeriodStart>=periodDuration) { lastPeriodStart+=periodDuration; tone(speakerPin,1340, onDuration); // play 550 Hz tone in background for 'onDuration' } else if(millis()-lastPeriodStart1>=periodDuration) { lastPeriodStart1+=periodDuration; tone(speakerPin,1100, onDuration); }

}