3

I would like to generate a sequence of pulses of varying lengths in the range of 0-100us, so that from the start of one pulse to the start of the next there is a delay of 100us. I have set up timer0 in CTC mode to trigger an interrupt every 100us.

In this interrupt, I would like to turn the appropriate pin high, read the length of the current pulse from an array, and then configure the timer in such a away that it turns the pin off as soon as the pulse length has elapsed (I am hoping that this is possible without using an interrupt for turning off the pin). It seems that the PWM functionality can do what I want, if I use the second output compare register.

In any case this seems possible using a secondary timer in PWM mode, but I'd like to know whether the same is possible using only a single timer. From what I've seen in the datasheets the answer seems no, but perhaps I am missing something.

Can a timer be used in both CTC (with output compare register A) and PWM modes (with output compare register B)?

  • 1
    Setting the COM0B1 bit in the TCCR0A register will Clear OC0B on Compare Match. Though as others described, CTC might not be the best mode for it. – Gerben Oct 19 '16 at 8:48
2

As noted in previous answer, CTC and PWM are distinct modes, and only one mode can be selected at any given moment.

However, your problem description sounds like mode 14 on timer 1 will serve. That's a Fast PWM mode that uses ICR1 as TOP. OCR1A or OCR1B can be used for output compare, depending whether you want to output on OC1A or OC1B. OC1A is PB1, or digital pin 9 on ATmega328 systems, and OC1B is PB2, or digital pin 10.

On a 16 MHz system, you would put 1600 in ICR1, so there would be an Overflow Interrupt every 100 μs. At each Overflow Interrupt you would put the currently desired pulse-length into OCR1A or OCR1B. This will work so long as your Overflow ISR takes fewer cycles than any desired pulse length.

You would set COM1A1/COM1B1 and COM1A0/COM1B0 to 1, 0, because Table 16-3 for this combination says, “Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode).” [Or see §16.9.3 (“Fast PWM Mode”) of the 2015 '328 spec, which says: “In non-inverting Compare Output mode, the Output Compare (OC1x) is cleared on the compare match between TCNT1 and OCR1x, and set at BOTTOM.”]

3

Technically no. CTC and PWM are distinct modes of operation.

However, more advanced PWM modes, specifically mode 7 for 8-bit timers and modes 14 and 15 for 16-bit timers, allow specifying an arbitrary timer duration in OCRxA or ICRx while still allowing PWM operation using the other output compares.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.