Timer2, CTC, OCR2A doesn't work as expected

Hello everyone,
I'm new to this forum and would like to ask for help. I'm trying to bring OCR2A to work but I'm lost. Using Arduino Nano.
Task: INT0 will receive a falling edge every 26us for about 63 periodes.
I would like to measure the cyle time with an accuacy of 1 us and expect values about 1638 us.
I got always a measurement of 8us.

volatile uint32_t startCnt = 0;
volatile uint32_t endCnt= 0;
volatile uint8_t flgPuls = false;
volatile uint8_t flgMsg = false;

#define OC2A_PIN       PB3          // D11
#define INTERRUPT_PIN  PD2          // D2

void setup() {
  Serial.begin(115200);
  pinMode(OC2A_PIN, OUTPUT);        // OC2A pin: D11
  pinMode(INTERRUPT_PIN, INPUT_PULLUP);      // Interrupt input D2

  // Timer 2
  TCCR2A = 0;
  TCCR2B = 0;
  TIMSK2 = 0;
  TCNT2 = 0;                        // reset counter to zero

  TCCR2A |= _BV(COM2A0);            // Toggle OC2A on Compare Match  
  TCCR2A |= _BV(WGM21);             // CTC mode  
  TCCR2B |= _BV(CS20);              // Prescaler = 32, -> 2us
  TCCR2B |= _BV(CS21);              // Prescaler = 32, -> 2us
  
  OCR2A = 15;                       // Output Compare Register A: 15 * 32 * 0,0625us = 30us
 
  
  EICRA |= _BV(ISC01);              // Falling edge on INT0 generates an interrupt
  EIMSK |= _BV(INT0);               // Enable INT0 interrupt 

  Serial.print(F("F_CPU="));
  Serial.println(F_CPU );
  Serial.println(F("running"));
}

ISR(INT0_vect) {                    // Interrupt INT0 ocurred every 26.4us
  TCNT2 = 0;                        // reset counter to zero
  TIMSK2 |= _BV(OCIE2A);            // OCIE2A: Enable Timer/Counter2 Interrupt 
  if(flgPuls == false) {
    startCnt = micros();
    flgPuls = true;
  }
}

ISR(TIMER2_COMPA_vect) {
    endCnt = micros();
    TIMSK2 &= ~_BV(OCIE2A);         // OCIE2A: Disable Interrupt 
    EIMSK  &= ~_BV(INT0);           // Disable INT0 interrupt 
    flgMsg = true;
}


void loop() {
  if(flgMsg == true) {
    flgMsg = false;
    Serial.print(F("measure="));
    Serial.println(endCnt - startCnt);
  }
}

F_CPU=16000000
running
measure=8

It's also strange for me, that the OC2A_PIN will never change.

Do something first that works and then play wit TC2 etc.

Generate exacltly 63 pulses (ontime 13 us and Offtime 13 us) over DPin-4 (say) and use them to interrupt the MCU over INT0-pin; count the number of inerruptions (n) and then dsiplay nx26 (= 1638) on the display.

micros() on the Arduino Nano has only 4 µs resolution.You always read 8 µs because micros() updates every 4 µs. Your code measures interrupt latency, not pulse duration.Timer2 never reaches OCR2A because INT0 keeps resetting it. The compare interrupt almost never fires. Timer2 is also too small for a 1.6 ms measurement. Do not use micros() for 1 µs accuracy. Use Timer1 as a free-running counter instead. Set Timer1 prescaler to 8 for 0.5 µs ticks. Start Timer1 on the first falling edge. Stop it on the 63rd falling edge and read TCNT1.

So, tC1 is running @16000000/8 Hz. Is tere anyway to bring that frequency out?

OP wants that an external interrupting signal of 26 us period (assume square wave) which will interrupt the MCU over INT0-pin on the falling edge.

Thank you for the explanatin. I didn't know that micros() has this behavior. I'll try to use Timer1.
The challenge is that I didn't know how many falling edges I will get. The only thing I know is: if there is no further falling edge after 26us the package is complete.


This is the start of a long signal (IR sender of a remote control) I want to decode. At the end I need to measure the pulse packages AND the gaps between them. My first approach was to measure the first pulse package which failed.

You want to receive and decode an IR signal coming from a Remote Control which yu have not told before except now.

First of all, you need to know the structure of an IR signal (Fig-1, demodulated from 38/40 kHz carrier for Sony CD remote control (RM-DC335)). There is a long gap. Tell your program to search for that gap and then you statrt counting the pulses. The 40 kHz carrier signal (not shown in Fig-1 which is a decode signal) is there when the signal is at HIGH level.


Figure-1:

Header: 2400 us

Bit-1: 600 us Off and 1200 us On

Bit-0: 600 us Off and 600 us On

Inter-fram (silence) gap = 45 ms

Command Bits: 7 after Header (LSBit first) . It tells about a particular coomand for the Device. For example:

Device Bits: 5 after command bits. These bits specify the type of Device. For example: 17 (10001) for CD Player.

Link: Understanding Sony IR remote codes, LIRC files, and the Arduino library

The best way to do that with AVR Arduinos is to use the Input Capture function of Timer1. Tutorial here (scroll down to "input capture unit"). The highest accuracy possible is 1/16 microseconds, or 62.5 ns, on a 16 MHz Arduino.

An interesting library that I wasn't aware of before. I'll examine it to see if it's suitable, as my remote control isn't from the consumer electronics sector. But I'm sure the detailed article contains valuable information.
I have already received some initial help, namely that micros() does not count microseconds in this case.
I also will dive into the Input Capture of the ATmega328.

