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):

Advertisements
This entry was posted in Uncategorized and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s