Hello!

I am beginner in everything here so let’s see how it goes.

Trying to use the C++ block to generate space vector PWM.

and the code looks like as below:

```
if ( (t-timecheck) >= 20.e-6)
{
timecheck = t; // CHECK THE CURRENT TIME AND STORE IT
pi = 3.141592653589793;
wg_1 = 2 * pi * 50;
Va = In * sin(wg_1*t);
Vb = In * sin(wg_1*t - ((2*pi) / 3));
Vc = In * sin(wg_1*t + ((2*pi) / 3));
double factor = 1.0 / 3.0;
Val_g = (factor) * ((2*Va) - Vb - Vc);
Vbet_g = (factor) * ((sqrt(3)*Vb) - (sqrt(3)*Vc));
phi= pi/2;
Vdg = Val_g * cos((wg_1*t) - phi) - Vbet_g * sin((wg_1*t) - phi);
Vqg = - Val_g * sin((wg_1*t) - phi) - Vbet_g * cos((wg_1*t) - phi);
double Vdc = 20;
double Ts = t * 0.1;
// Compute Vref
double Vref = sqrt(pow(Vdg, 2) + pow(Vqg, 2));
// Compute phi_pwm
double phi_pwm = atan2(Vqg, Vdg); // atan2(y, x) returns the arctangent of y/x
// Adjust theta to be in the range [-pi, pi)
if (phi_pwm < 0) {
phi_pwm += 2 * M_PI;
}
// Determine the sector based on theta
int sector;
if (phi_pwm >= 0 && phi_pwm < M_PI / 3) {
sector = 1;
} else if (phi_pwm >= M_PI / 3 && phi_pwm < 2 * M_PI / 3) {
sector = 2;
} else if (phi_pwm >= 2 * M_PI / 3 && phi_pwm < M_PI) {
sector = 3;
} else if (phi_pwm >= M_PI && phi_pwm < 4 * M_PI / 3) {
sector = 4;
} else if (phi_pwm >= 4 * M_PI / 3 && phi_pwm < 5 * M_PI / 3) {
sector = 5;
} else {
sector = 6;
}
double K = sqrt(3)* Ts * Vref / Vdc;
double T1 = K *(sin(sector * (pi / 3) - phi_pwm));
double T2 = K * (sin(phi_pwm - (sector - 1) * (pi / 3)));
double To = (Ts-T1-T2) / 2;
double s1, s2, s3;
s1 = (sector == 1) * (T1 + T2 + To) + (sector == 2) * (T1 + T2 + To) + (sector == 3) * (T1 + To) +
(sector == 4) * (To) + (sector == 5) * (To) + (sector == 6) * (T2 + To);
s2 = (sector == 1) * (To) + (sector == 2) * (T2 + To) + (sector == 3) * (T1 + T2 + To) +
(sector == 4) * (T1 + T2 + To) + (sector == 5) * (T1 + To) + (sector == 6) * (To);
s3 = (sector == 1) * (T1 + To) + (sector == 2) * (To) + (sector == 3) * (To) +
(sector == 4) * (T2 + To) + (sector == 5) * (T1 + T2 + To) + (sector == 6) * (T1 + T2 + To);
double Vsa = (2*s1-s2-s3) * (Vdc / 3);
double Vsb = (2*s2-s1-s3) * (Vdc / 3);
double Vsc = (2*s3-s1-s2) * (Vdc / 3);
Out1 = Vsa;
Out2 = Vsb;
}
}
```

output:

so basically not able to close the loop and and the value is keep increasing. Ofcourse there is a basic mistake, just do not know where, is there any help available here?

Thanks in advance.

Anup