Advanced topics

Configuration and Customization

Pcbnew has a variety of preferences that can be configured through the Preferences dialog. Like all parts of KiCad, the preferences for Pcbnew are stored in the user configuration directory and are independent between KiCad minor versions to allow multiple versions to run side-by-side with independent preferences.

The first sections of the Preferences dialog (Common, Mouse and Touchpad, and Hotkeys) are shared between all KiCad programs. These sections are described in detail in the KiCad manual under the “Common preferences” section. Note that even though the Hotkeys section is shared between all programs, there are many Pcbnew-specific hotkeys that only appear in the list when Pcbnew is running.

Display options

pcbnew preferences display

Rendering Engine: Controls if Accelerated graphics or Fallback graphics are used.

Grid style: Controls how the alignment grid is drawn.

Grid thickness: Controls how thick grid lines or dots are drawn.

Min grid spacing: Controls the minimum distance, in pixels, between two grid lines. Grid lines that violate this minimum spacing will not be drawn, regardless of the current grid setting.

Snap to grid: Controls when drawing and editing operations will be snapped to coordinates on the active grid. “Always” will enable snapping even when the grid is hidden; “When grid shown” will enable snapping only when the grid is visible.

Grid snapping can be temporarily disabled by holding down Ctrl.

Cursor shape: Controls whether the editing cursor is drawn as a small crosshair or a full-screen crosshair (a set of lines covering the entire drawing canvas). The editing cursor shows where the next drawing or editing action will occur and will be snapped to a grid location if snapping is enabled.

Always show crosshairs: Controls whether the editing cursor is shown all the time or only when an editing or drawing tool is active.

Net names: Controls whether or not net name labels are drawn on copper objects. These labels are guides for editing only and do not appear in fabrication outputs.

Show pad numbers: Controls whether or not pad number labels are drawn on footprint pads.

Show pad <no net> indicator: Controls whether or not pads with no net are indicated with a special marker.

Track clearance: Controls whether or not clearance outlines around tracks and vias are shown. Clearance outlines are shown as thin shapes around objects that indicate the minimum clearance to other objects, as defined by constraints and design rules.

Show pad clearance: Controls whether or not clearance outlines around pads are shown.

Center view on cross-probed items: When both Eeschema and Pcbnew are running, controls whether clicking a component or pin in Eeschema will center the Pcbnew view on the corresponding footprint or pad.

Zoom to fit cross-probed items: Controls whether the view will be zoomed to show a cross-probed footprint or pad.

Highlight cross-probed nets: Controls whether or not nets highlighted in Eeschema will be highlighted in Pcbnew when the highlight tool is activated in both tools.

Editing options

pcbnew preferences editing

Flip board items L/R: Controls the direction board items will be flipped when moving them between the top and bottom layers. When checked, items are flipped Left-to-Right (about the Vertical axis); when unchecked, items are flipped Top-to-Bottom (about the Horizontal axis).

Step for rotate commands: Controls how far the selected object(s) will be rotated each time the Rotate command is used.

Allow free pads: Controls whether or not the pads of footprints can be unlocked and edited or moved separately from the footprint.

Magnetic points: This section controls object snapping, also called magnetic points. Object snapping takes precedence over grid snapping when it is enabled. Object snapping only works to objects on the active layer. Hold Shift to temporary disable object snapping.

Snap to pads: Controls when the editing cursor will snap to pad origins.

Snap to tracks: Controls when the editing cursor will snap to track segment endpoints.

Snap to graphics: Controls when the editing cursor will snap to graphic shape points.

Always show selected ratsnest: When enabled, the ratsnest for a selected footprint will always be shown even if the global ratsnest is hidden.

Show ratsnest with curved lines: Controls whether ratsnest lines are drawn straight or curved.

Mouse drag track behavior: Controls the action that will occur when you drag a track segment with the mouse: “Move” will move the track segment independent of any others. “Drag (45 degree mode)” will invoke the push-and-shove router to drag the track, respecting design rules and keeping other track segments attached. “Drag (free angle)” will move the nearest corner of the track segment, highlighting collisions with other objects but not moving them out of the way.

Limit actions to 45 degrees from start Controls whether lines drawn with the graphic drawing tools can take on any angle. Note that this only affects drawing new lines: lines can be edited to take on any angle.

Show page limits: Controls whether or not the page boundary is drawn as a rectangle.

