#define URL "https://wokwi.com/projects/391849803585874945"
#define TITLE "3phase square waves with Bresenham"
/*
  3phase 500Hz square waves with Bresenham calculations
  https://wokwi.com/projects/391849803585874945

  Blink with Scope https://github.com/Dlloydev/Wokwi-Chip-Scope
        and https://github.com/Dlloydev/Wokwi-Chip-PWM

  Wokwi Uno https://wokwi.com/projects/390819301187622913
  Wokwi Mega: https://wokwi.com/projects/390819455604080641

*/

long D=0; // Bresenham decision sum
int8_t pin = 0;
byte Pins[] = {13, 12, 11};
byte NumPins = sizeof(Pins) / sizeof(Pins[0]);

// target 333.3us changes
long dt = 50; // time step
long dx = 2000; // bresenham multiplier = us/cycle
long dy = dt*2*3 ; // * 2 transitions * 3 traces // Bresenham divisor

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  for (auto &pin : Pins) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);
  }
  digitalWrite(Pins[1],HIGH);
  digitalWrite(Pins[2],LOW);
  Serial.begin(115200);
Serial.println(TITLE);
Serial.println(URL);
Serial.print(1e6/dx);
Serial.print("Hz 3-phase square waves require a transition every ");
Serial.print(dx/3.0/2);
Serial.print("us.  This can be done with a Bresenham algorithm stepping ratio of ");
Serial.print(dx);
Serial.print(":");
Serial.print(dy/dt);
Serial.println("");
Serial.print("Phase-locked with the Arduino clock with a timestep of ");
Serial.print(dt);
Serial.println("us");


}

// the loop function runs over and over again forever
void loop() {
  cycle();
}

//333

void cycle(void) {
  const uint32_t interval = dt;
  static uint32_t last = -interval;
  if (micros() - last >= interval) {
    last += interval;
    if (D > 0 ) {
      digitalWrite(Pins[pin], digitalRead(Pins[pin]) == HIGH ? LOW : HIGH);
      pin+=2;
      if (pin >= NumPins) pin -= 3;
      if (pin <0 ) pin +=3;
      D -= 2*dx;
    }
    D += 2*dy;
  }
}
Loading chip...chip-scope
Loading chip...chip-pwm