Weird TIMER1 behavior (simple square wave using interrupt)

Hello all,
I’m writing here after a lot of unsuccessful tests on what should be a VERY simple task: making a 38 kHz square wave using TIMER1 on a UNO board. After reading a lot of (but very scattered) information regarding TIMER1 features, I ended with these conclusions:

  • choose TIMER1 for this purpose;
  • use CTC on compare match;
  • setup OC1A pin in toggle mode.

With this configuration, it should be possible to have a square wave on OC1A pin (Arduino pin 9) even without calling any ISR. Indeed here’s my code on setup() section:

  // timer1 initialization
  noInterrupts(); // disable all interrupts
  TCCR1A = 0;
  TCCR1A |= (1 << COM1A0);             // setup OC1A pin in toggle mode
  TCCR1B = 0;
  TCCR1B |= (1 << WGM12);              // clear timer/counter 1 on compare match
  TCCR1B |= (1 << CS10);               // no prescaler (timer clock = system clock)
  TCNT1 = 0;                           // reset counter
  OCR1A = 210;                         // set value on TCNT1 for given IR frequency (AVRCLOCK/IRFREQUENCY/2)
  TIMSK1 |= (1 << OCIE1A);             // enable timer compare interrupt
  TIFR1 = (1<<OCF1B);
  interrupts();                        // enable all interrupts

On main() section the program simply does nothing. Capturing the signal on pin 9 (with a DSO) I obtain a signal which doesn’t have a 38 kHz frequency, doesn’t have a 50% duty cycle (as I was expecting) and, above all, has this strange waveform: Capture — ImgBB
Obviously, I’m missing something… but what? Can someone help me in this fairly simple task?
Thanks in advance.
Gabriele.

TIMSK1 |= (1 << OCIE1A);

Why are you enabling this interrupt? Where’s your ISR?

In fact I don't exactly know why should I enable interrupts: I don't need an ISR (and there isn't any ISR routine on my code) because the toggle function on OC1A pin (Arduino pin 9) is all that I need for generating a square wave: it toggles at every compare match between counter 1 and OCR1A register. Do you think I only need to disable that flag? Thanks in advance.

gabrielebellini: Do you think I only need to disable that flag?

I don't know. Try it.

gfvalvo: I don't know. Try it.

You're right! Resetting that flag prevented the (useless) ISR call and thus the unexpected waveform disappeared! Now I have the correct frequency, duty cycle and waveform! Thank you so much!!!!