Refill zones after Zone Properties dialog: Controls whether or not zones are automatically refilled after editing the properties of any zone. This may be disabled on complicated designs or slower computers to improve responsiveness.

Colors

pcbnew preferences colors

Pcbnew supports switching between different color themes to match your preferences. Kicad 6.0 comes with two built-in color themes: “KiCad Default” is a new theme designed to have good contrast and balance for most cases and is the default for new installations. “KiCad Classic” is the default theme from KiCad 5.1 and earlier versions. Neither of these built-in themes can be modified, but you can create new themes to customize the look of Pcbnew as well as install themes made by other users.

Color themes are stored in JSON files located in the colors subdirectory of the KiCad configuration directory. The “Open Theme Folder” button will open this location in your system file manager, making it easy to manage your installed themes. To install a new theme, place it in this folder and restart KiCad. The new theme will be available from the drop-down list of color themes if the file is a valid color theme file.

To create a new color theme, choose New Theme…​ from the drop-down list of color themes. Enter a name for your theme and then begin editing colors. The colors in the new theme will be copied from whatever theme was selected before you created the new theme.

To change a color, double-click or middle-click the color swatch in the list. The “Reset to Default” button will reset that color to its corresponding entry in the “KiCad Default” color theme.

Color themes are saved automatically; all changes are reflected immediately when you close the Preferences dialog. The window on the right side of the dialog shows a preview of how the selected theme will look.

Action plugins

pcbnew preferences action plugins

The KiCad PCB editor supports plugins written in Python that can perform actions on the board being edited. These plugins can be installed using the built-in Plugin and Content Manager (see the KiCad chapter for details) or by placing the plugin files inside the user plugins directory. See the Scripting section below for details.

Each plugin that is detected will be shown in a row on this preferences page. Plugins may show a button on the top toolbar of the PCB editor. If the “Show button” control is unchecked for a plugin, it may still be accessed from the Tools > External Plugins menu.

The arrow controls at the bottom of the list allow changing the order that the plugins appear in the toolbar and menu. The folder button will launch a file explorer to the plugin folder, to make installing new plugins easier. The refresh button will scan the plugin folder for any new or removed plugins and update the list.

Origin & axes

pcbnew preferences origin axes

Display origin: Determines which coordinate origin is used for coordinate display in the editing canvas. The page origin is fixed at the corner of the page. The drill/place file origin and the grid origin can be moved by the user.

X axis: Controls whether X-coordinates increase to the right or to the left.

Y axis: Controls whether Y-coordinates increase upwards or downwards.

Custom design rules

KiCad’s custom design rule system allows creating design rules that are more specific than the generic rules available in the Constrants page of the Board Setup dialog. Custom design rules have many applications, but in general they are used to apply certain rules to a portion of the board, such as a specific net or netclass, a specific area, or a specific footprint.

Custom design rules are stored in a separate file with the extension kicad_dru. This file is created automatically when you start adding custom rules to a project. If you are using custom rules in your project, make sure to save the kicad_dru file along with the kicad_pcb and kicad_pro files when making backups or committing to a version control system.

The kicad_dru file is managed automatically by KiCad and should not be edited with an external text editor. Always use the Custom Rules page of the Board Setup dialog to edit custom design rules.

The Custom Rules editor

The custom rules editor is located in the Board Setup dialog and provides a text editor for entering custom rules, a syntax checker that will test your custom rules and note any errors, and a syntax help dialog that contains a quick reference to the custom rules language and some example rules.

It is a good idea to use the Check rule syntax button after editing custom rules to make sure there are no syntax errors. Any errors in the custom rules will prevent the design rule checker from running.

Custom rule syntax

The custom design rule language is based on s-expressions and allows you to create design constraints that are not possible with the built-in constraints. Each design rule generally contains a condition defining what objects to match, and a constraint defining the rule to be applied to the matched objects.

The language uses parentheses (( and )) to define clauses of related tokens and values. Parentheses must always be matched: for every ( there must be a matching ). Inside a clause, tokens and values are separated by whitespace. By convention, a single space is used, but any number of whitespace characters between tokens is acceptable. In places where text strings are valid, strings without any whitespace may be quoted with " or ', or unquoted. Strings that contain whitespace must always be quoted. Where nested quotes are required, a single level of nesting is possible by using " for the outer quote character and ' for the inner (or vice versa). Newlines are not required, but are typically used in examples for clarity.

