3d part design with OpenSCAD #154: An automatic resistor color code calculator and model generator.
In the last post I made a resistor model generator that you could manually change the values of the bands for specific resistor values, this updated code will automatically change the colors based on the input of the resistor value and output a model that can be used in Kicad.
Here is the code:
//
//Auto resistor Calculator and generator Version2 by InfinityPlays.com//
/*[ Enter resistor Value ]*/
Resistor_value=1200;
Tolerance="silver";//[gold]
/*[Resize for Kicad]*/
Resize=5.30;//[2.65:2.65:26.5]
/*[leads]*/
lead_length=4;//[2:.01:6]
lead_diameter=.40;//[.1:.01:.6]
/*[Hidden]*/
$fn=$preview?60:150;;
function get_color(val) =
val == 0 ? "black":
val == 1 ? "brown":
val == 2 ? "red":
val == 3 ? "orange":
val == 4 ? "yellow":
val == 5 ? "green":
val == 6 ? "blue":
val == 7 ? "violet":
val == 8 ? "gray":
val == 9 ? "white":
val == "gold"?"#D4AF37":
val == "silver"?"#C0C0C0":"khaki";
module auto_resistor(ohms, tolerance=Tolerance){
raw_exp=floor(log(ohms)/log(10));
sig_digits=round(ohms/pow(10,raw_exp-1));
d1=sig_digits>=100?floor(sig_digits/100):floor(sig_digits/10);
d2=sig_digits>=100?floor((sig_digits % 100)/10) :floor(sig_digits%10);
mult=sig_digits>=100?raw_exp:raw_exp-1;
colors=[get_color(d1),get_color(d2),get_color(mult),get_color(tolerance)];
echo (colors);
echo (tolerance=tolerance);
color("khaki"){
minkowski(){
translate([0,0,-3.5])
rotate([0,0,0])
cylinder(7.1,.01,.01);
sphere(1.5);
}
translate([0,0,-3.5])
sphere(1.6);
translate([0,0,3.5])
sphere(1.6);
}
for(i=[0:3]){
band_offset=-15/2+.75+(i*(1.75));
translate([0,0,band_offset+4]){
color(colors[i])
cylinder(h=1,r=1.54,center=true);
}}
color("lightgrey"){
rotate([90,180,0])
translate([-2,5,0])
rotate_extrude(90)
translate([2,0,0])
circle(r=lead_diameter);
rotate([270,180,0])
translate([-2,5,0])
rotate_extrude(90)
translate([2,0,0])
circle(r =lead_diameter);
rotate([90,180,90])
translate([0,7,2])
cylinder(lead_length,lead_diameter,lead_diameter);
rotate([90,180,90])
translate([0,-7,2])
cylinder(lead_length,lead_diameter,lead_diameter);
}}
resize([Resize,0,0], auto=true){
rotate([0,90,0])
auto_resistor(Resistor_value);
}
and here is the output in Kicad:

