3

I need 2 PWM pins to oscillate at 25 KHz but they need to oscillate inverse to each other. When one is high, the other must be low and vise-versa.

I want to do this with a Nano.

4
  • use one pin and invert it using hardware
    – jsotola
    Commented Jul 29, 2021 at 4:04
  • Use two timers with the same settings, started simulaneously.
    – towe
    Commented Jul 29, 2021 at 7:29
  • 2
    @towe: How do you start them simultaneously? Commented Jul 29, 2021 at 8:03
  • @EdgarBonet Set their Clock Select right after each other, that should only be a couple clock cycles of difference.
    – towe
    Commented Jul 29, 2021 at 8:21

1 Answer 1

8

There are various solutions. I suggest using two PWM channels driven by a single timer. This way you do not have to worry about synchronizing two timers. You can configure the channels identically, except that one of them would be in “non-inverting” PWM mode, while the other one would be in “inverting” mode.

Here is how I would do it: use Timer 1 to drive pins 9 (PB1, OC1A) and 10 (PB2, OC1B) in fast PWM.

void setup() {
    // Configure Timer 1 for complementary PWM @ 25 kHz.
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = 0;           // undo the Arduino timer initialization
    TCCR1B = 0;           // ditto
    ICR1   = 640 - 1;     // period = 640 CPU cycles = 40 us
    OCR1A  = 320 - 1;     // OC1A HIGH for 320 CPU cycles = 20 us
    OCR1B  = 320 - 1;     // OC1B LOW for 320 CPU cycles = 20 us
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(COM1B0)  // inverting PWM on OC1B
           | _BV(COM1B1)  // ditto
           | _BV(WGM11);  // fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock at F_CPU
}
2
  • 1
    Ah, that's what I had in mind first, but I was irritated by the second Compare Output Mode behaving different for OC1A and OC1B and thought they were fixed to each other. +1
    – towe
    Commented Jul 29, 2021 at 8:19
  • 1
    This works perfectly. I could not have asked for a more simple and precise solution !!!
    – Curtis
    Commented Jul 30, 2021 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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