In the syntax descriptions below, items in <angle brackets> represent tokens that must be present and items in [square brackets] represent tokens that are optional or only sometimes required.

The Custom Rules file must start with a version header defining the version of the rules language. As of KiCad 6.0, the version is 1. The syntax of the version header is (version <number>). So in KiCad 6.0 the header should read:

  1. (version 1)

After the version header, you can enter any number of rules. Rules are evaluated in reverse order, meaning the last rule in the file is checked first. Once a matching rule is found for a given set objects being tested, no further rules will be checked. In practice, this means that more specific rules should be later in the file, so that they are evaluated before more general rules.

For example, if you create one rule that limits the minimum clearance between tracks in the net HV and tracks in any other net and a second rule that limits the minimum clearance for all objects inside a certain rule area, make sure the first rule appears later in the custom rules file than the second rule. Otherwise tracks in the HV net could have the wrong clearance if they fall inside the rule area.

Each rule must have a name and one or more constraint clause. The name can be any string and is used to refer to the rule in DRC reports. The constraint defines the behavior of the rule. Rules may also have a condition clause that determines which objects should have the rule applied and an optional layer clause, which specifies which board layers the rule applies to.

  1. (rule <name>
  2. [(layer <layer_name>)]
  3. [(condition <expression>)]
  4. (constraint <constraint_type> [constraint_arguments]))

The custom rules file may also include comments to describe rules. Comments are denoted by any line that begins with the # character (not including whitespace).

  1. # Clearance for 400V nets to anything else
  2. (rule HV
  3. (condition "A.NetClass == 'HV'")
  4. (constraint clearance (min 1.5mm)))
Layer Clause

The layer clause determines which layers the rule will work on. While the layer of objects can be tested in the condition clause as described below, using the layer clause is more efficient.

The value of the layer clause can be any board layer name, or the shortcuts outer to match the front and back copper layers (F.Cu and B.Cu) and inner to match any internal copper layers.

If the layer clause is omitted, the rule will apply to all layers.

Some examples:

  1. # Do not allow footprints on back layer (no condition clause means this rule always applies)
  2. (rule "Top side footprints only"
  3. (layer B.Cu)
  4. (constraint disallow footprint))
  5. # This rule does the same thing, but is less efficient
  6. (rule "Top side footprints only"
  7. (condition "A.Layer == 'B.Cu'")
  8. (constraint disallow footprint))
  9. # Larger clearance on outer layers (inner layer clearance set by board minimum clearance)
  10. (rule "clearance_outer"
  11. (layer outer)
  12. (constraint clearance (min 0.25mm)))
Condition Clause

The rule condition is an expression contained inside a text string (and therefore usually surrounded by quotes in order to allow whitespace for clarity). The expression is evaluated against each pair of objects that is being tested by the design rule checker. For example, when checking for clearance between copper objects, each copper object (track segment, pad, via, etc.) on each net is checked against other copper objects on other nets. If a custom rule exists where the expression matches the two given copper objects and the constraint defines a copper clearance, this custom rule could be used to determine the required clearance between the two objects.

The objects being tested are referred to as A and B in the expression language. The order of the two objects is not important because the design rule checker will test both possible orderings. For example, you can write a rule that assumes that A is a track and B is a via. There are some expression functions that test both objects together; these use AB as the object name.

The expression in a condition must resolve to a boolean value (true or false). If the expression resolves to true, the rule is applied to the given objects.

Each object being tested has properties that can be compared, as well as functions that can be used to perform certain tests. The syntax for using properties and functions is <object>.<property> and <object>.<function>([arguments]) respectively.

When you type <object>. in the text editor (A., B., or AB.), an autocomplete list will open that contains all the object properties that can be used.

The object properties and functions are compared using boolean operators to result in a boolean expression. The boolean operators are based on C/C++ syntax, and the following operators are supported:

==

Equal to

!=

Not equal to

>, >=

Greater than, greater than or equal to

<, <=

Less than, less than or equal to

&&

And

||

Or

For example, A.NetClass == 'HV' will apply to any objects that are part of the “HV” netclass and A.NetClass != B.NetClass will apply to any objects that are in different netclasses. Parentheses can be used to clarify the order of operations in complex expressions but they are not required.

