sensorium / Mozzi

sound synthesis library for Arduino
https://sensorium.github.io/Mozzi/
GNU Lesser General Public License v2.1
1.06k stars 185 forks source link

Output frequency 0.25% off on AVRs #201

Closed tomcombriat closed 10 months ago

tomcombriat commented 10 months ago

Hi, Just reporting here something that has been said on the forum: when playing a simple oscillator at a given frequency on an AVR board, the output is slightly off, to be precise it is too low by 0.25% from my tests.

This is not a lot, but it is hearable when playing when other very in-tune digital instruments.

Looking at the timer for AVR source code:

Timer1.initializeCPUCycles( F_CPU / AUDIO_RATE,

should only be off by (16e6/32768 - int(16e6/32768))/32768 = 0.0576%, five times less!

So if anyone has an idea!

tomcombriat commented 10 months ago

Maybe a quick fix:

changing Timer1.initializeCPUCycles(F_CPU / PWM_RATE, to Timer1.initializeCPUCycles(F_CPU / PWM_RATE-1, on line 204 of MozziGuts_impl_AVR.hpp reduces the difference to 0.0625%.

Do not really understand why this would be the correct formula but it seems to make things quite closer to the expected values. Of course, other parts of this same file should be changed in the same way. Ideally, if it could be reproduced by someone I would commit a patch, being more sure that there is not flaw in my measurements.

Best,