Strangeness with Tone

Status
Not open for further replies.

macaba

Well-known member
Code running on Teensy 3.6:
https://gist.github.com/macaba/33813b083b226fead09bfc127f83d7a2

It's so simple, I'm sure I'm missing something obvious...

The sketch as-is won't output any tone (but the Serial output shows valid frequency numbers). If you uncomment line 17 and comment out line 16, it'll give a [fixed frequency] tone. Why doesn't the sketch as-is work?

(I also tried AnalogWriteFrequency and get the same issue)
 
Figured it out - passing a frequency of 0 creates some kind of unrecoverable fault. Coercing to 1 or higher fixes it.
 
That’s quite logical behavior. Setting a frequency means using the bus clock divided by the frequency as a timer mod value proportional to the signal period. And division by 0 is not too amusing for a small microcontroller...
 
Logical; for sure. Good behavior; certainly not.

Once 0 has been set once, it seems any positive integers after this point don't work. This would be ok if documented but it's not in the GitHub source or the PJRC page.
 
The avr version of Tone.cpp constrains frequency to within a MIN and MAX (dictated by hardware). teensy3 version of Tone.cpp has no check on frequency, and value of 0 will result in divide by zero. Probably limit minimum frequency to 1
 
Yup, I've "fixed" this by just disallowing zero. Instead you get 1 Hz.

https://github.com/PaulStoffregen/cores/commit/bb72c33d14e5829f11a07836bf60f484a8f81996

I briefly considered supporting DC. But that would make all the code much more complex, especially when tone() is used with the 3rd parameter for duration.

Turns out Arduino Uno clamps the minimum to about 31 Hz, which makes me feel much better about not being able to go all the way down to DC.
 
Status
Not open for further replies.
Back
Top