Some properties represent a physical measurement, such as a size, angle, length, position, etc. On these properties, unit suffixes can be used in the custom rules language to specify what units are being used. If no unit suffix is used, the internal representation of the property will be used instead (nanometers for distances and degrees for most angles). The following suffixes are supported:

mm

Millimeters

mil, th

Thousandths of an inch (mils)

in,

Inches

deg

Degrees

rad

Radians

The units used in custom design rules are independent of the display units in the PCB editor.
Constraints

The constraint clause of the rule defines the behavior of the rule on the objects that are matched by the condition. Each constraint clause has a constraint type and one or more arguments that set the behavior of the constraint. A single rule may have multiple constraint clauses, in order to set multiple constraints (for example, clearance and track_width) for objects that match the same rule conditions.

Many constraints take arguments that specify a physical measurement or quantity. These constraints support minimum, optimal, and maximum value specification (abbreviated “min/opt/max”). The minimum and maximum values are used for design rule checking: if the actual value is less than the minimum or is greater than the maximum value in the constraint, a DRC error is created. The optimal value is only used for some constraints, and informs KiCad of a “best” value to use by default. For example, the optimal diff_pair_gap is used by the router when placing new differential pairs. No errors will be created if the differential pair is later modified such that the gap between the pair is different from the optimal value, as long as the gap is between the minimum and maximum values (if these are specified). In all cases where a min/opt/max value is accepted, any or all of the minimum, optimal, and maximum value can be specified.

Min/opt/max values are specified as (min <value>), (opt <value>), and (max <value>). For example, a track width constraint may be written as (constraint track_width (min 0.5mm) (opt 0.5mm) (max 1.0mm)) or simply (constraint track_width (min 0.5mm)) if only the minimum width is to be constrained.

Constraint typeArgument typeDescription

annular_width

min/opt/max

Checks the width of annular rings on vias.

clearance

min

Checks the clearance between copper objects of different nets. KiCad’s design rule system does not permit constraining clearance between objects on the same net at this time.

To allow copper objects to overlap (collide), create a clearance constraint with the min value less than zero (for example, -1).

courtyard_clearance

min

Checks the clearance between footprint courtyards and generates an error if any two courtyards are closer than the min distance. If a footprint does not have a courtyard shape, no errors will be generated from this constraint.

diff_pair_gap

min/opt/max

Checks the gap between coupled tracks in a differential pair. Coupled tracks are segments that are parallel to each other. Differential pair gap is not tested on uncoupled portions of a differential pair (for example, the fanout from a component).

diff_pair_uncoupled

max

Checks the distance that a differential pair track is routed uncoupled from the other polarity track in the pair (for example, where the pair fans out from a component, or becomes uncoupled to pass around another object such as a via).

disallow

track
via
micro_via
buried_via
pad
zone
text
graphic
hole
footprint

Specify one or more object types to disallow, separated by spaces. For example, (constraint disallow track) or (constraint disallow track via pad). If an object of this type matches the rule condition, a DRC error will be created. This constraint is essentially the same as a keepout rule area, but can be used to create more specific keepout restrictions.

edge_clearance

min/opt/max

Checks the clearance between objects and graphical items on the Edge.Cuts layer (the board outline, as well as any board cutouts or slots defined on that layer).

length

min/max

Checks the total routed length for the nets that match the rule condition and generates an error for each net that is below the min value (if specified) or above the max value (if specified) of the constraint.

hole

min/max

Checks the size (diameter) of a drilled hole in a pad or via. For oval holes, the smaller (minor) diameter will be tested against the min value (if specified) and the larger (major) diameter will be tested agains the max value (if specified).

hole_clearance

min

Checks the clearance between a drilled hole in a pad or via and copper objects on a different net. The clearance is measured from the diameter of the hole, not its center.

hole_to_hole

min

Checks the clearance between mechanically-drilled holes in pads and vias. The clearance is measured between the diameters of the holes, not between their centers. HDI vias (microvias, blind vias, and buried vias) are not tested by this constraint.

silk_clearance

min/opt/max

Checks the clearance between objects on silkscreen layers and other objects.

skew

max

Checks the total skew for the nets that match the rule condition, that is, the difference between the length of each net and the average of all the lengths of each net that is matched by the rule. If the absolute value of the difference between that average and the length of any one net is above the constraint max value, an error will be generated.

track_width

