MustafaMulla29/rp2040-bldc-motor-controller

Hardware assembly metadata and PCB geometry for a controller board with a snap-off rotary-encoder section, plus four parallel 150 µF/50 V bulk electrolytic capacitors filtering the motor supply.

Version
2.0.40
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone MustafaMulla29/rp2040-bldc-motor-controller  # download the package files into ./rp2040-bldc-motor-controller
tsci add MustafaMulla29/rp2040-bldc-motor-controller    # add it to your project as @tsci/MustafaMulla29.rp2040-bldc-motor-controller

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

scripts/pcb-audit/audit-route-lengths.py

"""Read-only planar route estimates from actual copper, not ratsnest distances.

Split wire centerlines at touching copper and join them through real pads/vias.
Lengths include pad-center spokes but exclude vertical travel through the board.
This is a layout triage tool, not a loop-inductance or signal-integrity model.
"""
import collections
import hashlib
import heapq
import json
import math
import sys
from pathlib import Path
from shapely.geometry import LineString, Point
from shapely.ops import nearest_points
from shapely.strtree import STRtree
from geometry import padshape


def route_graph(segments, contacts):
    cuts = [{0.0, s['line'].length} for s in segments]
    links = []
    bylayer = collections.defaultdict(list)
    for i, s in enumerate(segments):
        bylayer[s['layer']].append(i)

    def tap(i, point):
        d = min(segments[i]['line'].length, max(0.0, segments[i]['line'].project(point)))
        d = round(d, 10)
        cuts[i].add(d)
        return ('wire', i, d)

    # Junctions include intentional overlaps in authored routes. Parallel copper
    # that physically touches is connected too; no same-net proximity shortcut.
    for layer, ids in bylayer.items():
        shapes = [segments[i]['line'].buffer(segments[i]['width'] / 2) for i in ids]
        tree = STRtree(shapes)
        for ii, i in enumerate(ids):
            a = segments[i]['line']
            for jj in tree.query(shapes[ii].buffer(1e-7)):
                j = ids[int(jj)]
                if j <= i or shapes[ii].distance(shapes[int(jj)]) > 1e-7:
                    continue
                b = segments[j]['line']
                pairs = [nearest_points(a, b)]
                # Both ends of a collinear overlap need split points.
                for p in [Point(a.coords[0]), Point(a.coords[-1])]:
                    q = b.interpolate(b.project(p))
                    if p.distance(q) < 1e-7:
                        pairs.append((p, q))
                for q in [Point(b.coords[0]), Point(b.coords[-1])]:
                    p = a.interpolate(a.project(q))
                    if p.distance(q) < 1e-7:
                        pairs.append((p, q))
                for p, q in pairs:
                    links.append((tap(i, p), tap(j, q), p.distance(q), None))

    pins = collections.defaultdict(list)
    for ci, c in enumerate(contacts):
        p = c['center']
        layers = c['layers']
        for layer in layers:
            key = ('contact', ci, layer)
            if c.get('label'):
                pins[c['label']].append(key)
            for i in bylayer.get(layer, []):
                s = segments[i]
                if s['line'].distance(c['shape']) <= s['width'] / 2 + 1e-7:
                    q = s['line'].interpolate(s['line'].project(p))
                    links.append((key, tap(i, q), p.distance(q), None))
        for a, b in zip(layers, layers[1:]):
            links.append((('contact', ci, a), ('contact', ci, b), 0, c['id']))
    # Pads/vias can directly touch, without an intervening trace.
    for i, a in enumerate(contacts):
        for j, b in enumerate(contacts[:i]):
            if a['shape'].distance(b['shape']) > 1e-7:
                continue
            for layer in set(a['layers']) & set(b['layers']):
                links.append((('contact', i, layer), ('contact', j, layer), a['center'].distance(b['center']), None))
    for i, ds in enumerate(cuts):
        ds = sorted(ds)
        for a, b in zip(ds, ds[1:]):
            links.append((('wire', i, a), ('wire', i, b), b - a, None))
    graph = collections.defaultdict(list)
    for a, b, length, via in links:
        graph[a].append((b, length, via))
        graph[b].append((a, length, via))
    return graph, pins


def shortest(graph, starts, ends):
    queue = [(0.0, i, n) for i, n in enumerate(starts)]
    heapq.heapify(queue)
    best = {n: 0.0 for n in starts}
    prev = {}
    counter = len(queue)
    while queue:
        d, _, n = heapq.heappop(queue)
        if d > best[n] + 1e-9:
            continue
        if n in ends:
            vias = set()
            layers = set()
            while True:
                if n[0] == 'contact':
                    layers.add(n[2])
                if n not in prev:
                    break
                n, via = prev[n]
                if via:
                    vias.add(via)
            return d, sorted(vias), sorted(layers)
        for dest, length, via in graph[n]:
            nd = d + length
            if nd + 1e-9 < best.get(dest, math.inf):
                best[dest] = nd
                prev[dest] = (n, via)
                counter += 1
                heapq.heappush(queue, (nd, counter, dest))
    raise RuntimeError(f'No copper path: {starts} -> {ends}')


def audit(path, output):
    raw = path.read_bytes()
    circuit = json.loads(raw)
    of = lambda kind: [x for x in circuit if x['type'] == kind]
    netkey = {x['subcircuit_connectivity_map_key']: x['name'] for x in of('source_net')}
    netid = {x['source_net_id']: x['name'] for x in of('source_net')}
    components = {x['source_component_id']: x['name'] for x in of('source_component')}
    ports = {x['source_port_id']: x for x in of('source_port')}
    pcbports = {x['pcb_port_id']: x for x in of('pcb_port')}
    traces = {x['source_trace_id']: x for x in of('source_trace')}
    poured_nets = {netid.get(x.get('source_net_id')) for x in of('pcb_copper_pour')}
    segments = collections.defaultdict(list)
    contacts = collections.defaultdict(list)
    pin_net = {}
    pin_center = {}
    for t in of('pcb_trace'):
        net = netid.get(t.get('connection_name')) or netkey.get(traces.get(t.get('source_trace_id'), {}).get('subcircuit_connectivity_map_key'))
        for a, b in zip(t['route'], t['route'][1:]):
            if a['route_type'] == b['route_type'] == 'wire' and a['layer'] == b['layer']:
                line = LineString([(a['x'], a['y']), (b['x'], b['y'])])
                if line.length > 1e-8:
                    segments[net].append(dict(line=line, layer=a['layer'], width=min(a['width'], b['width'])))
    for p in of('pcb_smtpad') + of('pcb_plated_hole'):
        s = ports[pcbports[p['pcb_port_id']]['source_port_id']]
        net = netkey.get(s.get('subcircuit_connectivity_map_key'))
        label = f"{components[s['source_component_id']]}.{s['pin_number']}"
        shape = padshape(p)
        pin_net[label] = net
        pin_center[label] = shape.centroid
        contacts[net].append(dict(id=p.get('pcb_smtpad_id', p.get('pcb_plated_hole_id')), label=label,
                                 shape=shape, center=shape.centroid, layers=p.get('layers', [p.get('layer', 'top')])))
    for v in of('pcb_via'):
        net = netkey.get(v.get('subcircuit_connectivity_map_key')) or netid.get(v.get('source_net_id'))
        p = Point(v['x'], v['y'])
        contacts[net].append(dict(id=v['pcb_via_id'], center=p, shape=p.buffer(v['outer_diameter'] / 2), layers=v['layers']))

    pairs = []
    def add(category, a, b): pairs.append((category, a, b))
    for a, b in [('U18.1','L2.2'), ('U18.6','C186.1'), ('U18.5','C187.1'),
                 ('U18.5','C183.1'), ('U18.3','R181.2'), ('U18.3','R182.1'),
                 ('U19.5','C185.1'), ('U22.6','C191.1'), ('U20.6','C189.1'),
                 ('U21.16','C190.1'), ('U23.1','C194.1'), ('U23.8','C193.1'),
                 ('U24.6','C195.1')]:
        add('oled-power-local-routing', a, b)
    for gate, r, pin, fet in [('GHA',90,11,10),('GLA',92,12,11),('GHB',94,15,12),('GLB',96,16,13),('GHC',98,19,14),('GLC',100,20,15)]:
        add('driver-to-gate-resistor', f'U7.{pin}', f'R{r}.1')
        add('resistor-to-MOSFET', f'R{r}.2', f'Q{fet}.1')
    for i in range(3):
        add('bootstrap-supply', f'U7.{9+4*i}', f'C{74+i}.1')
        add('bootstrap-return', f'U7.{10+4*i}', f'C{74+i}.2')
        add('high-side-source-return', f'U7.{10+4*i}', f'Q{10+2*i}.3')
        add('low-side-source-return', 'U7.21', f'Q{11+2*i}.3')
    for a, b in [('U7.6','C72.2'),('U7.7','C72.1'),('U7.8','C73.1'),('U7.26','C77.1'),('U7.36','C78.1'),('U7.2','C80.1'),('U7.5','C70.1')]:
        add('driver-local-capacitors', a, b)
    for a, b in [('U5.20','Y1.1'),('U5.21','R46.1'),('R46.2','Y1.3')]:
        add('crystal', a, b)
    for a, b in [(51,7),(52,6),(53,5),(54,3),(55,2),(56,1)]:
        add('QSPI', f'U5.{a}', f'U6.{b}')
    cache = {}
    results = []
    for category, a, b in pairs:
        net = pin_net[a]
        assert net == pin_net[b], (a,b,net,pin_net[b])
        assert net != 'GND', 'Ground pours require a loop/return model, not this centerline estimator'
        assert net not in poured_nets, f'Cannot estimate {net}: its pours need a separate path model'
        if net not in cache:
            cache[net] = route_graph(segments[net], contacts[net])
        graph, pins = cache[net]
        length, vias, layers = shortest(graph, pins[a], set(pins[b]))
        direct = pin_center[a].distance(pin_center[b])
        results.append(dict(category=category, net=net, start=a, end=b, planarLengthMm=round(length,3),
                            directDistanceMm=round(direct,3), detourRatio=round(length/direct,2),
                            viasUsed=vias, viaCount=len(vias), contactAndViaSpannedLayers=layers))
    report = dict(sha256=hashlib.sha256(raw).hexdigest(), scope=__doc__, paths=results)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(json.dumps(report, indent=2) + '\n')
    for r in results:
        print(f"{r['category']:24} {r['net']:12} {r['start']:7}->{r['end']:7} {r['planarLengthMm']:7.3f} mm, {r['viaCount']} vias, {r['detourRatio']:.2f}x direct")


if __name__ == '__main__':
    audit(Path(sys.argv[1]), Path(sys.argv[2]))