## H-bridge control example for Arduino Nano (ATmega328) – two phase-displaced square waves

This is the code:

```//
// H-bridge control example for Arduino Nano (ATmega328)
// Written by Ted Burke, 27-4-2018
//
// 20 kHz square wave output on OC2 (pin D11) and OC2B (pin D3)
// The phase difference between OC2 and OC2B can be controlled
// by varying the value of OCR2B between 1 and 49 inclusive.
//
// OCR2B = 49 makes the square waves in opposite phase.
// OCR2B = 1 makes the square waves almost in phase.
//
// Subsequent changes to OCR2B must be done with care because
// missing a compare event will change the phase of OC2B by
// 180 degrees!
//

void setup()
{
// TC2 (Timer/Counter 2) in CTC mode with 8:1 prescaler
TCCR2A = (0<<COM2A1)|(1<<COM2A0)|(0<<COM2B1)|(1<<COM2B0)| 0        | 0        |(1<<WGM21)|(0<<WGM20);
TCCR2B = (0<<FOC2A )|(1<<FOC2B )| 0         | 0         |(0<<WGM22)|(0<<CS22 )|(1<<CS21 )|(0<<CS20 );
OCR2A = 49; // sets the frequency
OCR2B = 1; // phase shift between outputs (49 is opposite phase, 1 is almost in phase)

// Enable timer output pins: OC2 (pin D11) and OC2B (pin D3)
pinMode(3, OUTPUT);
pinMode(11, OUTPUT);
}

void loop()
{
// Do other stuff here if desired
}

```

## Example Output

In the following oscilloscope screenshots, channel 1 (yellow) displays the signal from OC2 (pin D11) and channel 2 (blue) displays the signal from OC2B (pin D3).

This is the output when OC2RB = 49, making the two square waves 180° out of phase: This is the output when OC2RB = 25, making the two square waves 90° out of phase: This is the output when OC2RB = 1, making the two square waves 3.6° out of phase (i.e. almost in phase): This entry was posted in Uncategorized and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

### 1 Response to H-bridge control example for Arduino Nano (ATmega328) – two phase-displaced square waves

1. Ahmad says:

Dear Mr. Ted Bruke;

I tried to simulate in proteus for dsPIC33FJ32MC204, following your code posted at
https://batchloaf.wordpress.com/2010/12/06/motor-pwm-example-for-the-dspic30f4011/.
Thanks for detailed code of yours.can you please little explain how did you come up with that if PDC2 = (1-dutycycle)*2*PTPER,
then you get almost 180 degree shift.

Also sir how can i generate code that will have 3 pwm channels that are 120 degeree shifted with respect each other, using dsPIC30F4011