min/opt/max

Checks the width of track and arc segments. An error will be generated for each segment that has a width below the min value (if specified) or above the max value (if specified).

via_count

max

Counts the number of vias on every net matched by the rule condition. If that number exceeds the constraint max value on any matched net, an error will be generated for that net.

Object property and function reference

The following properties can be tested in custom rule expressions:

Common Properties

These properties apply to all PCB objects.

PropertyData typeDescription

Layer

string

The board layer on which the object exists. For objects that exist on more than one layer, this property will return the first layer (for example, F.Cu for most through-hole pads/vias).

Locked

boolean

True if the object is locked.

Parent

string

Returns the unique identifier of the parent object of this object.

Position_X

dimension

The position of the object’s origin in the X-axis. Note that the origin of an object is not always the same as the center of the object’s bounding box. For example, the origin of a footprint is the location of the (0, 0) coordinate of that footprint in the footprint editor, but the footprint may have been designed such that this location is not in the center of the courtyard shape.

Position_Y

dimension

The position of the object’s origin in the Y-axis. Note that KiCad always uses Y-coordinates that increase from the top to bottom of the screen internally, even if you have configured your settings to show the Y-coordinates increasing from bottom to top.

Type

string

One of “Footprint”, “Pad”, “Graphic Shape”, “Board Text”, “Footprint Text”, “Zone”, “Track”, “Via”, “Zone”, or “Group”.

Connected Object Properties

These properties apply to copper objects that can have a net assigned (pads, vias, zones, tracks).

PropertyData typeDescription

Net

integer

The net code of the copper object.

Note that net codes should not be relied upon to remain constant: if you need to refer to a specific net in a rule, use NetName instead. Net can be used to compare the nets of two objects with better performance, for example A.Net == B.Net is faster than A.NetName == B.NetName.

NetClass

string

The name of the netclass for the copper object.

NetName

string

The name of the net for the copper object.

Footprint Properties
PropertyData typeDescription

Clearance_Override

dimension

The copper clearance override set for the footprint.

Orientation

double

The orientation (rotation) of the footprint in degrees.

Reference

string

The reference designator of the footprint.

Solderpaste_Margin_Override

dimension

The solder paste margin override set for the footprint.

Solderpaste_Margin_Ratio_Override

dimension

The solder paste margin ratio override set for the footprint.

Thermal_Relief_Gap

dimension

The thermal relief gap set for the footprint.

Thermal_Relief_Width

dimension

The thermal relief connection width set for the footprint.

Value

string

The contents of the “Value” field of the footprint.

Pad Properties
PropertyData typeDescription

Clearance_Override

dimension

The copper clearance override set for the pad.

Fabrication_Property

string

One of “None”, “BGA pad”, “Fiducial, global to board”, “Fiducial, local to footprint”, “Test point pad”, “Heatsink pad”, “Castellated pad”.

Hole_Size_X

dimension

The size of the pad’s drilled hole/slot in the X axis.

Hole_Size_Y

dimension

The size of the pad’s drilled hole/slot in the Y axis.

Orientation

double

The orientation (rotation) of the pad in degrees.

Pad_Number

string

The “number” of a pad, which can be a string (for example “A1” in a BGA).

Pad_To_Die_Length

dimension

The value of the “pad to die length” property of a pad, which is additional length added to the pad’s net when calculating net length.

Pad_Type

string

One of “Through-hole”, “SMD”, “Edge connector”, or “NPTH, mechanical”.

Pin_Name

string

The name of the pad (usually the name of the corresponding pin in the schematic).

Pin_Type

string

The electrical type of the pad (usually taken from the corresponding pin in the schematic). One of “Input”, “Output”, “Bidirectional”, “Tri-state”, “Passive”, “Free”, “Unspecified”, “Power input”, “Power output”, “Open collector”, “Open emitter”, or “Unconnected”.

Round_Radius_Ratio

double

For rounded rectangle pads, the ratio of radius to rectangle size.

Shape

string

One of “Circle”, “Rectangle”, “Oval”, “Trapezoid”, “Rounded rectangle”, “Chamfered rectangle”, or “Custom”.

Size_X

dimension

The size of the pad in the X-axis.

Size_Y

dimension

The size of the pad in the Y-axis.

Soldermask_Margin_Override

dimension

The solder mask margin override set for the pad.

Solderpaste_Margin_Override

