## cschem fawk sheet

# The first line must be the above, else cschem will refuse to run the script.

# Generate classic R2R digital-analog-converter
#
# input0        input1        input2
#   |             |             |
#  [R1]          [R3]          [R5]
#   |             |             | 
#   j0 -- [R2] -- j1 -- [R4] -- j2 -- ...
#   |
#  [R0]
#   |
#   gnd
#
# R0, R1, R3, R5, ... are 2*R resistors (2k0 by default)
# R2, R4, ... are 1*R resistors (1k0 by default)
# output is the last j

function refdes(n)
{
	return "R" @ (base + n);
}

function resistor(n, val,       rfd)
{
	rfd = refdes(n);
	acomp_attr(rfd,   "value", val,   "footprint", fp);
	return rfd;
}

function main(ARGV)
{
	bits=5;
	valr =  "1k0";
	valr2 = "2k0";
	base = 100;
	fp = "0805";

	# create leftmost divider
	low = resistor(0, valr2);
	high = resistor(1, valr2);
	aconn("gnd", low, 1);
	aconn("input0", high, 2);
	aconn("j0", low, 2, high, 1);

	# create the rest of the ladder, piece by piece from the horizontal
	# R resistor and ther vertical 2*R resistor
	for(i = 1; i < bits; i++) {
		horiz = resistor(i*2+0, valr);
		vert  = resistor(i*2+1, valr2);
		aconn("j" @ (i-1), horiz, 1);
		aconn("j" @ i, horiz, 2, vert, 1);
		aconn("input" @ i, vert, 2);
	}
}
