rushabhcodes/wireless-split-keyboard
Wireless Split Keyboard — custom routed nRF52840 split PCBs with a printable enclosure
- Version
- 0.4.5
- License
- unset
- Stars
- 0
Use with the tscircuit CLI
tsci is the tscircuit CLI. Install it with npm install -g tscircuit.
tsci clone rushabhcodes/wireless-split-keyboard # download the package files into ./wireless-split-keyboard
tsci add rushabhcodes/wireless-split-keyboard # add it to your project as @tsci/rushabhcodes.wireless-split-keyboardIn 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/generate-routing-input.py
"""Exact DSN routing interchange, retaining native pad geometry and locked outline.
No assembled reference PCB or source copper is imported."""
from pathlib import Path
import sys,json,math,hashlib
from collections import defaultdict
from shapely.geometry import box,Point,LineString
from shapely.affinity import translate
from shapely.ops import unary_union
from routing_model import BoardModel,LAYERS,DSN
root=Path(__file__).resolve().parents[1]
half=sys.argv[1] if len(sys.argv)>1 else 'right'
m=BoardModel(root/f'outputs/{half}/keyboard.circuit.json')
out=root/f'.cache/routing/{half}';out.mkdir(parents=True,exist_ok=True)
def q(s):return json.dumps(s)
def n(v):return f'{v*1000:.5f}'.rstrip('0').rstrip('.')
def pts(g):return ' '.join(f'{n(x)} {n(y)}' for x,y in list(g.exterior.coords)[:-1])
lines=['(pcb custom_sofle_'+half,' (parser (string_quote ") (space_in_quoted_tokens on))',' (resolution um 10) (unit um)',' (structure']
for i,l in enumerate(LAYERS):lines.append(f' (layer {DSN[l]} (type signal) (property (index {i})))')
lines.append(f' (boundary (path pcb 0 {pts(m.outline)} {n(m.outline.exterior.coords[0][0])} {n(m.outline.exterior.coords[0][1])}))')
lines+=[' (via Through_500_250)',' (rule (width 145) (clearance 125) (clearance 100 (type smd_smd)))']
# Drill holes are all-layer obstacles; extra radius accounts for 0.20 mm trace/drill clearance.
for i,e in enumerate(m.bytype['pcb_hole']):
for l in LAYERS:lines.append(f' (keepout hole_{i}_{l} (circle {DSN[l]} {n(e["hole_diameter"]+.15)} {n(e["x"])} {n(e["y"])}))')
# Protected reference-sensitive copper. Native source net names are retained.
seed=[];vias=[]
def wire(net,xy,width=.145,layer='bottom',name=None):
seed.append({'net':net,'layer':layer,'width':width,'points':[{'x':x,'y':y} for x,y in xy],'name':name})
def pinxy(ref,net):p=m.netpin(ref,net);return p['x'],p['y']
u=next(c for c in m.components.values() if m.sources[c['source_component_id']]['name']=='U1');ux,uy=u['footprint_origin']['x'],u['footprint_origin']['y']
shift=ux+54
# Nordic output match: ANT and VSS_PA stay on the component surface, no via in either RF pad.
ant=pinxy('U1','RF_ANT'); c1=pinxy('C_RF1','RF_ANT'); l1=pinxy('L_RF1','RF_ANT')
wire('RF_ANT',[ant,(-57.1+shift,34.1),(-57.65+shift,34.1),(-58.05+shift,c1[1]),c1,l1])
wire('RF_50',[pinxy('L_RF1','RF_50'),pinxy('C_RF2','RF_50'),(-62+shift,33.8108),pinxy('R_RF_T1','RF_50')],.20)
wire('RF_TUNE',[pinxy('R_RF_T1','RF_TUNE'),pinxy('R_RF_T2','RF_TUNE')],.20)
wire('RF_TUNE',[(-62+shift,39),pinxy('C_ANT_TUNE','RF_TUNE')],.20)
feed=pinxy('ANT1','RF_FEED');start=pinxy('R_RF_T2','RF_FEED')
wire('RF_FEED',[start,(start[0],44),(feed[0],45),feed],.20,name='T_ANT_FEED')
vss=next(p for p in m.byref['U1'] if 'VSS_PA' in m.sourceports[m.ports[p['element']['pcb_port_id']]['source_port_id']]['port_hints'])
wire('GND',[(vss['x'],vss['y']),(-57.1+shift,34.4),(-57.65+shift,34.4),(-58.035+shift,34.7853848),pinxy('C_RF1','GND'),pinxy('C_RF2','GND')])
ground_end=pinxy('C_RF2','GND')
wire('GND',[ground_end,(ground_end[0],35.95)])
vias.append({'net':'GND','x':ground_end[0],'y':35.95,'from_layer':'top','to_layer':'bottom','diameter':.5,'hole':.25,'kind':'Through_500_250'})
# Via-in-pad inner-row escapes, copper-filled/capped blind vias B.Cu to In2.Cu.
for p in m.byref['U1']:
if not p['net'] or p['net']=='RF_ANT':continue
sp=m.sourceports[m.ports[p['element']['pcb_port_id']]['source_port_id']]
if 'VSS_PA' in sp['port_hints']:continue
dx,dy=p['x']-ux,p['y']-uy
if 2.6<max(abs(dx),abs(dy))<2.9:
vias.append({'net':p['net'],'x':p['x'],'y':p['y'],'from_layer':'bottom','to_layer':'inner2','diameter':.35,'hole':.15,'kind':'Micro_B_L3'})
# Filled/capped thermal vias under the EP, distinct from blind signal escapes.
for dx in [-1.2,0,1.2]:
for dy in [-1.2,0,1.2]:vias.append({'net':'GND','x':ux+dx,'y':uy+dy,'from_layer':'top','to_layer':'bottom','diameter':.60,'hole':.30,'kind':'Thermal_600_300'})
# Full all-layer antenna clearance, with only the fixed surface feed and its two lands exempt.
zone=box((-61.5 if half=='right' else 47)-3.25,45.75,(-61.5 if half=='right' else 47)+3.25,52.25)
feed_shapes=[p['shape'].buffer(.130) for p in m.byref['ANT1']]
feed_shapes +=[LineString([(p['x'],p['y']) for p in w['points']]).buffer(w['width']/2+.130) for w in seed if w['net']=='RF_FEED']
for l in LAYERS:
g=zone.difference(unary_union(feed_shapes)) if l=='bottom' else zone
for i,gp in enumerate(g.geoms if hasattr(g,'geoms') else [g]):
if gp.area>1e-8:lines.append(f' (keepout antenna_{l}_{i} (polygon {DSN[l]} 0 {pts(gp)}))')
# Reserve the feed's adjacent reference layer against routed wires; ground fill is added after routing.
ref_zone=LineString([(start[0],35.8),(start[0],44),(feed[0],45.5)]).buffer(.65,cap_style='flat')
lines.append(f' (wire_keepout rf_reference (polygon In2.Cu 0 {pts(ref_zone)}))')
match_zone=box(-62.375+shift,33.1,-57.625+shift,35.5)
for l in ['inner1','inner2']:
lines.append(f' (keepout rf_match_{l} (polygon {DSN[l]} 0 {pts(match_zone)}))')
lines.append(' )')
# Every image is unique: no deduplication by bounding-box dimensions or lost component rotations.
lines.append(' (placement')
for cid,c in m.components.items():
ref=m.sources[c['source_component_id']]['name'];o=c.get('footprint_origin',c['center'])
lines.append(f' (component {q("image_"+ref)} (place {q(ref)} {n(o["x"])} {n(o["y"])} front 0))')
lines.append(' )\n (library')
for cid,c in m.components.items():
ref=m.sources[c['source_component_id']]['name'];o=c.get('footprint_origin',c['center'])
lines.append(f' (image {q("image_"+ref)}')
for p in m.byref[ref]:lines.append(f' (pin {q("pad_"+p["id"])} {q(p["id"])} {n(p["x"]-o["x"])} {n(p["y"]-o["y"])})')
lines.append(' )')
for p in m.pads:
e=p['element'];lines.append(f' (padstack {q("pad_"+p["id"])}')
local=translate(p['shape'],-p['x'],-p['y'])
for l in p['layers']:
if e['shape']=='circle':lines.append(f' (shape (circle {DSN[l]} {n(e.get("radius",e.get("outer_diameter",0)/2)*2)}))')
else:lines.append(f' (shape (polygon {DSN[l]} 0 {pts(local)}))')
lines.append(' (attach off))')
for name,ls,d in [('Through_500_250',LAYERS,.5),('Thermal_600_300',LAYERS,.6),('Micro_B_L3',['inner2','bottom'],.35)]:
lines.append(f' (padstack {name} '+''.join(f'(shape (circle {DSN[l]} {n(d)}))' for l in ls)+'(attach off))')
lines.append(' )\n (network')
for net,pads in m.netpads.items():
lines.append(f' (net {q(net)} (pins '+ ' '.join(f'{p["ref"]}-{p["id"]}' for p in pads)+'))')
critical={'XC1','XC2','XL1','XL2','DCC','DCC_FILTER','DEC4_6','DEC1','DEC3','DEC5','DECUSB','SW_NODE1','SW_NODE2','REG_FB','CH_ISET','CH_ILIM','BAT_NTC'}
for group,nets in [('critical',[net for net in m.netpads if net in critical]),('USB',[net for net in m.netpads if net in ['USB_DP','USB_DM']]),('default',[net for net in m.netpads if net not in critical and net not in ['USB_DP','USB_DM']])]:
lines.append(' (class '+group+' '+' '.join(q(net) for net in nets)+' (circuit (use_via Through_500_250)) (rule (width 145) (clearance 125)))')
lines.append(' )\n (wiring')
for w in seed:
path=' '.join(f'{n(p["x"])} {n(p["y"])}' for p in w['points'])
lines.append(f' (wire (path {DSN[w["layer"]]} {n(w["width"])} {path}) (net {q(w["net"])}) (type protect))')
for v in vias:lines.append(f' (via {v["kind"]} {n(v["x"])} {n(v["y"])} (net {q(v["net"])}) (type protect))')
lines.append(' ))')
(out/'input.dsn').write_text('\n'.join(lines)+'\n')
(out/'seed.json').write_text(json.dumps({'traces':seed,'vias':vias,'referenceZone':list(ref_zone.exterior.coords),'stackup':'4-layer 1+2+1 HDI, 0.15/0.35 mm copper-filled/capped B-L3 microvias'},indent=2)+'\n')
(out/'pad-map.json').write_text(json.dumps([{k:v for k,v in p.items() if k not in ['element','component','shape']} for p in m.pads],indent=2)+'\n')
print(half,len(m.pads),'pads',len(m.netpads),'nets',len(vias),'fixed vias',len(seed),'fixed RF paths')