Problem with speed, working slower than it should


I have an Arduino Uno clone that I purchased to start learning.

Installed ok, and I uploaded my first sketch fine.

The sketch is a 24hs countown timer, available here:

24 hour countdown timer

Everything was looking good until I noticed the seconds felt a little slower, so I compared with a real clock, and yes, it was a lot slower. The arduino took 750 seconds to count 600 real seconds (1.25 slower) I realized that it was the exact difference between 20Mhz and 16Mhz (20/16=1.25)

So I moved the Atmega328p with the code to a breadboard and I installed a 20Mhz crystal, and the countdown started working fine.

I would like to know what is wrong.

Maybe the fuses are set for 20Mhz but the resonator installed is 16Mhz? that would explain this?

Or it has to do with the bootloader?

I want to know if I can correct this. The resonator on the board is very small, it would be very difficult to replace with a 20mhz part as I did in the breadboard.



Instead of muddying the waters with that display, write time directly to Serial Monitor and see what it shows.


They're not using millis() for timing in that sketch - just relying on a delay() at the end. My guess is that they didn't properly account for the execution time of the code. I notice that their comments don't match the lengths of the actual delay, which is always a red flag (aka "code smell")

Unless you have selected a board definition that spec's 20MHz processor speed (have you? If so why?), the problem is a bug in the code.

I would not expect that code to give reliable results, since different versions of the IDE (with different compiler versions making different optimizations) or different boards would run the code outside of the delays at a different speed; it should be rewritten to use millis() for timekeeping.