Quantcast
Channel: ad hocumentation • n. fast documentation of ideas and solutions.
Viewing all articles
Browse latest Browse all 72

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

$
0
0

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


Viewing all articles
Browse latest Browse all 72

Trending Articles