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);
}
}
}