dimension

The solder paste margin override set for the pad.

Solderpaste_Margin_Ratio_Override

dimension

The solder paste margin ratio override set for the pad.

Thermal_Relief_Gap

dimension

The thermal relief gap set for the pad.

Thermal_Relief_Width

dimension

The thermal relief connection width set for the pad.

Track and Arc Properties
PropertyData typeDescription

Origin_X

dimension

The x-coordinate of the start point.

Origin_Y

dimension

The y-coordinate of the start point.

End_X

dimension

The x-coordinate of the end point.

End_Y

dimension

The y-coordinate of the end point.

Width

dimension

The width of the track or arc.

Via Properties
PropertyData typeDescription

Diameter

dimension

The diameter of the via’s pad.

Drill

dimension

The diameter of the via’s finished hole.

Layer_Bottom

string

The last layer in the via stackup.

Layer_Top

string

The first layer in the via stackup.

Via_Type

string

One of “Through”, “Blind/buried”, or “Micro”.

Zone and Rule Area Properties

These properties apply to copper and non-copper zones, and rule areas (formerly called keepouts).

PropertyData typeDescription

Clearance_Override

dimension

The copper clearance override set for the zone.

Min_Width

dimension

The minimum allowed width of filled areas in the zone.

Name

string

The user-specified name (blank by default).

Pad_Connections

string

One of “Inherited”, “None”, “Thermal reliefs”, “Solid”, or “Reliefs for PTH”.

Priority

int

The priority level of the zone.

Thermal_Relief_Gap

dimension

The thermal relief gap set for the zone.

Thermal_Relief_Width

dimension

The thermal relief connection width set for the zone.

Graphic Shape Properties

These properties apply to graphic lines, arcs, circles, rectangles, and polygons.

PropertyData typeDescription

End_X

dimension

The x-coordinate of the end point.

End_Y

dimension

The y-coordinate of the end point.

Thickness

dimension

Thickness of the strokes of the shape.

Text Properties

These properties apply to text objects (footprint fields, free text labels, etc).

PropertyData typeDescription

Bold

boolean

true if the text is bold.

Height

dimension

Height of a character in the font.

Horizontal_Justification

string

Horizontal text justification (alignment): one of “Left”, “Center”, or “Right”.

Italic

boolean

true if the text is italic.

Mirrored

boolean

true if the text is mirrored.

Text

string

The contents of the text object.

Thickness

dimension

Thickness of the stroke of the font.

Width

dimension

Width of a character in the font.

Vertical_Justification

string

Vertical text alignment: one of “Top”, “Center”, or “Bottom”.

Visible

boolean

true if the text object is visible (displayed).

Expression functions

The following functions can be called on objects in custom rule expressions:

FunctionObjectsDescription

existsOnLayer(‘layerid’)

A or B

Returns true if the object exists on the given board layer. layer_id is a string containing the name of a board layer.

fromTo(‘x’, ‘y’)

A or B

Returns true if the object exists on the copper path between the given pads. x and y are the full names of pads in the design, such as ‘R1-Pad1’.

inDiffPair(‘x’)

A or B

Returns true if the object is part of a differential pair and the base name of the pair matches the given argument x. For example, inDiffPair(‘USB‘) returns true for objects in the nets USB_P and USB_N. The can be used as a wildcard, so inDiffPair(‘USB‘) matches USB1_P and USB1_N. Note this will always return false if the given net is not a diff pair, meaning that there isn’t a matching net of the opposite polarity. So, on a board with a net named USB_P but no net named USB_N, this function returns false.

insideArea(‘x’)

A or B

Returns true if the object is fully inside the named rule area or zone. Rule area and zone names can be set in their respective properties dialogs. Note that if a track segment crosses from the inside of a rule area to the outside, this function will return false as the track is not fully inside the area. If the given area is a filled copper zone, the function tests if the given object is inside any of the filled copper regions of the zone, not if the object is inside the zone’s outline.

insideCourtyard(‘x’)

insideFrontCourtyard(‘x’)

insideBackCourtyard(‘x’)

A or B

Returns true if the object is fully inside the courtyard of the given footprint reference. The first variant checks both the front or back courtyard and returns true if the object is inside either one; the second and third variants check a specific courtyard. The wildcard can be used in the reference: insideCourtyard(‘R‘) would check all footprints with references that start with R.

