Phase shifted PWM signal

Hi all,

I used the PWM library to generate two PWM signals at a desired frequency. The problem is that I am not able to phase shift the PWM signal. For example I am generating a PWM signal at a frequency of 30Hz on PIN 9 and i need a phase shift of 45 degrees of the same PWM on PIN 10. Anyone who knows how to come around this ?

P.S. I am using an arduino uno.

Thanks in advance.

#include "PWM.h"

int frequency1 = 120;
int frequency2 = 120;
int pin1 = 9; // Timer1 for pins 9 and 10 (One frequency for both pins)
int pin2 = 3; // Timer2 for pins 3 and 11 

void setup() {

 InitTimersSafe();
 SetPinFrequencySafe(pin1,frequency1);
 SetPinFrequencySafe(pin2,frequency2);
}

void loop() {

pwmWrite(pin1,127);
pwmWrite(pin2,127);

}

You can't do this with pwmWrite.

You'll have to generate your signals explicitly pin by pin ,and use delays to get the timing.

eg here's some code I wrote to drive a 6-phase motor...

void setup() {
  pinMode (2, OUTPUT);
  pinMode (3, OUTPUT);
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (6, OUTPUT);
  pinMode (7, OUTPUT);
  noInterrupts() ;

}

const byte pulseDelay = 11;

const byte pattern[] = {0, 0b00011100, 0, 0b00111000, 0 , 0b01110000,
                        0, 0b11100000, 0, 0b11000100, 0, 0b10001100
                       };
byte i = 0;

void loop() {

  while (1) {
    PORTD = pattern[i++];
    if (i >= sizeof(pattern)) i = 0;
    delayMicroseconds(pulseDelay);
  }
}

I know it's clunky, but can't think of a better way offhand.

Note the use of noInterrupts() and the while(1) loop.

These disable the millis() and loop() background tasks - otherwise you get significant jitter.

Allan

allanhurst:
I know it's clunky, but can't think of a better way offhand.

This if probably going to be beyond the OP if he needs to ask this, but could you use Timer1 and Timer2 in FastPWM mode and preload the TCNT value of one to to change the phase angle? You'd need to set TOP of Timer2 I imagine.

TOP must stay the same for both timers, but the timers have to be started with different counter (TCNT) values. If one starts in Fast PWM at BOTTOM and the other one at TOP/2, the phase shift is 180°.

Another approach.

You could always use a couple of external gates - eg 74HCT00's.

Feed one input of each with the basic PWM frequency, and use 2 other arduino outputs to gate the PWM bit on the other inputs..

If you don't want gating glitches, use D flipflops eg 74HCT74's

Allan