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?
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.
// 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);
}