3
\$\begingroup\$

Is there any easy easy way to play tones on a piezo buzzer with the Arduino other than the built in tone() method? I only need to call it a couple of times, but I notice that when I use it there is an extra 1256 bytes added to the output size! I realize that on a normal Arduino this would't be a whole lot out of the 16KB available, but I'm trying to do this on the ATTinyX5 series. I'm currently using a t45 but would like to be able to use the t25 if at all possible and that extra 1256 bytes puts me well over the 2048 byte limit.

Thoughts?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

There's the Melody example on the Arduino site that just uses digitalWrite to quickly toggle the I/O pins:

void playTone(int tone, int duration) {
  for (long i = 0; i < duration * 1000L; i += tone * 2) {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
  }
}

The main disadvantage to this over other methods such as using a timer output is that your code will be stalled while the tone is being played, and if you have background interrupt activity occuring you may end up with a few anomalies in the tone.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.