Skip to content

Instantly share code, notes, and snippets.

@LightningStalker
Created September 11, 2025 10:06
Show Gist options
  • Select an option

  • Save LightningStalker/2ff6a8bb067fbd6285bbadf4f66fced6 to your computer and use it in GitHub Desktop.

Select an option

Save LightningStalker/2ff6a8bb067fbd6285bbadf4f66fced6 to your computer and use it in GitHub Desktop.
Buck converter calc
/* Compile with $ gcc -Wall -o bucks bucks.c
* For Watcom: $ wcl -bcl=$(DEST_OS) -wx -fe=$(EXE_file) bucks.c
* or use make
* Buck converter Power State calculator
* Formuli from SLVA477B by TI, Rev. 8/2015
* C adaptation by Project Crew 2024
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int
main(int argc, char ** argv) {
char strg[40];
double
freq, // frequency
vin, // input voltage
vout, // output voltage
ioutmax, // max output current
voutripple, // desired output voltage ripple
D, // duty cycle
iripple, // ripple current
L, // inductor value
mincap, // minimum output capacitance
idiode; // avg. forward diode current
if (argc == 1) {
if (fgets(strg, 40, stdin) == NULL) // process input
goto usage; // NO_VALUE
else if ((isdigit(strg[0]) == 0) && (strg[0] != '.'))
goto usage;
freq = atof(strg);
fgets(strg, 40, stdin);
vin = atof(strg);
fgets(strg, 40, stdin);
vout = atof(strg);
fgets(strg, 40, stdin);
ioutmax = atof(strg);
fgets(strg, 40, stdin);
voutripple = atof(strg);
// begin calc section
D = vout * 0.85 / vin; // equation 1
iripple = 0.3 * ioutmax; // equation 6
L = vout * (vin - vout) / (iripple * freq * vin); // equation 5
mincap = iripple / (8.0 * freq * voutripple); // equation 12
idiode = ioutmax * (1 - D); // equation 7
// spacer
fputs("-\n", stderr);
// send formatted output
printf("%.3f\n%.3f\n%.3f\n%.3f\n%.3f\n",
D * 100,
iripple,
L * 1e6,
mincap * 1e6,
idiode
);
exit(EXIT_SUCCESS);
} else {
usage:
puts(" bucks is a buck converter power state calculator.");
puts(" 5 output paramaters including inductor value\n");
puts(" 5 position dependent input paramaters from stdin, 1 per line");
puts(" scriptable and designed to be used with formvar");
puts(" Input: frequency, Vin, Vout, Ioutmax, Voutripple");
#if defined (__DOS__)
puts(" Output: dutyCycle, Iripple, L(\xe6\H), "
"minimumOutputCapacitance(\xe6\F), Idiode");
#else
puts(" Output: dutyCycle, Iripple, L(µH), "
"minimumOutputCapacitance(µF), Idiode\n");
#endif
exit(EXIT_FAILURE);
}
return(EXIT_SUCCESS);
} /* main */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment