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-controllerIn 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.
encoder-mount/update_assembly.py
"""Swap the encoder parts in assets/connected-system.glb for the project's own encoder board,
its holder, magnet cap and 5-way cable.
Stop-gap: the assembly is normally generated by `bun run assembly:build` from assembly/, which is
not part of the published package. Port this change there before regenerating, or it is lost.
Everything else in the file (motor, leads, USB cables, display parts) is copied through unchanged.
Run: enclosure/.venv/bin/python encoder-mount/update_assembly.py
"""
from pathlib import Path
import hashlib, json, math, struct
import numpy as np
import trimesh
import manifold3d as mf
import mount
ROOT = Path(__file__).resolve().parent.parent
GLB = ROOT / "assets" / "connected-system.glb"
PROVENANCE = ROOT / "assets" / "connected-system.provenance.json"
MOTOR_AXIS = (-12.0, 127.0) # x, z of the motor axis in the assembly; its base plane is y = 0
REMOVE = ("ENCODER_BOARD", "ENCODER_BRACKET_STUDY", "ENCODER_COUPLER_STUDY", "ENCODER_MAGNET",
"ENCODER_BOARD_SPACER_", "ENCODER_BOARD_SCREW_", "ENCODER_BOARD_NUT_", "ENCODER_CONTACT_", "ENCODER_WIRE_",
"ENCODER_HOLDER_STUDY", "ENCODER_MAGNET_CAP_STUDY", "ENCODER_CABLE_PLUG_J30")
# existing material slots in the file, reused so the colours stay consistent
MAT = {"board": 11, "chip": 12, "study": 15, "magnet": 16, "cap": 17, "screw": 19, "plug": 21, "wires": [26, 27, 28, 29, 30]}
def to_assembly(v):
"""Mount frame (X, Y, Z-up) -> node-local assembly frame (x, y-up, z); the node sits on the motor axis."""
v = np.asarray(v, float)
return np.stack([v[:, 0], v[:, 2], -v[:, 1]], axis=1)
def flat(solid):
"""Manifold solid -> flat-shaded position/normal/index arrays in the assembly frame."""
m = solid.to_mesh()
tri = trimesh.Trimesh(vertices=to_assembly(m.vert_properties[:, :3]), faces=m.tri_verts, process=False)
pos = tri.vertices[tri.faces].reshape(-1, 3).astype(np.float32)
nor = np.repeat(tri.face_normals, 3, axis=0).astype(np.float32)
return dedupe(pos, nor, np.arange(len(pos)))
def dedupe(pos, nor, idx):
key = np.ascontiguousarray(np.hstack([pos, nor])).view(np.dtype((np.void, 24))).reshape(-1)
_, first, inv = np.unique(key, return_index=True, return_inverse=True)
order = np.argsort(first); rank = np.empty_like(order); rank[order] = np.arange(len(order))
return pos[first[order]], nor[first[order]], rank[inv.reshape(-1)][idx]
def tube(path, radius, sides=6):
"""Smooth-shaded tube along a polyline given in assembly coordinates."""
path = np.asarray(path, float); n = len(path)
tangent = np.gradient(path, axis=0); tangent /= np.linalg.norm(tangent, axis=1)[:, None]
normal = np.cross(tangent[0], [0, 1, 0]); normal /= np.linalg.norm(normal)
rings, normals = [], []
for i in range(n):
if i:
normal = normal - tangent[i] * np.dot(normal, tangent[i]); normal /= np.linalg.norm(normal)
binormal = np.cross(tangent[i], normal)
for k in range(sides):
a = 2 * math.pi * k / sides; d = math.cos(a) * normal + math.sin(a) * binormal
rings.append(path[i] + radius * d); normals.append(d)
faces = []
for i in range(n - 1):
for k in range(sides):
a, b = i * sides + k, i * sides + (k + 1) % sides
faces += [[a, b, a + sides], [b, b + sides, a + sides]]
return np.array(rings, np.float32), np.array(normals, np.float32), np.array(faces, np.int64).reshape(-1)
def rounded(points, radius=7.0, steps=8):
"""Polyline with each interior corner replaced by a quadratic curve."""
pts = [np.asarray(p, float) for p in points]; out = [pts[0]]
for a, b, c in zip(pts, pts[1:], pts[2:]):
r = min(radius, np.linalg.norm(b - a) / 2, np.linalg.norm(c - b) / 2)
p0 = b + (a - b) / np.linalg.norm(a - b) * r; p2 = b + (c - b) / np.linalg.norm(c - b) * r
out += [(1 - t) ** 2 * p0 + 2 * (1 - t) * t * b + t ** 2 * p2 for t in np.linspace(0, 1, steps)]
out.append(pts[-1])
return np.array(out)
def main():
raw = GLB.read_bytes()
jl = struct.unpack("<I", raw[12:16])[0]
j = json.loads(raw[20:20 + jl]); binary = raw[28 + jl:]
types = {5126: np.float32, 5123: np.uint16, 5125: np.uint32}; width = {"SCALAR": 1, "VEC3": 3}
def read(i):
a = j["accessors"][i]; v = j["bufferViews"][a["bufferView"]]; n = width[a["type"]]
return np.frombuffer(binary, types[a["componentType"]], a["count"] * n, v.get("byteOffset", 0) + a.get("byteOffset", 0)).reshape(a["count"], n)
out = bytearray(); views = []; accessors = []
def push(arr, target, component, kind, bounds=None):
while len(out) % 4: out.append(0)
data = np.ascontiguousarray(arr).tobytes()
views.append({"buffer": 0, "byteOffset": len(out), "byteLength": len(data), "target": target}); out.extend(data)
acc = {"bufferView": len(views) - 1, "componentType": component, "count": int(len(arr)), "type": kind}
if bounds: acc["min"], acc["max"] = bounds
accessors.append(acc); return len(accessors) - 1
def primitive(pos, nor, idx, material):
big = len(pos) > 65535
return {"attributes": {"POSITION": push(pos, 34962, 5126, "VEC3", ([float(v) for v in pos.min(0)], [float(v) for v in pos.max(0)])),
"NORMAL": push(nor, 34962, 5126, "VEC3")},
"indices": push(np.asarray(idx, np.uint32 if big else np.uint16).reshape(-1, 1), 34963, 5125 if big else 5123, "SCALAR"),
"material": material}
# keep every node that is not an encoder part; their meshes are copied through unchanged
keep = [n for n in j["nodes"] if not n.get("name", "").startswith(REMOVE)]
removed = [n["name"] for n in j["nodes"] if n.get("name", "").startswith(REMOVE)]
meshes = []; remap = {}
for node in keep:
old = node.get("mesh")
if old is None: continue
if old not in remap:
prims = []
for p in j["meshes"][old]["primitives"]:
pa = j["accessors"][p["attributes"]["POSITION"]]
q = {k: v for k, v in p.items() if k not in ("attributes", "indices")}
q["attributes"] = {"POSITION": push(read(p["attributes"]["POSITION"]), 34962, 5126, "VEC3", (pa["min"], pa["max"])),
"NORMAL": push(read(p["attributes"]["NORMAL"]), 34962, 5126, "VEC3")}
ia = j["accessors"][p["indices"]]
q["indices"] = push(read(p["indices"]), 34963, ia["componentType"], "SCALAR")
prims.append(q)
remap[old] = len(meshes); meshes.append({**{k: v for k, v in j["meshes"][old].items() if k != "primitives"}, "primitives": prims})
node["mesh"] = remap[old]
nodes = keep
def add(name, prims, translation=(MOTOR_AXIS[0], 0.0, MOTOR_AXIS[1])):
meshes.append({"name": name, "primitives": prims})
nodes.append({"name": name, "mesh": len(meshes) - 1, "translation": [float(v) for v in translation]})
# coarser circles than the print files: this copy is only for viewing
original = mount.cyl
mount.cyl = lambda x, y, z0, z1, radius, segments=32: original(x, y, z0, z1, radius, 32)
holder, cap, env, z = mount.build()
mount.cyl = original
add("ENCODER_HOLDER_STUDY", [primitive(*flat(holder), MAT["study"])])
add("ENCODER_MAGNET_CAP_STUDY", [primitive(*flat(cap), MAT["cap"])])
add("ENCODER_MAGNET", [primitive(*flat(env["magnet"]), MAT["magnet"])])
add("ENCODER_BOARD", [primitive(*flat(env["board"]), MAT["board"]), primitive(*flat(env["chip"]), MAT["chip"]),
primitive(*flat(env["plug"]), MAT["plug"])])
b = mount.P["board"]
for i, (x, y) in enumerate(b["holes"], 1):
add(f"ENCODER_BOARD_SCREW_{i}", [primitive(*flat(mount.cyl(x, y, z["boardBottom"] - 2.0, z["boardBottom"], 2.3, 24)), MAT["screw"])])
# mating cable plug, pushed into the board's header, and five wires back to the plug at J20
plug_z0, plug_z1 = z["boardTop"] + 0.7, z["boardTop"] + 5.0
plug_end = b["plug"]["far"] + 5.5 # wire side of the mating plug
add("ENCODER_CABLE_PLUG_J30", [primitive(*flat(mount.box(-plug_end, -(b["plug"]["far"] - 1.5), -6.0, 6.0, plug_z0, plug_z1)), MAT["plug"])])
harness = next(n for n in nodes if n.get("name") == "ENCODER_HARNESS_J20")
hx, hy, hz = harness["translation"]; hm = meshes[harness["mesh"]]["primitives"][0]
outer_x = hx + accessors[hm["attributes"]["POSITION"]]["min"][0] # wire side of the J20 plug
wire_y = (plug_z0 + plug_z1) / 2
for i in range(5):
level = hy + 0.9 * (i - 2) # stagger, so the one cable twist does not overlap
start = np.array([outer_x, hy, hz + (i - 2) * 2.0]) # J20 pin i+1
end = np.array([MOTOR_AXIS[0] - plug_end, wire_y, MOTOR_AXIS[1] - (4.0 - 2.0 * i)]) # J30 pin i+1
lane = min(outer_x, end[0]) - 6.0 - 1.2 * i # outside the enclosure wall
path = rounded([start, [start[0] - 2.0, level, start[2]], [lane, level, start[2]], [lane, wire_y, end[2]], end])
pos, nor, idx = tube(path, 0.4)
add(f"ENCODER_WIRE_{i + 1} / jacket", [primitive(pos, nor, idx, MAT["wires"][i])], translation=(0.0, 0.0, 0.0))
while len(out) % 4: out.append(0)
j["nodes"], j["meshes"], j["accessors"], j["bufferViews"], j["buffers"] = nodes, meshes, accessors, views, [{"byteLength": len(out)}]
j["scenes"][j.get("scene", 0)]["nodes"] = list(range(len(nodes)))
text = json.dumps(j, separators=(",", ":")).encode(); text += b" " * (-len(text) % 4)
total = 12 + 8 + len(text) + 8 + len(out)
data = struct.pack("<4sII", b"glTF", 2, total) + struct.pack("<I4s", len(text), b"JSON") + text + struct.pack("<I4s", len(out), b"BIN\0") + bytes(out)
GLB.write_bytes(data)
p = json.loads(PROVENANCE.read_text())
p["mechanicalAssetSha256"] = hashlib.sha256(data).hexdigest(); p["mechanicalAssetBytes"] = len(data)
holder_bounds = mount.mesh(holder).bounds
p["encoder"] = {
"part": "AS5047P-ATSM on the project encoder board (encoder-board.circuit.tsx)", "magnetPart": "6 x 2.5 mm diametric, e.g. Radial Magnets 9049",
"boardWidth": b["width"], "boardHeight": b["length"], "boardThickness": b["thickness"],
"holeX": 8.5, "holeY": 8.5, "holeDiameter": b["holeDiameter"], "boardTop": round(z["boardTop"], 3),
"sensorHeight": mount.P["sensor"]["chipHeight"], "gap": mount.P["sensor"]["gap"],
"magnetDiameter": mount.P["magnet"]["diameter"], "magnetHeight": mount.P["magnet"]["height"],
"pose": p.get("encoder", {}).get("pose", {"position": {"x": 12, "y": 127, "z": 0}, "rotation": {"x": 0, "y": 0, "z": 0}}),
"bracketWidth": round(float(holder_bounds[1][0] - holder_bounds[0][0]), 3), "bracketDepth": round(float(holder_bounds[1][1] - holder_bounds[0][1]), 3),
"shaftStickOut": mount.P["shaft"]["stickOut"], "shaftSource": mount.P["shaft"]["source"],
"status": "FIT STUDY: flat base from the seller's drawing; check the shaft end, its retainer and the lead exit on a motor",
"editedBy": "encoder-mount/update_assembly.py (not yet ported to assembly/full-assembly.tsx)",
}
PROVENANCE.write_text(json.dumps(p, indent=2) + "\n")
print(f"removed {len(removed)} old encoder nodes; file now has {len(nodes)} nodes, {len(data)} bytes (base64 {len(data) * 4 // 3})")
if __name__ == "__main__":
main()