Skip to content

Commit a444898

Browse files
pfeerickigrr
authored andcommitted
Prevent divide by zero error causing tone() to crash (esp8266#2780)
* Prevent divide by zero error causing code to crash As per the issue at esp8266#2491, there is a divide by error issue resulting from the specification of 0 as the frequency. This does not appear to affect the AVR implementation, but it crashes on ESP8266s. I have merely removed the division if the frequency is zero, which appears to be giving the expected results (no tone), without any code crashes. To test, simply load the toneMelody sketch included with the Arduino IDE (Examples -> 02. Digital -> toneMelody) and change the piezo to something else if you need to. On the Witty module used to test this, I could also tell by the wifi led blinking every time the code crashed as the ESP8266 immediately rebooted. * Use noTone when frequency is zero When a frequency of zero is given to tone(), instead call noTone() and exit. Placed after some of the initialisation stuff to ensure the pin is mapped as a output, etc. Tested as functional against a Node MCU 1.0 board and the toneMelody example sketch, using GPIO5 (pin D1). * Errant tab in formatting * Rest of tabs that crept in from web editor Defaulted to tabs and 8 indent :sigh:
1 parent f18b18d commit a444898

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

cores/esp8266/Tone.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,13 @@ void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) {
6464
// Set the pinMode as OUTPUT
6565
pinMode(_pin, OUTPUT);
6666

67+
// Alternate handling of zero freqency to avoid divide by zero errors
68+
if (frequency == 0)
69+
{
70+
noTone(_pin);
71+
return;
72+
}
73+
6774
// Calculate the toggle count
6875
if (duration > 0) {
6976
toggle_counts[_index] = 2 * frequency * duration / 1000;

0 commit comments

Comments
 (0)