# tone() and PWM limits

I'm developing an active sonar using Costas arrays and Golomb rulers. I need the Arduino to switch between frequencies very quickly to shorten the length of the ping, both to improve processing and to lessen speed of sound limitations. I also need to know the exact times each frequency will be released from the Arduino so the real time computer can ignore those frequencies.

I'm able to generate the melodies I want using the `tone()` command, but I couldn't find the time required to change frequencies or the standard deviation of that time. I'm also not sure what the minimum length of PWM is.

So I want to know, what is:

• The switching time for changing PWM frequencies
• The standard deviation of that switching time
• The minimum length PWM pulse that can be generated
• The standard deviation of the length of that minimum PWM pulse.

And how might I achieve those minimums?

• 1,2; You could be able to change the frequency in something like 4 instructions, but tone has quite a bit of overhead. But it should still be pretty fast. Though you could write your own optimize code, setting the prescaler and OCRx registers. 3; Highest frequency is something like half of 16Mhz, so 8Mhz. Maybe even higher using PLL. – Gerben Oct 12 '14 at 18:41
• The number of instructions does not equal the switcing time... well, maybe if they're assembly instructions, but even then, the hardware has to react to the cpu. And highest frequency doesn't necessarily equal the minimum length PWM, that would be the period; if I can stop generating PWM after less than one wavelength, then the PWM's length is smaller than the wavelength, and same if I have to wait more than one wavelength to stop it. – SimLeek Oct 12 '14 at 18:58
• In `PWM, Phase Correct` mode you can update the OCRA and OCRB values while it is running. It will buffer those values and only update them and the end on the "cycle". That way no "half-tone" is ever generated. Since you are talking about tone generation I was assuming 50% duty cycle. Or did you mean duty cycle when you said `minimum length PWM`? – Gerben Oct 13 '14 at 18:57
• Yeah, 50% duty cycle is correct. So the minimum length of PWM is almost exactly its period? – SimLeek Oct 13 '14 at 21:40
• If you pre-calculate the values you need, and arm an interrupt to change on the next edge, then for anything up to a few hundred KHz you should be able to load the new values into the registers before that count is reached, yielding the fastest frequency change theoretically possible with a rectangular waveform. It's been a while since I looked at the details, but you may need to pre-load the total count register during the the cycle preceding the one in which you want to change it. For better results, one would think you would want a sinusoidal synthesizer. – Chris Stratton Oct 14 '14 at 15:37