Foundation (Python)How-to guidesCouple joints: gears, rack & pinion, screws

Joint Relations

A relation couples the value of one joint to the value of another — the “mate relations” of Onshape. Turn a pinion and the gear it meshes with turns by the gear ratio; the rack under it slides by the pitch-circle arc.

Renders the 3D model in your browser. The first run downloads the Python runtime (≈30 MB).
"""Joint relations: a pinion drives a gear and a rack.

* Each wheel turns on a ``RevoluteJoint``; the rack slides on a
  ``SliderJoint`` along +X.
* ``GearRelation`` turns the gear (above the pinion) by ``ratio = 12 / 24``
  the other way (``reverse=True``). Its ``offset`` of half a tooth pitch puts
  a gap in front of the pinion's tooth, so the teeth mesh.
* ``RackPinionRelation`` slides the rack ``pitch_radius`` mm per radian:
  one pinion turn is ``2π · 12`` mm of rack travel.
* Change ``DRIVE_DEG`` and run again: only the pinion is set, the gear and
  the rack follow.
"""

import math

from cadbuildr.foundation import *

MODULE = 2.0  # tooth size (mm of pitch diameter per tooth)
PINION_TEETH = 12
GEAR_TEETH = 24
THICKNESS = 6.0
DRIVE_DEG = 20.0  # pinion angle


def pitch_radius(teeth):
    return MODULE * teeth / 2


def tooth_outline(teeth):
    """Trapezoid teeth around the pitch circle, one tooth on +X."""
    r = pitch_radius(teeth)
    tip, root = r + MODULE, r - 1.25 * MODULE
    step = 2 * math.pi / teeth
    points = []
    for i in range(teeth):
        a = i * step
        for radius, da in ((root, -0.3), (tip, -0.14), (tip, 0.14), (root, 0.3)):
            points.append(
                (radius * math.cos(a + da * step), radius * math.sin(a + da * step))
            )
    return points


class Gear(Part):
    def __init__(self, teeth, color):
        s = Sketch(self.xy())
        self.extrude(Polygon.from_points(s, tooth_outline(teeth)), THICKNESS)
        self.cut_extrude(Circle(s.origin, 4.0), THICKNESS)
        self.add_anchor(make_anchor("axis", (0, 0, 0)))
        self.paint(color)


class Rack(Part):
    """A toothed bar: pitch line on y = 0, teeth up, a gap at x = 0."""

    def __init__(self, teeth=14):
        pitch = math.pi * MODULE
        start = -teeth / 2 * pitch
        top, root, base = MODULE, -1.25 * MODULE, -8.0
        points = [(start, base)]
        for i in range(teeth):
            x = start + i * pitch
            points += [
                (x, root),
                (x + 0.2 * pitch, root),
                (x + 0.36 * pitch, top),
                (x + 0.64 * pitch, top),
                (x + 0.8 * pitch, root),
            ]
        points += [(start + teeth * pitch, root), (start + teeth * pitch, base)]
        s = Sketch(self.xy())
        self.extrude(Polygon.from_points(s, points), THICKNESS)
        self.add_anchor(make_anchor("slide", (0, 0, 0), z_axis=(1, 0, 0)))
        self.paint("light_grey")


