I have a project that needs to generate a ~130kHz square wave and noticed the wonderful tone() function would do it. It looks, however, that there is some issue and I was wondering if anyone else has used it.
What I am seeing are two issues, and I think they are related to the library casting the frequency as 16bit unsigned int. The odd thing is the way the device acts with the larger data values.
These all assume a large frequency (above 65535, although I am doing everything with ~130000)
1. If the duration value is used, it has no effect on timing, but it seems to reduce the amplitude of the wave. I don't have a oscope, but I am using this with a piezo transducer and water and the result is a "very weak mist". I suspect that the value passed is causing a crash somewhere that leaves the tone playing. For odd.
2. Even if I remove the duration and use a subsequent delay and noTone(), the mist is very weak unless the tone function call is immediately followed by an analogWrite() to some other pin. I use pin1 for my tone and 0 as the analogWrite call. Not sure what about that write changes anything on pin1, but it does.
For example:
void loop(){
tone(1,130000,1500);
delay(10000);
noTone(1);
}This should "play" the tone for 1.5s, then sleep for an additional 8.5s and then repeat. It doesn't. It emits a weak, but continuous stream of mist.
void loop(){
tone(1,130000);
delay(1500);
noTone(1);
delay(8500);
}This should "play" the tone for 1.5s, then sleep for an additional 8.5s and then repeat. It does, sort of. It emits a weak mist for 1.5s and then sleeps and repeats as expected.
void loop(){
tone(1,130000);
analogWrite(0,64);
delay(1500);
noTone(1);
delay(8500);
}This should "play" the tone for 1.5s, then sleep for an additional 8.5s and then repeat. It does, I just don't understand why.
FYI, for playing lower frequencies, ie. audible tones, all behaviors are as expected. Any thoughts?