Project 7: PCB Design for a Custom Keyboard
Design a complete keyboard PCB (schematic, layout, and manufacturing files) that matches your QMK firmware assumptions.
Quick Reference
| Attribute | Value |
|---|---|
| Difficulty | Level 4: Advanced |
| Time Estimate | 4-8 weeks |
| Main Programming Language | C + KiCad |
| Alternative Programming Languages | None |
| Coolness Level | Level 5: Pure Magic |
| Business Potential | Level 4: Hardware Founder |
| Prerequisites | QMK matrix knowledge, basic KiCad |
| Key Topics | Schematic design, USB routing, DRC/DFM |
1. Learning Objectives
By completing this project, you will:
- Design a matrix schematic that matches QMK pin mapping.
- Select an MCU and supporting components (USB, ESD, crystal if needed).
- Route a PCB that passes DRC and manufacturing checks.
- Generate Gerbers and drill files for fabrication.
- Validate that firmware assumptions match the PCB design.
2. All Theory Needed (Per-Concept Breakdown)
2.1 Matrix Schematic Design and MCU Selection
Fundamentals
A keyboard PCB schematic translates the matrix wiring model into a manufacturable circuit. You must choose an MCU with enough GPIO pins, USB support, and flash/RAM capacity for QMK features. The schematic must define the matrix: rows and columns connected through switches and diodes, with clear labeling that matches the firmware configuration. Each net in the schematic becomes a physical trace on the board, so a clean schematic is the foundation of a reliable PCB.
Deep Dive into the Concept
Schematic design starts with requirements: number of keys, matrix size, USB connectivity, and optional peripherals like RGB or OLED. The matrix defines the minimum number of GPIO pins. For example, a 5x14 matrix needs 19 GPIO pins. You must pick an MCU that provides at least that many usable GPIOs plus any pins required for USB D+/D-, reset, bootloader, and optional peripherals. This is why MCU selection is a first-class design decision. Common choices are ATmega32U4 (native USB, QMK support) or ARM MCUs like STM32F072 or RP2040.
Once the MCU is chosen, you assign row and column nets to specific pins. This is not arbitrary: some pins may be input-only, some shared with crystal or debug, and some have special functions. You should reserve a hardware reset pin and, if required, a bootloader pin. In QMK, you will later define MATRIX_ROW_PINS and MATRIX_COL_PINS that must match the schematic net names. A mismatch between schematic and firmware is the most common cause of a dead keyboard after assembly.
Diodes must be included for each switch. In the schematic, each switch connects between a row net and a column net with a diode in series. The diode orientation must match the firmware’s DIODE_DIRECTION. If your firmware expects COL2ROW, then the diode arrow should point toward the row net. In a schematic, consistent diode orientation makes PCB layout and assembly straightforward. A good practice is to keep all diodes oriented the same way for easy placement.
MCU selection also affects clocking and USB. Some MCUs require an external crystal for USB timing; others use an internal oscillator with calibration. For example, ATmega32U4 can use a crystal or internal oscillator but typically uses an external crystal for stability. The schematic must include crystal and load capacitors if needed. If you select a MCU like RP2040, you must include its required crystal and proper USB circuit. You must also include decoupling capacitors near each power pin; this is non-negotiable for stability.
The schematic should include a power distribution strategy: USB 5V input, optional voltage regulators for 3.3V peripherals, and proper grounding. The keyboard should have a clear ground plane and proper decoupling. If you plan to add RGB or OLED, you must consider the power budget and include current-limiting resistors where required. A well-designed schematic anticipates firmware features and hardware constraints.
Additional schematic discipline: treat each net name as a firmware interface. Prefix row and column nets consistently (e.g., R0-R5, C0-C14) and match those labels in your QMK configuration. Add test points for at least one row and column so you can validate the matrix after assembly. For USB, include a fuse or polyfuse if you expect the device to be exposed to unknown USB ports. Place decoupling capacitors as close to MCU power pins as possible, and follow the datasheet recommendations on capacitor values and placement.
Extra schematic insight: pin swapping can dramatically improve routing, but only if you update your firmware mapping to match. In KiCad, you can use net labels and a consistent naming scheme to prevent accidental swaps. Add test pads for USB D+/D- and key matrix lines so you can probe signals on a finished board. These pads are cheap to add and invaluable for debugging early prototypes.
How this fits on projects
This concept is central to Project 7 and feeds directly into Project 11 (production-ready product line). It also relies on the matrix understanding from Project 1 and 3.
Definitions & key terms
- Net: A named electrical connection in a schematic.
- MCU: Microcontroller unit used to run firmware.
- Decoupling capacitor: Capacitor placed near power pins to stabilize voltage.
- DIODE_DIRECTION: QMK setting that must match diode orientation.
Mental model diagram (ASCII)
Row nets ----switch----|>|---- Column nets
diode
MCU pins -> row/col nets -> matrix
How it works (step-by-step, with invariants and failure modes)
- Define matrix size and row/col nets.
- Select MCU with enough GPIO and USB support.
- Assign row/col nets to MCU pins.
- Add diodes, USB connector, decoupling caps.
Invariant: schematic net names must match firmware pin mapping. Failure modes include missing diodes, swapped rows/cols, and insufficient GPIO.
Minimal concrete example
R0 -> MCU pin D1
R1 -> MCU pin D0
C0 -> MCU pin C6
C1 -> MCU pin D7
Common misconceptions
- “Any MCU with enough pins works”: USB support and QMK compatibility are critical.
- “Diodes can be placed anywhere”: Orientation and consistency matter.
- “Firmware can fix wiring”: Wrong net assignments are hardware bugs.
Check-your-understanding questions
- How do you determine the number of GPIO pins required?
- Why must diode orientation match
DIODE_DIRECTION? - What happens if you choose an MCU without native USB?
Check-your-understanding answers
- Rows + columns + extra pins for USB, reset, and peripherals.
- Because scan direction expects current flow in a specific direction.
- You need an external USB controller or you cannot implement USB HID easily.
Real-world applications
- Custom keyboard PCB design.
- Embedded control panels and button matrices.
Where you’ll apply it
- In this project: §3.2 Functional Requirements and §5.10 Phase 1.
- Also used in: Project 11.
References
- “Designing Electronics That Work” by Hunter Scott.
- QMK hardware and handwired docs.
Key insights
The schematic is the single source of truth for both hardware and firmware; any mismatch is a guaranteed failure.
Summary
PCB design starts with a clean schematic that encodes matrix wiring and MCU selection. A correct schematic makes firmware mapping straightforward and reliable.
Homework/Exercises to practice the concept
- Calculate GPIO needs for a 6x15 matrix.
- Identify an MCU that meets the requirements and list its pins.
Solutions to the homework/exercises
- 6 + 15 = 21 pins, plus USB and reset pins.
- Example: RP2040 with enough GPIO and native USB support.
2.2 USB Routing, ESD Protection, and Manufacturing Constraints
Fundamentals
USB signaling is high-speed and sensitive to impedance and routing quality. The D+ and D- lines must be routed as a matched differential pair, with short and symmetric traces. ESD protection is essential to prevent damage from static discharge. Manufacturing constraints like trace width, clearance, and via sizes must be respected to ensure the board can be fabricated reliably. KiCad’s DRC rules enforce many of these constraints, but you must design with them in mind from the start.
Deep Dive into the Concept
USB full-speed (12 Mbps) uses differential signaling on D+ and D- lines. These traces should be routed as a pair with consistent spacing and length matching. While full-speed USB is more forgiving than high-speed, poor routing can still cause enumeration failures or unreliable connections. The recommended approach is to route D+ and D- on the same layer, keep them short, avoid sharp corners, and maintain consistent impedance. Avoid stubs and unnecessary vias. If you must change layers, do so symmetrically.
ESD protection is critical for USB connectors. A USB port is exposed to the outside world and is a common entry point for static discharges. A small ESD protection array (TVS diodes) near the connector can protect the MCU. The placement matters: the ESD device should be as close to the connector as possible so that the high-energy transient is shunted to ground before it reaches the MCU. You should also include a USB connector with a solid mechanical footprint and consider adding shield grounding if the connector supports it.
Manufacturing constraints are often ignored by beginners. Each PCB fab has minimum trace widths and clearances. If you design traces that are too thin or too close together, the board may fail DRC or be unmanufacturable. For keyboard PCBs, 0.2 mm traces and 0.2 mm clearance are common, but always check your fab’s capabilities. For USB traces, you might use wider traces (e.g., 0.3 mm) with proper spacing to approximate impedance control. KiCad allows you to set net classes for USB differential pairs with specific width and clearance.
Another critical manufacturing consideration is footprints. Incorrect footprints lead to assembly errors. Use verified footprints for the MCU, USB connector, and diodes. If you design your own footprint, validate it against the datasheet. For example, many USB-C connectors have non-standard pin arrangements and require specific mechanical holes. It’s common to break USB designs by using the wrong footprint or incorrect pin mapping for CC pins.
Finally, DRC and ERC are your safety nets. ERC checks schematic connectivity; DRC checks PCB layout constraints. Run them early and often. A “green” DRC report is not the end; you should still visually inspect critical nets like USB and power. Good manufacturing output includes Gerbers, drill files, and a pick-and-place file if you plan on assembly. This project requires generating a complete manufacturing package.
Additional layout best practices: keep the USB differential pair over a solid ground plane and avoid routing it across splits in the ground plane. When routing the matrix, use a consistent layer strategy to minimize vias, and keep row traces and column traces visually distinct for easier inspection. If you have RGB LEDs, consider adding a dedicated power trace with sufficient width. For manufacturing, generate a fabrication drawing and assembly drawing that call out key components and orientations; this reduces assembly mistakes, especially for diodes and USB connectors.
Extra manufacturing prep: include fiducials and tooling holes if you plan to use automated assembly. Panelization can reduce costs for small boards; if you expect to panelize, ensure your board edges and tabs follow the fabricator’s guidelines. A final review of the solder mask openings on USB and MCU pins is critical, as small errors here can cause assembly failures even if DRC passes.
How this fits on projects
USB routing and manufacturing constraints are crucial for Project 7 and influence Project 11, where you scale designs for production.
Definitions & key terms
- Differential pair: Two traces carrying complementary signals.
- ESD protection: Circuit elements that protect against static discharge.
- DRC/ERC: Design rule check and electrical rule check.
Mental model diagram (ASCII)
USB-C Connector -> ESD -> MCU USB pins
D+ --------------//--------------> D+
D- --------------//--------------> D-
How it works (step-by-step, with invariants and failure modes)
- Place USB connector and ESD close together.
- Route D+ and D- as matched pair.
- Set net class rules for USB traces.
- Run DRC and fix violations.
Invariant: USB traces must be short and matched. Failure modes include swapped D+/D-, excessive stubs, and missing ESD.
Minimal concrete example
Net class: USB_DIFF
Width: 0.3 mm
Clearance: 0.2 mm
Diff pair gap: 0.2 mm
Common misconceptions
- “USB full-speed doesn’t need careful routing”: It still needs matched pairs.
- “ESD is optional”: It’s a frequent failure point in the field.
- “DRC passing means it’s perfect”: DRC does not check signal integrity.
Check-your-understanding questions
- Why must D+ and D- be routed as a pair?
- Where should ESD protection be placed?
- What does DRC verify?
Check-your-understanding answers
- Differential signals require matched length and impedance to avoid noise.
- As close as possible to the USB connector.
- DRC checks trace widths, clearances, and layout rules.
Real-world applications
- USB device hardware design.
- Manufacturing-ready PCB production.
Where you’ll apply it
- In this project: §3.3 Non-Functional Requirements and §5.10 Phase 2.
- Also used in: Project 11.
References
- KiCad documentation on differential pairs.
- USB 2.0 layout guidelines.
Key insights
USB reliability is often determined by layout quality and ESD protection, not firmware.
Summary
Careful routing and manufacturing awareness turn a schematic into a reliable product. USB and power nets deserve extra attention.
Homework/Exercises to practice the concept
- Define a USB differential net class in KiCad.
- Run DRC on a sample PCB and fix all errors.
Solutions to the homework/exercises
- Create a net class with width/clearance settings for D+/D-.
- Resolve violations by adjusting trace width and spacing.
3. Project Specification
3.1 What You Will Build
A complete keyboard PCB design including:
- Schematic with matrix, MCU, USB, ESD, and power circuits.
- PCB layout with routed matrix and USB differential pair.
- Gerber and drill files ready for fabrication.
3.2 Functional Requirements
- Matrix schematic: correct diode orientation and row/col nets.
- MCU connectivity: USB, reset, and power correctly wired.
- PCB layout: passes DRC with zero errors.
- Manufacturing files: Gerbers and drill files generated.
3.3 Non-Functional Requirements
- Reliability: USB traces short and matched.
- Manufacturability: within fab rules.
- Maintainability: clean net naming and labeling.
3.4 Example Usage / Output
$ kicad-cli pcb drc keyboard.kicad_pcb
DRC finished: 0 errors, 2 warnings
3.5 Data Formats / Schemas / Protocols
- KiCad schematic (.kicad_sch) and PCB (.kicad_pcb) files.
- Gerber and drill files.
3.6 Edge Cases
- D+ and D- swapped (USB fails).
- Missing ESD (field failures).
- MCU pins misassigned (matrix not scanning).
3.7 Real World Outcome
A manufacturable PCB package that matches your QMK configuration.
3.7.1 How to Run (Copy/Paste)
kicad-cli pcb drc keyboard.kicad_pcb
kicad-cli pcb export gerbers keyboard.kicad_pcb -o gerbers/
3.7.2 Golden Path Demo (Deterministic)
- DRC passes with 0 errors.
- Gerbers include top, bottom, and drill files.
3.7.3 If CLI: exact terminal transcript
$ kicad-cli pcb drc keyboard.kicad_pcb
DRC finished: 0 errors, 0 warnings
exit_code=0
$ kicad-cli pcb export gerbers keyboard.kicad_pcb -o gerbers/
Exported: top.gbr, bottom.gbr, drill.drl
exit_code=0
$ kicad-cli pcb drc missing_file.kicad_pcb
error: file not found
exit_code=2
4. Solution Architecture
4.1 High-Level Design
Schematic -> Netlist -> PCB Layout -> DRC -> Gerbers
4.2 Key Components
| Component | Responsibility | Key Decisions |
|---|---|---|
| Schematic | Define matrix and MCU connections | Diode orientation, pin map |
| Layout | Route traces and USB pairs | Net classes and clearances |
| DRC/DFM | Ensure manufacturability | Fab rules selection |
| Output | Generate Gerbers and drills | File naming conventions |
4.3 Data Structures (No Full Code)
Netlist: R0, R1, C0, C1, USB_D+, USB_D-, VBUS, GND
4.4 Algorithm Overview
Key Algorithm: PCB Validation
- Run ERC on schematic.
- Run DRC on PCB layout.
- Fix violations.
- Export manufacturing files.
Complexity Analysis:
- Time: O(n) for DRC checks
- Space: O(n) nets and components
5. Implementation Guide
5.1 Development Environment Setup
kicad --version
kicad-cli --help
5.2 Project Structure
keyboard-pcb/
├── keyboard.kicad_sch
├── keyboard.kicad_pcb
├── gerbers/
└── README.md
5.3 The Core Question You’re Answering
“How do I turn a firmware design into reliable, manufacturable hardware?”
5.4 Concepts You Must Understand First
- Matrix schematic and MCU pin mapping.
- USB routing and ESD placement.
- DRC/DFM rules for manufacturing.
5.5 Questions to Guide Your Design
- How many rows/cols will your matrix have?
- Which MCU pins are safe for rows/cols?
- What fab rules will you design to?
5.6 Thinking Exercise
Given a 5x14 matrix, list the required GPIO pins and choose an MCU that supports them.
5.7 The Interview Questions They’ll Ask
- How do you choose an MCU for a keyboard design?
- Why is USB routing sensitive?
- What does DRC check vs ERC?
5.8 Hints in Layers
Hint 1: Use a reference design Start from a known QMK-compatible schematic.
Hint 2: Lock down the matrix Define rows/cols early to avoid rework.
Hint 3: Route USB first Keep D+/D- short and matched.
Hint 4: Run DRC often Fix issues as they appear.
5.9 Books That Will Help
| Topic | Book | Chapter |
|---|---|---|
| Hardware basics | “Designing Electronics That Work” | Ch. 1-4 |
| Embedded systems | “Making Embedded Systems” | Ch. 2-4 |
| Digital logic | “Digital Design and Computer Architecture” | Ch. 1-2 |
5.10 Implementation Phases
Phase 1: Schematic (2-3 weeks)
Goals: full schematic and ERC pass
Tasks:
- Create matrix schematic and diode orientation.
- Add MCU, USB, ESD, power nets.
Checkpoint: ERC passes with zero errors.
Phase 2: Layout (2-3 weeks)
Goals: PCB layout and DRC pass
Tasks:
- Place components and route USB.
- Route matrix and power nets.
Checkpoint: DRC passes with zero errors.
Phase 3: Manufacturing (1-2 weeks)
Goals: export Gerbers and review
Tasks:
- Generate Gerbers and drill files.
- Review in a Gerber viewer.
Checkpoint: Files ready for fabrication.
5.11 Key Implementation Decisions
| Decision | Options | Recommendation | Rationale |
|---|---|---|---|
| MCU choice | ATmega32U4 vs RP2040 | RP2040 | more flash and RAM |
| USB connector | USB-C vs Micro-USB | USB-C | modern standard |
| Diode footprint | SMD vs through-hole | SMD | compact routing |
6. Testing Strategy
6.1 Test Categories
| Category | Purpose | Examples |
|---|---|---|
| Schematic Tests | Verify connectivity | ERC results |
| Layout Tests | Verify manufacturability | DRC results |
| Output Tests | Verify Gerber generation | Gerber viewer |
6.2 Critical Test Cases
- USB D+/D- nets correctly connected to MCU pins.
- All row/col nets connected to MCU GPIO.
- DRC has zero errors.
6.3 Test Data
Netlist: R0-R4, C0-C13, USB_D+, USB_D-
7. Common Pitfalls & Debugging
7.1 Frequent Mistakes
| Pitfall | Symptom | Solution |
|---|---|---|
| Swapped D+ / D- | USB fails enumeration | Re-check USB connector pins |
| Missing decoupling caps | Unstable MCU behavior | Place caps near power pins |
| Wrong diode orientation | Ghosting or dead keys | Match schematic to firmware |
7.2 Debugging Strategies
- Print net labels on the PCB to cross-check firmware mapping.
- Use a Gerber viewer to verify USB trace routing.
7.3 Performance Traps
Long, skinny traces for power nets can cause voltage drops. Use wider traces for VBUS and GND.
8. Extensions & Challenges
8.1 Beginner Extensions
- Add a reset button footprint.
- Add test pads for rows and columns.
8.2 Intermediate Extensions
- Add RGB underglow LEDs.
- Add an OLED header.
8.3 Advanced Extensions
- Design a split keyboard PCB with TRRS or JST connector.
- Add ESD and EMI filtering for production readiness.
9. Real-World Connections
9.1 Industry Applications
- Custom keyboard products.
- Embedded input devices.
9.2 Related Open Source Projects
- ai03 keyboard PCB guides.
- Open-source keyboard schematics (e.g., Lily58).
9.3 Interview Relevance
- Demonstrates end-to-end hardware design and manufacturability.
10. Resources
10.1 Essential Reading
- “Designing Electronics That Work” by Hunter Scott.
- QMK hardware guides.
10.2 Video Resources
- KiCad keyboard PCB tutorials.
10.3 Tools & Documentation
- KiCad, KiCad CLI, Gerber viewer.
10.4 Related Projects in This Series
- Project 3: handwired matrix.
- Project 11: production scaling.
11. Self-Assessment Checklist
11.1 Understanding
- I can explain how the matrix schematic maps to firmware pins.
- I can describe why USB routing needs care.
11.2 Implementation
- ERC and DRC pass.
- Gerbers are generated and verified.
11.3 Growth
- I can select MCU components based on requirements.
12. Submission / Completion Criteria
Minimum Viable Completion:
- Full schematic with matrix and MCU.
- DRC passes and Gerbers generated.
Full Completion:
- USB routing and ESD included.
- Documentation of pin mapping and design decisions.
Excellence (Going Above & Beyond):
- Manufacturing package with BOM and assembly drawings.
- Prototype assembled and validated with QMK.