isBlindBuriedVia()

A or B

Returns true if the object is a blind/buried via.

isCoupledDiffPair()

AB

Returns true if the two objects being tested are part of the same differential pair but are opposite polarities. For example, returns true if A is in net USB+ and B is in net USB-.

isMicroVia()

A or B

Returns true if the object is a microvia.

isPlated()

A or B

Returns true if the object is a plated hole (in a pad or via).

memberOf(‘x’)

A or B

Returns true if the object is a member of the named group x.

Custom design rule examples

  1. (rule RF_width
  2. (layer outer)
  3. (condition "A.NetClass == 'RF'")
  4. (constraint track_width (min 0.35mm) (max 0.35mm)))
  5. (rule "BGA neckdown"
  6. (constraint track_width (min 0.2mm) (opt 0.25mm))
  7. (constraint clearance (min 0.05mm) (opt 0.08mm))
  8. (condition "A.insideCourtyard('U3')"))
  9. (rule "Distance between Vias of Different Nets"
  10. (constraint hole_to_hole (min 0.25mm))
  11. (condition "A.Type =='Via' && B.Type =='Via' && A.Net != B.Net"))
  12. (rule "Distance between test points"
  13. (constraint courtyard_clearance (min 1.5mm))
  14. (condition "A.Reference =='TP*' && B.Reference == 'TP*"))
  15. # This assumes that there is a cutout with 1mm thick lines
  16. (rule "Clearance to cutout"
  17. (constraint clearance (min 0.8mm))
  18. (condition "A.Layer=='Edge.Cuts' && A.Thickness == 1.0mm"))
  19. (rule "Max Drill Hole Size Mechanical"
  20. (constraint hole (max 6.3mm))
  21. (condition "A.Pad_Type == 'NPTH, mechanical'"))
  22. (rule "Max Drill Hole Size PTH"
  23. (constraint hole (max 6.35mm))
  24. (condition "A.Pad_Type == 'Through-hole'"))
  25. # Specify an optimal gap for a particular differential pair
  26. (rule "Clock gap"
  27. (condition "A.inDiffPair('CLK') && AB.isCoupledDiffPair()")
  28. (constraint diff_pair_gap (opt 0.8mm)))
  29. # Specify a larger clearance between differential pairs and anything else
  30. (rule "Differential pair clearance"
  31. (condition "A.inDiffPair('*') && !AB.isCoupledDiffPair()")
  32. (constraint clearance (min 1.5mm)))

Scripting

Scripting allows you to automate tasks within KiCad using the Python language. It is possible to add functionality to KiCad through Python “action plugins” that can be added to the top toolbar. It is also possible to write standalone scripts that interact with KiCad files, for example, to generate fabrication outputs from a board file automatically.

This manual covers general scripting concepts. Users wishing to write or modify scripts should also use the Doxygen documentation located at https://docs.kicad.org/doxygen-python/namespaces.html.

KiCad 6 or newer requires Python 3 for scripting support. Python 2 is no longer supported.

Python script locations

Plugin scripts for the PCB editor can be installed automatically using the Plugin and Content Manager (PCM), or manually by copying the plugin to a folder. Each plugin should be in its own folder within the plugins folder. The location of the plugins folder is by default:

PlatformPath

Linx

~/.local/share/kicad/6.0/scripting/plugins

macOS

~/Documents/KiCad/6.0/scripting/plugins

Windows

%HOME%\Documents\KiCad\6.0\scripting\plugins

Action plugins

TODO: Write this section (how to install new action plugins)

Footprint wizards

The footprint wizards are a collection of python scripts that can be accessed from the Footprint Editor. If you invoke the footprint dialog you select a given wizard that allows you to see the footprint rendered, and you have some parameters you can edit.

If the plugins are not properly distributed to your system package, you can find the latest versions in the KiCad source tree at gitlab.

Using the scripting console

Pcbnew comes with a built-in Python console that can be used to inspect and interact with the board. To launch the console, use the py script icon in the top toolbar. The Pcbnew Python API is not automatically loaded, so to load it, type import pcbnew into the console. The command pcbnew.GetBoard() will then return a reference to the board currently loaded in Pcbnew, which can be inspected and modified through the console.

TODO: Document the other useful PyAlaMode functions

Writing external scripts

TODO: Write this section

Writing action plugins

TODO: Write this section