63 lines
1.5 KiB
C
63 lines
1.5 KiB
C
/*
|
|
* buck_emulator.c
|
|
*
|
|
* Created on: 12 May 2025
|
|
* Author: Christian Lind Vie Madsen
|
|
*/
|
|
|
|
|
|
typedef struct {
|
|
float Vin; // Input voltage
|
|
float Vout; // Output voltage
|
|
float IL; // Inductor current
|
|
float L; // Inductance
|
|
float C; // Capacitance
|
|
float Rload; // Load resistance
|
|
float dt; // Time step (e.g., 25e-6)
|
|
} BuckConverter;
|
|
|
|
void simulate_step(BuckConverter *buck, float duty_cycle) {
|
|
float dIL = (buck->Vin * duty_cycle - buck->Vout) / buck->L;
|
|
buck->IL += dIL * buck->dt;
|
|
|
|
float dVout = (buck->IL - buck->Vout / buck->Rload) / buck->C;
|
|
buck->Vout += dVout * buck->dt;
|
|
}
|
|
|
|
/*
|
|
int main() {
|
|
BuckConverter buck = {
|
|
.Vin = 12.0,
|
|
.Vout = 0.0,
|
|
.IL = 0.0,
|
|
.L = 100e-6,
|
|
.C = 100e-6,
|
|
.Rload = 10.0,
|
|
.dt = 25e-6
|
|
};
|
|
|
|
float duty_cycle = 0.5;
|
|
float Vref = 5.0;
|
|
float error, previous_error = 0, integral = 0;
|
|
float Kp = 0.2, Ki = 1000;
|
|
|
|
for (int i = 0; i < 40000; ++i) {
|
|
error = Vref - buck.Vout;
|
|
integral += error * buck.dt;
|
|
|
|
duty_cycle = Kp * error + Ki * integral;
|
|
if (duty_cycle > 1.0) duty_cycle = 1.0;
|
|
if (duty_cycle < 0.0) duty_cycle = 0.0;
|
|
|
|
simulate_step(&buck, duty_cycle);
|
|
|
|
// For debug:
|
|
if (i % 1000 == 0)
|
|
printf("Time: %.3f ms, Vout: %.2f V, IL: %.2f A, Duty: %.2f\n",
|
|
i * buck.dt * 1000, buck.Vout, buck.IL, duty_cycle);
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
*/
|