Go Down

Topic: Tone.cpp improvement (Read 1 time) 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)


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
Arduino - Teensy - Raspberry Pi
My libraries: NewPing - LCDBitmap - toneAC - NewTone - TimerFreeTone

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
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy