#include <Arduino.h>
#include <math.h>
#define PWM_A PB13
#define PWM_B PB14
#define PWM_C PB15
#define ADC_A PA0
#define ADC_B PA1
#define ADC_C PA4
const float F_SINE_HZ = 60.0f;
const float TWO_PI_F = 6.28318530718f;
const float DT_SINE_MS = 1.0f;
const uint16_t PWM_TOP = 200;
const uint32_t TICK_US = 10;
const float PHASE_A = 0.0f;
const float PHASE_B = -2.0f * PI / 3.0f; // -120°
const float PHASE_C = 2.0f * PI / 3.0f; // +120°
volatile uint16_t pwmCount = 0;
int dutyCount[3] = {0, 0, 0};
unsigned long lastPwmTickUs = 0;
unsigned long lastSineTickUs = 0;
float theta = 0.0f;
void setup() {
pinMode(PWM_A, OUTPUT);
pinMode(PWM_B, OUTPUT);
pinMode(PWM_C, OUTPUT);
digitalWrite(PWM_A, LOW);
digitalWrite(PWM_B, LOW);
digitalWrite(PWM_C, LOW);
}
void loop() {
unsigned long nowUs = micros();
if (nowUs - lastSineTickUs >= (unsigned long)(DT_SINE_MS * 1000.0f)) {
lastSineTickUs += (unsigned long)(DT_SINE_MS * 1000.0f);
float A[3];
A[0] = constrain(analogRead(ADC_A) / 4095.0f, 0.0f, 1.0f);
A[1] = constrain(analogRead(ADC_B) / 4095.0f, 0.0f, 1.0f);
A[2] = constrain(analogRead(ADC_C) / 4095.0f, 0.0f, 1.0f);
float sA = sinf(theta + PHASE_A);
float sB = sinf(theta + PHASE_B);
float sC = sinf(theta + PHASE_C);
float duty[3] = {
0.5f + 0.5f * A[0] * sA,
0.5f + 0.5f * A[1] * sB,
0.5f + 0.5f * A[2] * sC
};
for (int i = 0; i < 3; i++) {
duty[i] = constrain(duty[i], 0.0f, 1.0f);
dutyCount[i] = (int)(duty[i] * PWM_TOP);
}
theta += TWO_PI_F * F_SINE_HZ * (DT_SINE_MS / 1000.0f);
if (theta > TWO_PI_F) theta -= TWO_PI_F;
}
if (nowUs - lastPwmTickUs >= TICK_US) {
lastPwmTickUs += TICK_US;
pwmCount++;
if (pwmCount >= PWM_TOP) pwmCount = 0;
digitalWrite(PWM_A, (pwmCount < dutyCount[0]) ? HIGH : LOW);
digitalWrite(PWM_B, (pwmCount < dutyCount[1]) ? HIGH : LOW);
digitalWrite(PWM_C, (pwmCount < dutyCount[2]) ? HIGH : LOW);
}
}