Pages: [1]   Go Down
Author Topic: phase-shifted PWM  (Read 619 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 1
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I'm trying to make a program that quite simply, shifts the phase of PWM numbers.
So say I have two variables, var1 and var2.
var1 is moving up and down between 0 and 255. I want var2 to be 30 degrees out of phase of this,
so that when:
var1 = 0
var2 = 64

var 1 = 128
var2 = 192

But also,
var1 = 255
var2 = 192

Now this is getting into maths beyond my small brain's capability, especially seeing as I didn't do maths past GCSE.
Anyone care to lend a hand? Or a brain, rather?
« Last Edit: February 19, 2008, 12:42:09 pm by joepublic » Logged

California
Offline Offline
Jr. Member
**
Karma: 0
Posts: 62
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Greetings,

Doesn't something as simple as this work:

Code:
setup() {
    int var1 = 0;
    int var2 = 64;
}

loop () {
   var1 = (var1 + 1) % 256;
   var2 = (var2 + 1) % 256;
}


The variables start off with a fixed phase difference, and as long as they are incremented together, and wrap-around at the same point, they will stay in sync.

Regards,
David
Logged

Australia
Offline Offline
Jr. Member
**
Karma: 0
Posts: 63
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

// stdint.h has types such as uint8_t and uint16_t
#include <stdint.h>

// inherent wrapping of limited data type does all the phase stuff you need during a simple add operation
// note that (255 + 1) & 255 = 0, which is exactly what happens when we work with 8 bit variables
uint8_t var, phase;

#define INITIAL_PHASE 30

// we recalculate the phase angle for 128 = 180 degrees, 256 = 360 degrees so simply adding does everything we need
// 30 degrees comes to about 21
for (var=0, phase=255 * INITIAL_PHASE / 360;;var++) {
  doSomethingWith(var);
  doSomethingWith(var + phase);
}
Logged

California
Offline Offline
Jr. Member
**
Karma: 0
Posts: 62
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

That's clever. Thanks!
 ;D  :o  8-)
Logged

Pages: [1]   Go Up
Jump to: