Verifying clock speed of ATmega328p via code

Hello,

I have for the first time setup an ATmega328p on a breadboard. I haven’t burned the arduino bootloader to it, but I have set the fuses to the default fuse configuration for Arduino Uno boards.

The program I upload via the arduino IDE works just fine too!

My question is how to verify the clock speed. I am quite certain my controller is running at 16Mhz (I am using an external crystal), but I want to know if there is a way that I can verify this, preferably via code.

I had thought about using the delay function, but I can’t seem to work out the logic. I figure if the controller is actually running at 8Mhz, the delay function would still work as expected.

Any ideas?

Run the Blink example sketch. If the LED is on for about one second, then off for about one second, then no doubt the system clock is 16MHz.

If the mcu was set to use it’s internal 8mhz clock, would the blink example not yield the same result? Wouldn’t I only see a mismatch if I had set the fuse to use one clock setting, and it was actually getting a faster/slower signal?

System clock frequency is supplied as a compile-time parameter (F_CPU). This is specified in the boards.txt file, which also drives the Tools > Boards menu in the IDE.

System clock frequency is not somehow determined from the hardware at compile time or at execution time, it is a given value at compile time.

So when I select Tools > Boards > Arduino Uno, the compiler is told that the clock is 16MHz. If this doesn’t match the actual hardware that I connect, then timings will be off by the ratio of the given vs. actual clock frequencies.

If I connect a board with an 8MHz clock and tell the IDE that it’s an Uno, then the Blink sketch will blink the LED on for two seconds, off for two seconds. (In this situation, whether I can actually program the board via the bootloader is questionable, since the bootloader baud rate is also given in boards.txt, can be different for different bootloaders, and also is calculated from the system clock frequency. But in any event, I could program the board via ICSP.)

1 Like