toneAC v1.2 - Twice the volume, higher quality, higher frequency, etc.

Krodal:
The example is okay with the noToneAC() to reset the registers.
Try to remove the noToneAC(), that results in gaps in the sound.
Perhaps the counter has to roll-over ?

I heard something like this once, but couldn't duplicate it so I figured I just had a loose connection.

You're exactly correct on your diagnosis. The counter is "over the top" so it needs to wrap before resuming the sound. This isn't very long when using prescaler 1. But, at 122 Hz and below, prescaler 256 is used which is 256 times longer than prescaler 1 and the reason for the long silence.

Since even more problems can happen when we play notes on each side of the prescaler cutoff frequency, I tweaked your sketch to create a torture test:

#include <toneAC.h>

void setup() {}

void loop() {
  int f = random(50, 124);
  toneAC(f, 10, 0, true);
}

Since it includes frequencies above 122Hz, it sometimes also uses prescaler 1. Also, there's no delay so it just hammers the hell of of things. This sketch should produce a static-like noise as it plays random notes as fast as it can. Instead, it's a bunch of random clicks with periods of silence as it frequently goes "over the top".

After some testing, I've isolated the problem and have a fix. In the toneAC.cpp file after the line that reads "ICR1 = top;" add the following line:

  if (TCNT1 > top) TCNT1 = top;         // Counter over the top, not good, put within range.

With this, the above sketch now produces what you'd expect, static. During early development, I set TCNT1 = 0 when starting a tone. That works fine for high frequencies, but poorly at lower frequencies and when changing notes (creates clicks). It's even worse when driving a two-pin dual LED at ultra low frequencies (like at 2 Hz). Adding the noToneAC() in your sketch works because when TCCR1A resets the PWM it automatically sets the counter to zero. While this works, it's not ideal for the above reasons of setting the counter to zero can cause other problems.

In any case, the above line fixes things and I've added it to the development version which will be released in version 1.2.

On a side note, the volume setting doesn't really work well for low frequencies. It doesn't do much to change the volume and lowers the quality (makes it buzzy). I'd suggest to always use 10 for the volume, which keeps the quality high. Only use a lower volume if it's a requirement.

Anyway, thanks for the catch! And leading me in the right direction with the fix.

Tim