class GearTrain(Assembly):
    def __init__(self):
        r_pinion, r_gear = pitch_radius(PINION_TEETH), pitch_radius(GEAR_TEETH)
        # Axles and the rack's slide way are anchors on the assembly itself.
        self.add_anchor(make_anchor("pinion_axle", (0, 0, 0)))
        self.add_anchor(make_anchor("gear_axle", (0, r_pinion + r_gear, 0)))
        self.add_anchor(make_anchor("rack_way", (0, -r_pinion, 0), z_axis=(1, 0, 0)))

        pinion, gear, rack = (
            Gear(PINION_TEETH, "orange"),
            Gear(GEAR_TEETH, "light_blue"),
            Rack(),
        )
        no_flip = BoolParameter(value=False)  # align the anchors' Z axes
        drive = RevoluteJoint(
            self.anchor("pinion_axle"), pinion.anchor("axis"), flip=no_flip
        )
        driven = RevoluteJoint(
            self.anchor("gear_axle"), gear.anchor("axis"), flip=no_flip
        )
        slide = SliderJoint(self.anchor("rack_way"), rack.anchor("slide"), flip=no_flip)
        for joint in (drive, driven, slide):
            self.add_joint(joint)

        self.add_relation(
            GearRelation(
                driver=drive,
                driven=driven,
                ratio=PINION_TEETH / GEAR_TEETH,
                reverse=True,
                offset=math.pi / GEAR_TEETH,  # half a tooth: mesh at angle 0
            )
        )
        self.add_relation(
            RackPinionRelation(pinion=drive, rack=slide, pitch_radius=r_pinion)
        )
        drive.set_angle(math.radians(DRIVE_DEG))


show(GearTrain())

The four relations

Every relation reads one degree of freedom of a driver joint and writes one degree of freedom of a driven joint:

RelationDriver → drivenRule
GearRelation(driver, driven, ratio)angle → angledriven = ratio · driver
RackPinionRelation(pinion, rack, pitch_radius)angle → offsetrack = pitch_radius · pinion (2π·r mm per turn)
ScrewRelation(screw, nut, pitch)angle → offsetnut = pitch · screw / 2π (one pitch per turn)
LinearRelation(driver, driven, ratio)offset → offsetdriven = ratio · driver
  • Angles (radians) come from RevoluteJoint, CylindricalJoint, ScrewJoint and PinSlotJoint; offsets (mm) from SliderJoint, CylindricalJoint and PinSlotJoint.
  • ratio, pitch_radius and pitch are positive. reverse=True turns or slides the driven joint the other way.
  • offset is the driven value when the driver is at 0 — e.g. half a tooth of phase so two gears mesh at angle 0.
  • ScrewRelation without a nut couples a CylindricalJoint’s own offset to its own angle.
from cadbuildr.foundation import GearRelation, RackPinionRelation, RevoluteJoint, SliderJoint
 
drive = RevoluteJoint(asm.anchor("pinion_axle"), pinion.anchor("axis"))
driven = RevoluteJoint(asm.anchor("gear_axle"), gear.anchor("axis"))
slide = SliderJoint(asm.anchor("rack_way"), rack.anchor("slide"))
for joint in (drive, driven, slide):
    asm.add_joint(joint)
 
asm.add_relation(GearRelation(driver=drive, driven=driven, ratio=12 / 24, reverse=True))
asm.add_relation(RackPinionRelation(pinion=drive, rack=slide, pitch_radius=12.0))
 
drive.set_angle(math.radians(20))   # the gear and the rack follow
driven.set_angle(-0.1)              # works too: the pinion is back-solved

How relations behave

  • Both joints must be placed (add_joint) before add_relation. The relation is enforced at once: the driven joint jumps to the value its driver dictates.
  • Either end can be set. set_angle / set_offset on a driven joint back-solves its driver, then recomputes everything that driver drives — relations chain into gear trains.
  • Downstream joints follow. A part jointed onto a driven gear moves with it, through sub-assemblies too, exactly as after a direct set_angle.
  • Limits apply to every joint a change moves. If the driven joint would leave its JointLimits, the call raises and nothing moves.
  • No conflicts, no cycles. A joint value follows at most one relation (chain them instead: A drives B, B drives C), and relations cannot loop back to their driver — both raise when you add the relation.
  • assembly.resolve() re-applies the assembly’s relations, e.g. after a joint value was edited by hand.

Relations, like joints, resolve when the Python runs: the serialized DAG carries the resulting component frames plus the relation nodes, so viewers and kernels need nothing special.

Not yet supported

Parallel, tangent and width mates are not available: they constrain geometry rather than joint values, which needs a constraint solver.