Replacing delay with millis using tone function

Created a siren for a robot car using this code:

#define speakerPin 9

void setup() {
  }

void loop() {
  for (int hz = 440; hz < 1000; hz += 25) {
    tone(speakerPin, hz, 50);
    delay(5);
  }

  for (int hz = 1000; hz > 440; hz -= 25) {
    tone(speakerPin, hz, 50);
  }

}

In an effort to replace the delay function with millis, I tried to apply the Blink Without Delay example. While it compiles & uploads, I'm not getting the same sound effect.

#define speakerPin 9

int durationState = LOW;
int delayState = LOW;
unsigned long previousMillis = 0;
const long duration = 50;
const long noteDelay = 5;

void setup() {
}

void loop() {

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= duration) {
    previousMillis = currentMillis;
    if (durationState == LOW) {
      durationState = HIGH;
    }
    else {
      durationState = LOW;
    }


    for (int hz = 440; hz < 1000; hz += 25) {
      tone(speakerPin, hz, durationState);

      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= noteDelay) {
        previousMillis = currentMillis;
        if (delayState == LOW) {
          delayState = HIGH;
        }
        else {
          delayState = LOW;
        }
      }
      digitalWrite(speakerPin, delayState);
    }

    for (int hz = 1000; hz > 440; hz -= 25) {
      tone(speakerPin, hz, durationState);
    }

  }
}

Welcome

Here is an example : t951856.ino - Wokwi Arduino and ESP32 Simulator

Thanks for the reply & the example, much appreciated. Kind of curious to know what the problem is in my coding though.

But you didn't do it right. The current millis is set each time round the loop and so it never gets past zero.

It is just a blocking piece of code like delay. What were you hoping it would do?

Yeah, it's completely wrong...

I modified the example so it does the same thing as in your first code :slight_smile: : t951856_2.ino - Wokwi Arduino and ESP32 Simulator

Yes, I got that I didn't do it right. :smiley:
I was hoping it would replace the delay functions in the original code and that it would produce the same effects as the original code.

Thankyou, that was very helpful. Much appreciated.