aboutsummaryrefslogtreecommitdiff

Schematic generator (schgen)

tools/schgen.py writes KiCad 10 schematics from Python. Describe a circuit in a small script (e.g. modules/<name>/tools/gen_sch.py) and regenerate the schematic whenever it changes.

Use

import sys; sys.path.insert(0, "tools")
from schgen import Sheet, G
s = Sheet(project, "block.kicad_sch", root_uuid, sheet_uuid, "Sheet Name", paper="A3")
u = s.add("Amplifier_Operational:LM324", "U2", x, y, rot=0, unit=1, value="LM324BIPWR",  # dnp=True, in_bom=False for unfitted parts
          fp="Package_SO:TSSOP-14_4.4x5mm_P0.65mm", fields={"LCSC": "...", "MPN": "..."})
s.net(u, "3", "DAC1")          # 2.54 mm stub + local label, text runs away from the pin
s.power(u, "11", "GND")        # stub + power symbol turned to face away from the pin
s.hlabel(u, "1", "OUT", "output")
s.nc(u, "14"); s.text("note", x, y); s.write(path)
root = Sheet(project, "root.kicad_sch", root_uuid)
pins = root.sheet("Sheet Name", "block.kicad_sch", x, y, w, h, [("SDA", "bidirectional")], sheet_uuid, page="2")
  • Symbols come from KiCad's stock libraries (found by kicad_paths.py) or the repo's HW library (libraries/symbols/HW.kicad_sym). They are flattened into lib_symbols: extends is resolved and sub-units are renamed.
  • Pin positions: library Y points up, sheet Y points down, and rotation is counter-clockwise on screen. Mirroring is not supported.
  • UUIDs are uuid5 of project, sheet path, reference and unit, so regenerating writes the same file and the board keeps its links.
  • Check every result with kicad-cli sch erc and sch export netlist, and look at kicad-cli sch export svg.

Pitfalls met

  • A power symbol on a sideways pin first got a stub that turned down. It landed on the next pin's stub end and shorted three pins to GND; only the netlist showed it, ERC gave just a warning. power() now puts the symbol straight out from the pin and turns the symbol instead.
  • #PWR/#FLG references must be unique across all sheets. Start the root sheet's flags high, e.g. #FLG51. Duplicates make kicad-cli warn "schematic has annotation errors".
  • Page numbers: a root with several sheets needs a distinct page for each.
  • Layout units: layout is in grid units (G = 2.54 mm), and A3 is 165 × 117 grid units. Keep text off the border.

More schematic-as-file lessons: KiCad notes.