I am using Arduino Pro Mini with Atmega328P, 3.3V, 8MHz. I need it to generate permanently a 125kHz square wave. For that, I use the 16-bit Timer1 in the CTC mode with output to OC1A connected to pin 9. (Why the 16-bit timer? Because Timer0 is used by the core for micros(), and Timer2 uses either the MOSI or INT1 pins, which I need for something else.)
This is supposed to generate what I need, but instead I get a wave of about 4MHz, no matter what value I put into OCR1A. It was very puzzling and frustrating.
Eventually I decided to check what was the actual value of OCR1A:
I assumed originally that the Arduino core was at fault by nullifying register OCR1A in between setup() and loop(). But @van_der_decken kindly advised that this was done by writing to TCCR1A, thank you! I believe this was not documented in the datasheet.
Section 16.7. At the bottom of page 124 in the copy I have. Right under figure 16-4
The OCR1x Register is double buffered when using any of the twelve Pulse Width Modulation
(PWM) modes. For the Normal and Clear Timer on Compare (CTC) modes of operation, the
double buffering is disabled. The double buffering synchronizes the update of the OCR1x Com-
pare Register to either TOP or BOTTOM of the counting sequence.
It wasn't being zeroed. It was buffered and hadn't changed yet. When you switch to CTC mode the buffering got turned off so it never got loaded.
Another thing to be careful with when using CTC mode is that if TCNT1 is ahead of OCR1 when you set it then you have to wait until the timer wraps all the way around before your pulse starts. Usually I zero out TCNT1 on the line immediately before or after I set OCR1.
This is especially important when setting OCR1 to small values like you are.