// Stepper Microstepping coil power calculations
// https://wokwi.com/projects/417824766854934529
// For https://forum.arduino.cc/t/driving-stepper-at-rated-current/1333572/32

// Run on an ESP32 for printing doubles.

void setup() {


  const double CoilA = 4 * 1.414; // A RMS *1.414-> peak Amps
  const double CoilOhms = 1.0;

  const char BufSize = 128;
  char buff[BufSize];

  const int Microsteps = 32; // microsteps per full step
                             // 4 full steps in a full quadrature cycle

  Serial.begin(115200);
  Serial.printf("Microstepping /%d current/power table\n", Microsteps);

  Serial.printf("For %0.2f A(peak) %0.2f A(rms) and %0.2f Ohms\n",CoilA, CoilA/1.414, CoilOhms);

  Serial.println(R"(
  Step   Deg     A%&B%      Amps                Watts  )");
  for ( int ii = 0; ii < Microsteps * 4; ++ii) {
    int jj = ii + Microsteps / 2; // 45° start index

    double aFraction = sin(2 * PI * (jj) / Microsteps / 4);
    double bFraction = cos(2 * PI * (jj) / Microsteps / 4);
    double phaseAngle = atan2(aFraction, bFraction) * 180 / PI;
    double aAmps = CoilA * aFraction;
    double bAmps =  CoilA * bFraction;

    double aPower = aAmps * aAmps * CoilOhms;
    double bPower = bAmps * bAmps * CoilOhms;

    double sumAmps = abs(aAmps) + abs(bAmps);
    double sumPower = aPower + bPower;


    snprintf(buff, BufSize, "step: %d %.1f°: %.2f&%.2f %.2f&%.2f=%.2fA  %.2f+%.2f=%.2fW",
             ii, phaseAngle, aFraction, bFraction,
             aAmps, bAmps, sumAmps,
             aPower, bPower, sumPower);

    Serial.print(buff);
    Serial.println();
  }
}



void loop() {
  // put your main code here, to run repeatedly:

}