Electronic – XMega Get Clock Speed

avrclockclock-speedcrystalxmega

I'm doing some debugging on my project and I need to check if I'm setting my external crystal correctly. I have the ability to print out to a serial monitor via usb,
is it possible to retrieve the Clock Speed and whether or not the cpu is running off the internal clock or an external crystal so I can print that out?

Best Answer

You can measure the current CPU Clock speed by using the internal Real Time Clock driven by the 32.76kHz local oscillator. I don't have an XMEGA handy at a moment so I can not give exact procedure, but the general idea is to set up the RTC to measure some fixed amount of time (say 1ms), and then measure how many clock ticks occur during that time period using one of the 16 bit Counter/Timers. If, say, you count 8,044 ticks during a single 1ms RTC cycle, then your CPU clock speed is 8044/1ms= ~8Mhz.

You can check if you are running off of an internal or external clock by looking at the System Clock Selection (SCLKSEL) bits in the Clock Control Register (CTRL).