I'm curious to know if it's possible to measure the CPU clock speed of an Arduino board, ESP32, ATtiny, or any other MCU using Arduino code itself. I'm not looking for a Pin like the ATtiny x16 has (CLKO); instead, I'm interested in more of a "reverse engineer" approach.
Is this even possible or complete nonsense? I'm thinking of toggling a GPIO pin at a known frequency and using this frequency to calculate the CPU clock speed. I plan to measure this using an oscilloscope and would appreciate any insights or basic examples to help me get started in understanding this concept better.
But then it's no longer the Arduino board all by itself, is it?
Having said that - sure, you can toggle a GPIO and measure the frequency. You just have to figure out whether the measurement device has a better accuracy than the +/-40ppm or so of a typical microcontroller crystal.
A relatively simple way of doing this is by using an RTC (real time clock) module and letting an Arduino count milliseconds for a day or so. Record the time from the RTC at the start of that day and at the end of the day, and compare both of them. While simple, the problem is that you're still left with the accuracy question above. But it'll teach you something, at least.
I have some code for a 328p that I came across that could estimate the processor clock. I'm not at my PC right now but I will post the code later.
I seem to recall it used one of the timer/counters to count the CPU clock - probably via a prescaler - and used the watchdog timeout as a crude fixed time reference. By examining the count after the WDT timed out, it could estimate the processor clock.
How does the WDT keep track of time? Doesn't that rely on an internal R/C oscillator, which is orders of magnitude less accurate than the HSE oscillator?
A very accurate approach to measuring the CPU clock speed is to use the 1 pulse per second output of a GPS module with a valid satellite lock as the time base. That is accurate to a nanosecond or two, so you can count CPU clock pulses (incrementing 16 bit Timer1) to an accuracy of a few Hz.
Yes, but it's separate from the main CPU clock and you can configure it's timeout. It's not that accurate - it's not meant to be - but it's good enough to give you a frequency to within 1MHz if the crystal.
Are you looking for an indication of clock speed, perhaps to determine if you had an 8MHz 328p or a 16MHz 328p, or some way of measuring to within 100Hz or so?
Oh, I see what you mean; yes you could use the WDT to determine clock speed, approximately. I was thinking about scenarios to determine the accuracy of the CPU clock. Good call.