How to invert 100khz PWM on Mega?

Not sure if that PWM library supports phase inversion like that. This little bit of direct register manipulation will get you the desired waveform on pins 11 and 12 of a Mega2560:

const uint8_t pinPhase = 11;        //OC1A
const uint8_t pinInvert = 12;       //OC1B

void setup() 
    pinMode( pinPhase, OUTPUT );
    pinMode( pinInvert, OUTPUT );

    TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(COM1B0) | _BV(WGM11);
    TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10);
    ICR1 = 0xA0;
    OCR1A = 0xA0 >> 1;
    OCR1B = 0xA0 >> 1;

void loop() 
1 Like

Oh my gosh, i'm so excited. How did you do that?
Aren't "No prescaling" and "16-bit" supposed to produce a maximum frequency of 244Hz?

Or even if you used, f_pwm = f_clk / N(1+ICR1) is 15.8kHz

Did I miss something?

He just forgot to subtract 1. Set ICR1 to 159 (0xBF) to get 160 counts per cycle of Fast PWM. 16 MHz / 160 = 100 kHz.

If you use Phase Correct PWM the count is for a half-cycle so you use 79 instead of 159.

Since both 159 and 79 are below 256 you can use any available 8-bit timer as well.

1 Like

I used the 16-bit Timer1 specifically because OC1A and OC1B are connected to pins 11 and 12 respectively as the OP said "I want to invert PWM in 12,11 pins." Thanks for noting I forgot to subtract '1'; the value should be 0x9F, not 0xBF :slight_smile:

@tom_mali , check the WGM (waveform generator mode) settings; mode 14 allows the use of ICR1 to store the "top" value which is very handy for setting custom frequencies.

1 Like

DARN! I subtracted 1 from 'A' and somehow got 'B'?!? At least I got the decimal value right. :frowning:

Some processors (such as those used for the Teensy 3.x Family) include special hardware for H-bridge control. They support a "dead zone" to prevent the H-bridge legs from directly shorting top to bottom.

Thank you for all.

I should have thanked him right away, but Newbie didn't know there was a limit to the comments he could post a day.

Dead time has also been created.