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.
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.
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
}