Go Down

Topic: Tone.cpp improvement (Read 2070 times) previous topic - next topic

robtillaart

Jan 12, 2013, 11:46 pm Last Edit: Jan 12, 2013, 11:58 pm by robtillaart Reason: 1
Searching through some core code I came across the tone lib and especially the function:

Code: [Select]
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)

This function tries to find an optimal prescaler for the timer. To do that it calculates the OCR  = F_CPU / frequency / 2 / SomePrescaler -1  nine times.
Because division is expensive I took an extra variable uint32_t ocrRaw = F_CPU / frequency / 2;  which is the repeating part of the formula
and replaced that in the rest of the function.

I tested with ToneKeyboard.pde sample sketch to see the impact on the size.
before patch => 3614 bytes
after patch => 3526 bytes
improvement == 88 bytes!

I did not test speed, I expect it to be slightly faster (no free Arduino nearby to test)

Disadvantages?
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

robtillaart

Posted as improvement - https://github.com/arduino/Arduino/issues/1220 -
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

teckel


Searching through some core code I came across the tone lib and especially the function:

Code: [Select]
void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)

This function tries to find an optimal prescaler for the timer. To do that it calculates the OCR  = F_CPU / frequency / 2 / SomePrescaler -1  nine times.
Because division is expensive I took an extra variable uint32_t ocrRaw = F_CPU / frequency / 2;  which is the repeating part of the formula
and replaced that in the rest of the function.

I tested with ToneKeyboard.pde sample sketch to see the impact on the size.
before patch => 3614 bytes
after patch => 3526 bytes
improvement == 88 bytes!

I did not test speed, I expect it to be slightly faster (no free Arduino nearby to test)

Disadvantages?



Or, just replace the entire tone library with NewTone and save almost 1200 bytes.

Tim
My hardware: Arduino, Teensy 2.0, Teensy 3.2 & custom ATmega328
My libraries: NewPing, LCDBitmap, toneAC, toneAC2, NewTone, TimerFreeTone
My Projects: https://dogblocker.com & https://baconorbeer.com
My beer: Great Lakes Brewing Co. Lake Erie Monster

robtillaart

There are always other options, Tim!
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up