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.)
Here's what I do:
void setup() {
// Timer 1, CTC: 125 kHz carrier:
OCR1A = 31; // This divides the timer frequency -- 8MHz -- by 32*2 = 64
TCCR1A = bit(COM1A0); // Toggle
TCCR1B = bit(WGM12) | bit(CS10);
pinMode(9, OUTPUT);
}
void loop() {
}
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
:
void setup() {
Serial.begin(115200);
while(!Serial) {}
// Timer 1, CTC: 125 kHz carrier:
OCR1A = 31; // This divides the timer frequency -- 8MHz -- by 32*2 = 64
TCCR1A = bit(COM1A0); // Toggle
TCCR1B = bit(WGM12) | bit(CS10);
pinMode(9, OUTPUT);
}
bool firstTime = true;
void loop() {
if(firstTime) {
firstTime = false;
Serial.print("OCR1A "); Serial.println(OCR1A);
// Timer 1, CTC: 125 kHz carrier:
OCR1A = 31;
Serial.println("===============");
Serial.print("OCR1A "); Serial.println(OCR1A);
}
}
Guess what the output was:
22:36:52.768 -> OCR1A 0
22:36:52.768 -> ===============
22:36:52.768 -> OCR1A 31
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.