Even though there are great libraries, I would like to understand why my code isn't working.
The intention was:

  1. A rectangular signal is present at the INTERRUPT_PIN: 38kHz, i.e., every 26us the falling edge triggers an INT0.
  2. Timer 2 runs at 2us and should generate a TIMER2_COMPA interrupt at 30us.
  3. Timer2 will never trigger during the entire pulse packet. This is intentional.
  4. Only when the pulse packet ends, i.e., when INT0 is no longer firing, does Timer2 have the chance to fire TIMER2_COMPA.
  5. As soon as TIMER2_COMPA is triggered, both interrupts are disabled and the time is determined via micros().
    Even if micros() does not have the desired resolution, a quarter of the expected time should be measured.

I don't understand why TIMER2_COMPA never fires.

I don't see anything obviously wrong with the code, and the problem may be incorrect assumptions about the signal. Forum members are unlikely to be able to help, because they don't have that signal to test with.

I suggest to use a 38 kHz IR receiver to eliminate the 38 kHz carrier signal. Then, use the IRRemote library to get pulse timings of the raw data (one of its built in functions).

Does that mean that the TC2 is being driven by a 500 kHz clock coming from 16 MHz internal oscillator after divided by 32?

And the OCF2A flag will trigger interrupt after counting 16 clock pulses? How do you verify that the interrupt has occured? 32 us is too short to visualize unless you count 75000 interrupts and flash a LED at 2.4 sec interval. Test sketch using UNO R3.

volatile bool flag = false;
volatile unsigned long counter = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  TCCR2A = 0;
  TCCR2B = 0;
  TCNT2 = 0;
  OCR2A = 16;  //preset value
  bitSet(TIMSK2, OCIE2A);   //OCF2A interrupt is enabled
  TCCR2B = 0x03; //(1 << CS21) | (1 << CS20);   // divide by 32 and start TC2
  interrupts();    //global interrupt
}

void loop()
{
  if (flag == true)
  {
    Serial.println("Interrupt has occured.");
    digitalWrite(13, HIGH);   //75000x32 = 2.4 sec interval
    delay(100);
    digitalWrite(13, LOW);
    delay(100);
    flag = false;
    TCCR2B = 0x03; //start TC2
    interrupts();
  }
}

ISR(TIMER2_COMPA_vect)
{
  TCNT2 = 0;
  OCR2A = 16;
  counter++;
  if (counter == 75000)
  {
    noInterrupts();
    TCCR2B = 00;  //stop TC2
    flag = true;
    counter = 0;
  }
}

Output: (~380 ms for interrupt overhead)

11:02:09.001 -> Interrupt has occured.
11:02:11.777 -> Interrupt has occured.
11:02:14.532 -> Interrupt has occured.

What is the 38 kHz pulse packet size? Is it 63 you have mentioed earlier?

All of the IR libraries assume your input will be the output of an IR receiver module. Those modules go low when carrier is present, and back high when it stops. In effect, they demodulate the 38KHz carrier, which is what you're trying to do the hard way. But I wonder if you can't just capture the signal on your scope and figure out what it is. If it's a pulse position protocol, like NEC, the On periods are always the same duration, and it's the Off periods that determine the bit values. But usually there are only two Off possibilities - long and short. So it's pretty easy to figure it out. And if it's not NEC, this site will help you figure out what protocol is being used:

https://www.mikrocontroller.net/articles/IRMP_-_english

Or, as has been suggested, you could get an IR receiver module, and then one of the libraries can decode it for you.

What is your input coming from? Are you tapping into the LED driver circuit of the remote control, so it's digital input, or are you firing the remote into a photodiode or phototransistor?

I understand that it is not possible for you to help without having my test signal.
Ultimately, the easiest solution will be to use an IR receiver that eliminates the 38 kHz carrier.
But it annoys me that I can't get the TIMER2_COMPA interrupt under control :slight_smile:

Yes, that is my understanding of these settings:

  TCCR2A |= _BV(COM2A0);            // Toggle OC2A on Compare Match  
  TCCR2A |= _BV(WGM21);             // CTC mode  
  TCCR2B |= _BV(CS20);              // Prescaler = 32, -> 2us
  TCCR2B |= _BV(CS21);              // Prescaler = 32, -> 2us

That's the goal. The problem is that the TIMER2_COMPA interrupt occurs too early. In INT0, TCNT2 is already reset after 26µs.

With your code I got the same result on my Nano:

08:04:10.253 -> Interrupt has occured.
08:04:13.061 -> Interrupt has occured.
08:04:15.808 -> Interrupt has occured.

I didn't count the pulses individually, but with the oscilloscope I measured a packet width of 1.62ms with a period of 26us --> approx. 62.

I really don't think so.

void setup() {
   Serial.begin(115200);
   Serial.print("PB3 = ");
   Serial.println(PB3);
   Serial.print("PD2 = ");
   Serial.println(PD2);
}

void loop() {
}

Neither does the compiler.

OPTIONS: I18n 
Port /dev/ttyACM0, 00:25:07

Press CTRL-] Z for help on special keys

PB3 = 3
PD2 = 2

Be straightforward instead.

#define OC2A_PIN       11
#define INTERRUPT_PIN  2

Thanks Sherman, the protocol is the second issue. First, I want to get the simple output compare working properly.

I'm firing the remote into a photodiode:

You are right! I changed the define...

#define OC2A_PIN       11          // D11
#define INTERRUPT_PIN  2           // D2

... and got the first time a signal at the OC2A_PIN, Thanks!

Why do you prefer to using DPin numbers instead of pin signals?

Because 3 != 11.

===>
PB3 != 11

For example: both of the following two lines are compiled; but, the top line does not correspond to PPin-17 (DPin-11) of MCU.

pinMode(PB3, OUTPUT);
pinMode(11, OUTPUT);