I just made a sketch using simple code to make a buzzer output a tone (based on the 'blink' and the 'blink without delay' examples). However when I connect the buzzer to the arduino the sound is quite different depending on which function I use. By using the 'blink method', the beep is quite clear, but with the 'blink without delay method' it's quite different and even seems to be beating. Why is it so? The plan is to use this in a later project by having an analog input change the tone of the buzzer, but without the delay function to interfer with the the analog readings.
So what's causing this difference in sound?
#define outPin 7 // Pin connected to buzzer
#define inPin A0 // not used
long previousMillis = 0;
byte pinState = LOW;
void setup(){
pinMode(outPin, OUTPUT);
}
void loop(){
withoutDelay(10); // Specify the periode
//withDelay(10);
}
void withoutDelay(int interval){
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > (interval / 2)) {
previousMillis = millis();
if(pinState == LOW) pinState = HIGH;
else pinState = LOW;
}
digitalWrite(outPin, pinState);
}
void withDelay(int interval){
digitalWrite(outPin, HIGH);
delay(interval / 2);
digitalWrite(outPin, LOW);
delay(interval / 2);
}