Skip to content

Instantly share code, notes, and snippets.

@aerialist
Last active September 28, 2024 04:41
Show Gist options
  • Save aerialist/e22118b6c92add4bc008bf7a33e9ded0 to your computer and use it in GitHub Desktop.
Save aerialist/e22118b6c92add4bc008bf7a33e9ded0 to your computer and use it in GitHub Desktop.
KiCad script to layout key switch matrix with LED. Copy code and run it in Scripting Console by right clicking to chose "Paste And Run".
# starting position
sw = {}
led = {}
reg = {}
diode = {}
sw['ref'] = 'K'
sw['start_x'] = 42.4
sw['start_y'] = 30.3
sw['orientation'] = 180
sw['side'] = 0 # layer 0 = 'Front'
led['ref'] = 'E'
led['start_x'] = 42.4
led['start_y'] = 35.35
led['orientation'] = 0
led['side'] = 0 # layer 0 = 'Front'
reg['ref'] = 'R'
reg['start_x'] = 37.1
reg['start_y'] = 30.3
reg['orientation'] = 0
reg['side'] = 0 # layer 0 = 'Front'
diode['ref'] = 'D'
diode['start_x'] = 37.1
diode['start_y'] = 35.35
diode['orientation'] = 180
#diode['side'] = 31 # layer 31 = 'Back'
diode['side'] = 0 # layer 0 = 'Front'
components = [sw, led, reg, diode]
# distance between key switches
dx = 10.6
dy = 10.1
# number of rows and columns of the matrix
# in schematics, I have 3x3 matrix as subsheet. In the main sheet, I have blocks of subseets.
#rown = 6
#coln = 15
inner_rown = 3
inner_coln = 3
block_rown = 2
block_coln = 5
set_aside = [39, 42, 45, 84, 87, 90, 82, 38]
shift_half = [47, 48, 55, 56, 57, 64, 65, 66, 73, 74, 75]
import pcbnew
board = pcbnew.GetBoard()
refn = 0
for brow in range(block_rown):
for bcol in range(block_coln):
for inrowi in range(inner_rown):
for incoli in range(inner_coln):
#refn = brow*(inner_rown*inner_coln*block_coln) + inrowi*(inner_coln*block_coln) + bcol*inner_coln + incoli
refn += 1
for comp in components:
reftxt = f"{comp['ref']}{refn}"
fp = board.FindFootprintByReference(reftxt)
x = comp['start_x'] + bcol * (dx*inner_coln) + dx*incoli
if refn in set_aside:
x += dx*5
if refn in shift_half:
x += dx/2
y = comp['start_y'] + brow * (dy*inner_rown) + dy*inrowi
fp.SetPos(pcbnew.VECTOR2I_MM(x, y))
fp.SetOrientationDegrees(comp['orientation'])
if comp['side'] == 31:
fp.SetLayerAndFlip(31)
pass
print(f"block({brow}, {bcol}) ({inrowi},{incoli}) x:{x} y:{y} ref:{reftxt}")
pcbnew.Refresh()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment