by John Lauer
An independently designed 12 V to 5 V, 1 A synchronous buck molecule (TI TPS54202), with calculations, ngspice and PSpice simulation, KiCad 10 schematic and board, and the board laid out and analysed with adom-aiflow.
main
John Lauer
TP5: GND probe pad beside TP3 for the probing workcell; probing guide with the TP5 loop video and scope plots; molecule…
61f1679
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
#!/usr/bin/env python3
"""Write buck-12v5v-molecule.kicad_sch as a readable, datasheet-style sheet (v2).
v1 (gen_schematic.py, kept as buck-12v5v-molecule.kicad_sch.v1) put every part on a grid and joined
them only with net labels. v2 draws the circuit left to right with real wires:
Input (J1/J2, C1-C4) -> Enable UVLO (R4/R5, J3) -> Buck converter (U1, C5)
-> Output and feedback (L1, C6-C8, R1-R3, C9, J4/J5)
Indicator and monitor (R6/D1, R7/R8, J6) and Connectors (MP1-MP4, TP1-TP5) underneath.
Hard rule: the netlist must stay identical to v1's (same refs, values, footprints, fields, symbol
UUIDs, and every net with the same name and the same (ref, pin) set). Every net keeps a local
label of its v1 name (KiCad names a labelled net "/NAME", exactly as v1's label-only sheet did);
GND / VIN / VOUT are drawn with power-style symbols (see RAIL_STYLE below).
Layout units are 100 mil (2.54 mm); every coordinate is a multiple of 0.5 unit, so everything
sits on the 50 mil (1.27 mm) grid. Wires are split wherever another wire end or a pin lands on
them, and junction dots are added wherever three or more connections meet. A small checker at
the end reports dangling wire ends, wires crossing symbol bodies and overlapping text.
"""
import json, math, os, sys, uuid
import sexp
from sexp import Sym as S
HERE = os.path.dirname(os.path.abspath(__file__))
NAME = "buck-12v5v-molecule"
OUT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(HERE, NAME + ".kicad_sch")
net = json.load(open(os.path.join(HERE, "netlist.json")))
COMP = {c["ref"]: c for c in net["components"]}
LIBS = {
"Device": "lib/Device.kicad_sym",
"Regulator_Switching": "lib/Regulator_Switching.kicad_sym",
"power": "lib/power.kicad_sym",
"Connector": "lib/Connector.kicad_sym",
"Molecule": "lib/Molecule.kicad_sym",
"buck12v5v": "lib/buck12v5v.kicad_sym", # U1 in the Adom symbol style (tools/u1-symbol)
}
ALIAS = {"Molecule:Contact": "Molecule:MachineContact",
"Regulator_Switching:TPS54202DDC": "buck12v5v:TPS54202DDCR"}
# L1 / C1 / D1: KiCad's standard L / C_Polarized / LED graphics, turned the way this sheet draws them,
# with the part's 3D outline as a small grey graphic beside the symbol (tools/passive-symbols).
REF_SYM = {"L1": "buck12v5v:AMPLH5030S-150MT", "C1": "buck12v5v:EEE-FK1V470P", "D1": "buck12v5v:IN-S63BTG"}
ROOT = str(uuid.uuid5(uuid.NAMESPACE_URL, "adom/" + NAME + "/root")) # same as v1
U = 2.54 # layout unit (100 mil)
OX, OY = 5, 7 # sheet offset of the whole drawing, in units
def uid(s):
return str(uuid.uuid5(uuid.NAMESPACE_URL, f"adom/{NAME}/{s}"))
def mm(v):
return round(v * U, 4)
def X(x):
return mm(x + OX)
def Y(y):
return mm(y + OY)
cache = {}
LOCAL_POWER = "Buck_Power" # project library of sheet-local power symbols (see local_power())
def local_power(name):
"""GND / VIN / VOUT drawn like KiCad's power:GND / power:VCC but as LOCAL power symbols.
A global power symbol names its net "GND"; v1's label-only sheet named it "/GND". A local power
symbol (KiCad 9+) names the net like a local label, so the netlist keeps v1's exact names."""
import copy
if "power" not in cache:
cache["power"] = sexp.lib_symbols(os.path.join(HERE, LIBS["power"]))
base = "GND" if name == "GND" else "VCC"
s = copy.deepcopy(cache["power"][base])
s[1] = name
for e in s:
if isinstance(e, list) and e and e[0] == "power":
e[1] = S("local")
if isinstance(e, list) and e and e[0] == "property":
if e[1] == "Value":
e[2] = name
elif e[1] == "Description":
e[2] = f"Local power symbol: net {name} on this sheet (named like a local label)"
elif e[1] == "ki_keywords":
e[2] = "local power"
if isinstance(e, list) and e and e[0] == "symbol" and e[1].startswith(base + "_"):
e[1] = name + e[1][len(base):]
return s
def symdef(lib_id):
lib, name = lib_id.split(":")
if lib == LOCAL_POWER:
s = local_power(name)
s = [s[0], lib_id] + s[2:]
return s
if lib not in cache:
cache[lib] = sexp.lib_symbols(os.path.join(HERE, LIBS[lib]))
return sexp.flatten(name, cache[lib], lib)
def fnt(size=1.27, hide=False, justify=None, bold=False):
f = [S("font"), [S("size"), size, size]]
if bold:
f.append([S("bold"), S("yes")])
e = [S("effects"), f]
if justify:
e.append([S("justify")] + [S(j) for j in justify])
if hide:
e.append([S("hide"), S("yes")])
return e
lib_ids, body = {}, []
PINS = {} # ref -> {pin number: (x, y)} in layout units
BODIES = [] # (ref, x0, y0, x1, y1) symbol body boxes in units, for the checker
TEXTS = [] # (what, x0, y0, x1, y1) visible text boxes in units, for the checker
SEGS = [] # wire segments [(x0, y0), (x1, y1)] in units
LABELS = [] # (name, x, y, angle)
CW = 1.2 / U # stroke-font advance per character at 1.27 mm, in units (a little generous)
def text_box(what, x, y, s, just="left", angle=0, size=1.27):
"""Record an approximate box (units) for horizontal text anchored at (x, y) (baseline-centred)."""
w = len(s) * CW * size / 1.27
h = size / U
x0 = {"left": x, "right": x - w, "center": x - w / 2}[just]
TEXTS.append((what, x0, y - h / 2, x0 + w, y + h / 2))
def xform(px, py, rot, mirror):
"""Library point (mm, y up) -> sheet offset (units, y down) for a symbol at rot (CCW deg) / mirror."""
x, y = px / U, -py / U
if mirror:
x = -x
for _ in range((rot // 90) % 4): # CCW on screen, y down: (x, y) -> (y, -x)
x, y = y, -x
return x, y
def place(ref, x, y, rot=0, mirror=False, refpos=None, valpos=None, hide_value=False, box=None):
"""Place a netlist part. refpos/valpos = (dx, dy, justify) in units relative to (x, y)."""
c = COMP[ref]
lib_id = REF_SYM.get(ref) or ALIAS.get(c["sym"], c["sym"])
lib_ids[lib_id] = symdef(lib_id)
fang = 90 if rot in (90, 270) else 0 # field angle that renders horizontal text
sym = [S("symbol"), [S("lib_id"), lib_id], [S("at"), X(x), Y(y), rot]]
if mirror:
sym.append([S("mirror"), S("y")])
sym += [[S("unit"), 1], [S("exclude_from_sim"), S("no")],
[S("in_bom"), S("no") if c["block"] in ("probe",) else S("yes")],
[S("on_board"), S("yes")], [S("dnp"), S("no")], [S("uuid"), uid("sym/" + ref)]]
refpos = refpos or (1.0, -0.5, "left")
valpos = valpos or (1.0, 0.5, "left")
def just(j): # KiCad draws a 90-degree field on a 90-degree symbol at 180 and so mirrors its justification
if j != "center" and rot in (90, 270):
j = {"left": "right", "right": "left"}[j]
return None if j == "center" else [j]
props = [("Reference", ref, refpos, False), ("Value", c["value"], valpos, hide_value),
("Footprint", c["fp"], (0, 0, "center"), True), ("Datasheet", "~", (0, 0, "center"), True),
("MPN", c.get("mpn", ""), (0, 0, "center"), True), ("Manufacturer", c.get("mfr", ""), (0, 0, "center"), True),
("Source", c.get("src", ""), (0, 0, "center"), True)]
for k, v, (dx, dy, j), hide in props:
sym.append([S("property"), k, v, [S("at"), X(x + dx), Y(y + dy), fang], fnt(hide=hide, justify=None if hide else just(j))])
if not hide:
text_box(f"{ref}.{k}", x + dx, y + dy, v, j)
pins = sexp.pins(lib_ids[lib_id])
PINS[ref] = {}
for (num, pname, px, py, ang) in pins:
sym.append([S("pin"), num, [S("uuid"), uid(f"pin/{ref}/{num}")]])
ox, oy = xform(px, py, rot, mirror)
PINS[ref][num] = (round(x + ox, 3), round(y + oy, 3))
sym.append([S("instances"), [S("project"), NAME, [S("path"), "/" + ROOT, [S("reference"), ref], [S("unit"), 1]]]])
body.append(sym)
if box: # symbol body (units, relative, unrotated sheet frame) for the wire-crossing check
bx0, by0, bx1, by1 = box
BODIES.append((ref, x + bx0, y + by0, x + bx1, y + by1))
return PINS[ref]
PWR_N = [0]
# How GND / VIN / VOUT are drawn. A power-symbol name would win over the local label and rename
# the net from "/GND" to "GND", so the symbols here are drawn from KiCad's power library but with
# the net still named by the local label: see rail().
RAIL_LIB = {"GND": LOCAL_POWER + ":GND", "VIN": LOCAL_POWER + ":VIN", "VOUT": LOCAL_POWER + ":VOUT"}
def power(lib_id, value, x, y, rot=0):
"""A power-library symbol (GND / VCC-style / PWR_FLAG) with its pin at (x, y)."""
lib_ids[lib_id] = symdef(lib_id)
flag = lib_id.endswith("PWR_FLAG")
PWR_N[0] += 1
n = PWR_N[0]
rf = f"#FLG0{n:02d}" if flag else f"#PWR0{n:02d}"
down = lib_id.endswith(":GND")
vy = y + 1.5 if down else y - (1.5 if not flag else 1.5)
if flag:
vy = y - 1.5
body.append([S("symbol"), [S("lib_id"), lib_id], [S("at"), X(x), Y(y), rot], [S("unit"), 1],
[S("exclude_from_sim"), S("no")], [S("in_bom"), S("no")], [S("on_board"), S("no")], [S("dnp"), S("no")],
[S("uuid"), uid(f"pwr/{lib_id}/{x}/{y}")],
[S("property"), "Reference", rf, [S("at"), X(x), Y(y + (2.5 if down else -2.5)), 0], fnt(hide=True)],
[S("property"), "Value", value, [S("at"), X(x), Y(vy), 0], fnt()],
[S("property"), "Footprint", "", [S("at"), X(x), Y(y), 0], fnt(hide=True)],
[S("property"), "Datasheet", "~", [S("at"), X(x), Y(y), 0], fnt(hide=True)],
[S("pin"), "1", [S("uuid"), uid(f"pwrpin/{lib_id}/{x}/{y}")]],
[S("instances"), [S("project"), NAME, [S("path"), "/" + ROOT, [S("reference"), rf], [S("unit"), 1]]]]])
text_box(f"{value}@{x},{y}", x, vy, value, "center")
PINS[f"{rf}"] = {"1": (x, y)}
return (x, y)
def rail(name, x, y):
"""Rail symbol at (x, y): GND points down, VIN/VOUT point up."""
return power(RAIL_LIB[name], name, x, y)
def wire(*pts):
for a, b in zip(pts, pts[1:]):
assert a[0] == b[0] or a[1] == b[1], f"wire not orthogonal {a}->{b}"
if a != b:
SEGS.append((tuple(a), tuple(b)))
def label(name, x, y, angle=0):
LABELS.append((name, x, y, angle))
just = "left" if angle == 0 else "right"
text_box(f"label {name}", x + (0.25 if angle == 0 else -0.25), y - 0.5, name, just)
NOTES, TITLES, BOXES = [], [], []
def note(s, x, y, size=1.27, bold=False, just="left"):
NOTES.append((s, x, y, size, bold, just))
for i, line in enumerate(s.split("\n")):
text_box("note", x, y - 0.4 + i * size * 1.6 / U, line, just, size=size)
def section(title, x0, y0, x1, y1):
BOXES.append((x0, y0, x1, y1))
TITLES.append((title, x0 + 0.5, y0 + 1.2))
text_box("title " + title, x0 + 0.5, y0 + 1.0, title, "left", size=2.0)
# =========================================================================== layout
# Main row: VIN rail at y = 24 from J1 into U1; SW -> L1 -> VOUT rail at y = 28 out to J4.
RV = 24 # VIN rail
RO = 28 # SW / VOUT rail (U1 SW pin height)
# ---- Input: J1 (VIN), J2 (GND), PWR_FLAGs, C1 bulk + C2/C3 ceramic + C4 HF bypass
CAP = (-0.9, -1.0, 0.9, 1.0) # C / R body boxes for the checker (units)
RES = (-0.45, -1.1, 0.45, 1.1)
j1 = place("J1", 8, RV, refpos=(0, -1.5, "center"), hide_value=True, box=(-0.7, -0.6, 0.6, 0.6))
j2 = place("J2", 8, 32, refpos=(0, -1.5, "center"), hide_value=True, box=(-0.7, -0.6, 0.6, 0.6))
note("VIN 12 V", 6.5, RV + 0.4, size=1.0, just="right")
note("GND", 6.5, 32 + 0.4, size=1.0, just="right")
rail("VIN", 13, 21)
wire((13, 21), (13, RV))
power("power:PWR_FLAG", "PWR_FLAG", 18, RV)
wire(j2["1"], (14, 32), (14, 33))
rail("GND", 14, 33)
power("power:PWR_FLAG", "PWR_FLAG", 12, 32)
caps_in = [("C1", 22), ("C2", 28.5), ("C3", 35), ("C4", 41.5)]
for ref, cx in caps_in:
p = place(ref, cx, RV + 2.5, refpos=(1.5, -0.5, "left"), valpos=(1.5, 0.5, "left"), box=CAP)
wire((cx, RV), p["1"])
wire(p["2"], (cx, RV + 5))
rail("GND", cx, RV + 5)
BODIES.append(("C1-outline", 22 - 3.4, RV + 2.5 - 1.1, 22 - 1.2, RV + 2.5 + 1.1)) # C1's 3D outline, left of the can
# ---- Enable UVLO: R4 (VIN -> EN), R5 (EN -> GND), J3 on EN
E = 49.5
r4 = place("R4", E, RV + 2.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire((E, RV), r4["1"])
EN_Y = RO
wire(r4["2"], (E, EN_Y))
r5 = place("R5", E, EN_Y + 2.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire((E, EN_Y), r5["1"])
wire(r5["2"], (E, EN_Y + 5))
rail("GND", E, EN_Y + 5)
j3 = place("J3", 55.5, 33, mirror=True, refpos=(0, -1.5, "center"), hide_value=True, box=(-0.6, -0.6, 0.7, 0.6))
note("EN", 57, 33 + 0.4, size=1.0)
# ---- Buck converter: U1 + C5 bootstrap
# U1 = Adom-style TPS54202DDCR (2-column: Input VIN/EN + Ground GND left, Output BOOT/SW/FB right,
# 3D-chip outline in the body). Pins (units from the origin): VIN (-8, 1), EN (-8, 2), GND (-8, 5.5),
# BOOT (8, 1), SW (8, 2), FB (8, 3); body x -7..7, y -0.8..6.3.
XU, YU = 69, RO - 2
u1 = place("U1", XU, YU, refpos=(0, -1.8, "center"), valpos=(0, 7.3, "center"), box=(-7, -0.8, 7, 6.3))
wire((E, EN_Y), (53.5, EN_Y), u1["5"]) # EN node -> U1 EN
label("EN", 55.5, EN_Y)
wire((53.5, EN_Y), j3["1"]) # J3 hangs off the EN line
VD = 59.5 # VIN drop to the U1 VIN pin
wire((10, RV), (VD, RV), (VD, u1["3"][1]), u1["3"]) # VIN rail: J1 -> caps -> R4 -> U1 VIN
wire(j1["1"], (10, RV))
wire(u1["1"], (60.5, u1["1"][1]), (60.5, YU + 8))
rail("GND", 60.5, YU + 8)
XB = 82 # C5 column
c5 = place("C5", XB, 23.5, refpos=(1.5, -0.5, "left"), valpos=(1.5, 0.5, "left"), box=CAP)
wire(u1["6"], (79, u1["6"][1]), (79, 22), c5["1"]) # BOOT
label("BOOT", 79.5, 22)
wire(c5["2"], (XB, RO))
# ---- Output and feedback
XL = 92
l1 = place("L1", XL, RO, refpos=(0, 1.3, "center"), valpos=(0, 2.3, "center"), box=(-1.3, -0.3, 1.3, 0.1))
BODIES.append(("L1-outline", XL - 1.2, RO - 2.6, XL + 1.2, RO - 0.5)) # L1's 3D outline, above the coil
wire(u1["2"], l1["1"]) # SW node
label("SW", 85, RO)
caps_out = [("C6", 99), ("C7", 105.5), ("C8", 112)]
XR, XC9, XJ = 121, 129, 141
wire(l1["2"], (XJ - 2, RO)) # VOUT rail out to J4
for ref, cx in caps_out:
p = place(ref, cx, RO + 2.5, refpos=(1.5, -0.5, "left"), valpos=(1.5, 0.5, "left"), box=CAP)
wire((cx, RO), p["1"])
wire(p["2"], (cx, RO + 5))
rail("GND", cx, RO + 5)
label("VOUT", 95, RO)
r1 = place("R1", XR, RO + 2.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire((XR, RO), r1["1"])
r2 = place("R2", XR, RO + 7.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire(r1["2"], r2["1"])
label("FBM", XR, RO + 5, 180)
FBY = RO + 11
r3 = place("R3", XR, FBY + 2.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire(r2["2"], r3["1"])
wire(r3["2"], (XR, FBY + 5))
rail("GND", XR, FBY + 5)
c9 = place("C9", XC9, RO + 5, refpos=(1.5, -0.5, "left"), valpos=(1.5, 0.5, "left"), box=CAP)
wire((XC9, RO), c9["1"])
wire(c9["2"], (XC9, FBY), (XR, FBY))
wire(u1["4"], (78, u1["4"][1]), (78, FBY), (XR, FBY)) # FB back to U1
label("FB", 104, FBY)
rail("VOUT", 135, RO - 3)
power("power:PWR_FLAG", "PWR_FLAG", 132, RO)
wire((135, RO - 3), (135, RO))
j4 = place("J4", XJ, RO, mirror=True, refpos=(0, -1.5, "center"), hide_value=True, box=(-0.6, -0.6, 0.7, 0.6))
j5 = place("J5", XJ, RO + 4, mirror=True, refpos=(0, -1.5, "center"), hide_value=True, box=(-0.6, -0.6, 0.7, 0.6))
wire(j5["1"], (138, RO + 4), (138, RO + 5))
rail("GND", 138, RO + 5)
note("VOUT 5 V", XJ + 1.5, RO + 0.4, size=1.0)
note("GND", XJ + 1.5, RO + 4.4, size=1.0)
# ---- Indicator and monitor (lower left)
YB = 59
XD, XM = 9, 24
rail("VOUT", XD, YB - 1)
r6 = place("R6", XD, YB + 1.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire((XD, YB - 1), r6["1"])
d1 = place("D1", XD, YB + 7.5, refpos=(1.5, -0.5, "left"), valpos=(1.5, 0.5, "left"), box=(-0.6, -0.6, 0.6, 0.6))
BODIES.append(("D1-arrows", XD + 0.25, YB + 7.5 + 1.15, XD + 1.0, YB + 7.5 + 1.9)) # emission arrows
BODIES.append(("D1-outline", XD - 3.4, YB + 7.5 - 1.0, XD - 0.9, YB + 7.5 + 1.0)) # D1's 3D outline, left of the LED
wire(r6["2"], d1["2"])
label("LED", XD, YB + 4, 180)
wire(d1["1"], (XD, YB + 10))
rail("GND", XD, YB + 10)
rail("VOUT", XM, YB - 1)
r7 = place("R7", XM, YB + 1.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire((XM, YB - 1), r7["1"])
VM = YB + 4
r8 = place("R8", XM, VM + 2.5, refpos=(1.0, -0.5, "left"), valpos=(1.0, 0.5, "left"), box=RES)
wire(r7["2"], r8["1"])
wire(r8["2"], (XM, VM + 6))
rail("GND", XM, VM + 6)
j6 = place("J6", XM + 9, VM, mirror=True, refpos=(0, -1.5, "center"), hide_value=True, box=(-0.6, -0.6, 0.7, 0.6))
wire((XM, VM), j6["1"])
label("VMON", XM + 1.5, VM)
note("VMON", XM + 10.5, VM + 0.4, size=1.0)
# ---- Connectors: machine pins MP1-MP4 (GND) and test points TP1-TP5
XP = 48
for i, ref in enumerate(("MP1", "MP2", "MP3", "MP4")):
yy = YB + i * 3
p = place(ref, XP, yy, refpos=(-1.3, -1.0, "center"), hide_value=True, box=(-1.9, -0.4, 0.1, 0.4))
wire(p["1"], (XP + 4, yy))
wire((XP + 4, YB), (XP + 4, YB + 10))
rail("GND", XP + 4, YB + 10)
XT = 64
tp_net = [("TP1", "SW"), ("TP2", "FB"), ("TP3", "VOUT"), ("TP4", "GND"), ("TP5", "GND")] # TP5: probe ground 2.2 mm from TP3 (added for the probing workcell, 2026-10-06)
for i, (ref, nn) in enumerate(tp_net):
yy = YB + i * 3
p = place(ref, XT, yy, rot=90, refpos=(-1.3, -1.0, "center"), valpos=(-1.3, 1.0, "center"), hide_value=True,
box=(-1.9, -0.4, -0.9, 0.4))
wire(p["1"], (XT + 3, yy))
label(nn, XT + 3, yy)
# ---- sections and notes
section("Input", 1, 15, 48, 42)
section("Enable UVLO", 48, 15, 58.5, 42)
section("Buck converter", 58.5, 15, 89, 42)
section("Output and feedback", 89, 15, 149, 48)
section("Indicator and monitor", 1, 52, 42, 74)
section("Notes", 78, 52, 149, 74)
section("Connectors and test points", 42, 52, 78, 74)
note("TPS54202 synchronous buck, 12 V in, 5 V / 1 A out, fsw 500 kHz.\n"
"VOUT = 0.596 V x (1 + (R1 + R2) / R3) = 4.98 V.\n"
"C9 68 pF feed-forward across R1 + R2 (ngspice loop sweep, fc ~29 kHz).\n"
"EN UVLO R4 / R5: start 8.6 V, stop 6.9 V. J3 EN: pull low to disable.\n"
"VMON (J6) = VOUT / 2 for a 3.3 V ADC. D1 = output-on indicator.\n"
"J1-J6 MachineContactMedium; MP1-MP4 MachinePinMediumShort (corner pins, GND).", 80, 56)
# =========================================================================== wires -> sheet
def on_seg(p, a, b):
(x, y), (x0, y0), (x1, y1) = p, a, b
if x0 == x1 == x:
return min(y0, y1) < y < max(y0, y1)
if y0 == y1 == y:
return min(x0, x1) < x < max(x0, x1)
return False
pin_pts = [pt for ref, ps in PINS.items() for pt in ps.values()]
label_pts = [(x, y) for (_, x, y, _) in LABELS]
changed = True
while changed: # split every segment at any wire end / pin / label lying inside it
changed = False
ends = {p for s in SEGS for p in s} | set(pin_pts) | set(label_pts)
for i, (a, b) in enumerate(SEGS):
for p in ends:
if on_seg(p, a, b):
SEGS[i:i + 1] = [(a, p), (p, b)]
changed = True
break
if changed:
break
SEGS = list(dict.fromkeys(tuple(sorted(s)) for s in SEGS))
deg = {}
for a, b in SEGS:
deg[a] = deg.get(a, 0) + 1
deg[b] = deg.get(b, 0) + 1
for p in pin_pts:
deg[p] = deg.get(p, 0) + 1
junctions = sorted(p for p, d in deg.items() if d >= 3)
problems = []
pinset = set(pin_pts)
for p, d in deg.items():
if d == 1 and p not in pinset and p not in label_pts:
problems.append(f"dangling wire end at {p}")
for name, x, y, _ in LABELS:
if not any(on_seg((x, y), a, b) or (x, y) in (a, b) for a, b in SEGS):
problems.append(f"label {name} at {(x, y)} not on a wire")
for (ref, x0, y0, x1, y1) in BODIES:
for a, b in SEGS:
sx0, sx1 = sorted((a[0], b[0])); sy0, sy1 = sorted((a[1], b[1]))
if sx0 < x1 and sx1 > x0 and sy0 < y1 and sy1 > y0:
problems.append(f"wire {a}->{b} crosses body of {ref}")
for i in range(len(TEXTS)):
for j in range(i + 1, len(TEXTS)):
a, b = TEXTS[i], TEXTS[j]
if a[1] < b[3] and a[3] > b[1] and a[2] < b[4] and a[4] > b[2]:
problems.append(f"text overlap: {a[0]} / {b[0]}")
for t in TEXTS:
for a, b in SEGS:
sx0, sx1 = sorted((a[0], b[0])); sy0, sy1 = sorted((a[1], b[1]))
if sx0 <= t[3] and sx1 >= t[1] and sy0 <= t[4] - 0.05 and sy1 >= t[2] + 0.05 and not t[0].startswith("label"):
problems.append(f"wire {a}->{b} through text {t[0]}")
for (ref, x0, y0, x1, y1) in BODIES:
if t[1] < x1 and t[3] > x0 and t[2] < y1 and t[4] > y0 and not t[0].startswith(ref + "."):
problems.append(f"text {t[0]} over body of {ref}")
for (bx0, by0, bx1, by1) in BOXES: # section frames must not cut through text or symbols
edges = [((bx0, by0), (bx1, by0)), ((bx0, by1), (bx1, by1)), ((bx0, by0), (bx0, by1)), ((bx1, by0), (bx1, by1))]
for (ea, eb) in edges:
ex0, ex1 = sorted((ea[0], eb[0])); ey0, ey1 = sorted((ea[1], eb[1]))
for t in TEXTS:
if ex0 <= t[3] and ex1 >= t[1] and ey0 <= t[4] and ey1 >= t[2]:
problems.append(f"section edge {ea}->{eb} cuts text {t[0]}")
for (ref, x0, y0, x1, y1) in BODIES:
if ex0 <= x1 and ex1 >= x0 and ey0 <= y1 and ey1 >= y0:
problems.append(f"section edge {ea}->{eb} cuts {ref}")
for p in pin_pts + [q for s in SEGS for q in s]:
for v in p:
if abs(v * 2 - round(v * 2)) > 1e-6:
problems.append(f"off-grid point {p}")
for a, b in SEGS:
body.append([S("wire"), [S("pts"), [S("xy"), X(a[0]), Y(a[1])], [S("xy"), X(b[0]), Y(b[1])]],
[S("stroke"), [S("width"), 0], [S("type"), S("default")]], [S("uuid"), uid(f"w/{a}/{b}")]])
for p in junctions:
body.append([S("junction"), [S("at"), X(p[0]), Y(p[1])], [S("diameter"), 0], [S("color"), 0, 0, 0, 0],
[S("uuid"), uid(f"j/{p}")]])
for name, x, y, ang in LABELS:
body.append([S("label"), name, [S("at"), X(x), Y(y), ang], [S("fields_autoplaced"), S("yes")],
fnt(justify=["left", "bottom"] if ang == 0 else ["right", "bottom"]), [S("uuid"), uid(f"label/{name}/{x}/{y}")]])
for (x0, y0, x1, y1) in BOXES:
body.append([S("rectangle"), [S("start"), X(x0), Y(y0)], [S("end"), X(x1), Y(y1)],
[S("stroke"), [S("width"), 0.1524], [S("type"), S("dash")], [S("color"), 132, 132, 132, 1]],
[S("fill"), [S("type"), S("none")]], [S("uuid"), uid(f"box/{x0}/{y0}")]])
for (s, x, y) in TITLES:
body.append([S("text"), s, [S("exclude_from_sim"), S("no")], [S("at"), X(x), Y(y), 0],
fnt(size=2.0, bold=True, justify=["left", "bottom"]), [S("uuid"), uid(f"title/{s}")]])
for (s, x, y, size, bold, nj) in NOTES:
body.append([S("text"), S(sexp.q(s).replace("\n", "\\n")), [S("exclude_from_sim"), S("no")], [S("at"), X(x), Y(y), 0],
fnt(size=size, bold=bold, justify=[nj, "bottom"] if "\n" not in s else [nj, "top"]), [S("uuid"), uid(f"note/{s[:40]}/{x}/{y}")]])
sch = [S("kicad_sch"), [S("version"), 20250114], [S("generator"), "buck12v5v-gen"], [S("generator_version"), "2.0"],
[S("uuid"), ROOT], [S("paper"), "A3"],
[S("title_block"), [S("title"), net["title"]], [S("company"), "Adom"], [S("rev"), "A"],
[S("comment"), 1, "Generated from netlist.json; same source as the board"]],
[S("lib_symbols")] + list(lib_ids.values())] + body + \
[[S("sheet_instances"), [S("path"), "/", [S("page"), "1"]]]]
open(OUT, "w", encoding="utf-8").write(sexp.dump(sch) + "\n")
# the local power symbols also live in a project library, so ERC finds them and "update symbols
# from library" keeps them local (a global power:GND would rename the nets to "GND"/"VIN"/"VOUT")
plib = [S("kicad_symbol_lib"), [S("version"), 20241209], [S("generator"), "buck12v5v-gen"], [S("generator_version"), "2.0"]] + \
[local_power(n) for n in ("GND", "VIN", "VOUT")]
open(os.path.join(HERE, "lib", LOCAL_POWER + ".kicad_sym"), "w", encoding="utf-8").write(sexp.dump(plib) + "\n")
tbl = os.path.join(HERE, "sym-lib-table")
t = open(tbl, encoding="utf-8").read()
for nick, descr in ((LOCAL_POWER, "Sheet-local power symbols GND / VIN / VOUT (generated by gen_schematic_v2.py)"),
("buck12v5v", "Project symbols with 3D part outlines: U1 (tools/u1-symbol), L1 / C1 / D1 (tools/passive-symbols)")):
if f'(name "{nick}")' not in t:
entry = (f'\t(lib (name "{nick}")(type "KiCad")(uri "${{KIPRJMOD}}/lib/{nick}.kicad_sym")(options "")'
f'(descr "{descr}"))\n')
t = t.rstrip()[:-1].rstrip("\n") + "\n" + entry + ")\n"
open(tbl, "w", encoding="utf-8").write(t)
placed = {r for r in PINS if not r.startswith("#")}
missing = sorted(set(COMP) - placed)
if missing:
problems.append(f"parts not placed: {missing}")
print(json.dumps({"out": OUT, "symbols": len(placed), "wires": len(SEGS), "junctions": len(junctions),
"labels": len(LABELS), "problems": problems}, indent=1))