drivers.encoder module

class drivers.encoder.Encoder(tim, chA_pin, chB_pin)[source]

Bases: object

Quadrature encoder interface wrapper.

  • Uses a hardware Timer configured in ENC_AB mode with two channels (channel 1 -> A, channel 2 -> B).

  • Tracks total accumulated encoder position accounting for timer reloads (overflow / underflow).

  • Provides update() to sample the hardware counter and compute:
    • position: total encoder counts (signed, extended across reloads)

    • delta: change in position since last update (counts)

    • dt: elapsed time since last update (milliseconds, float)

  • Convenience methods:
    • get_position() -> wheel linear position (mm)

    • get_velocity() -> linear velocity (mm/s)

    • zero() -> reset the encoder zero (tare)

get_position()[source]

Convert the most recently-updated encoder position (counts) into a linear wheel displacement in millimeters.

Formula:

rotations = counts / ECOUNTS_PER_WREV distance = rotations * (2 * pi * wheel_radius)

get_velocity()[source]

Compute linear velocity (mm/s) using the most recent delta and dt.

Returns 0 if dt is zero (to avoid division by zero). The computation follows:

counts_per_ms = delta / dt
rotations_per_s = (counts_per_ms * 1000) / ECOUNTS_PER_WREV
velocity_mm_s = rotations_per_s * (2 * pi * wheel_radius)
update()[source]

Sample the hardware counter and update position/delta/dt.

  • Reads the raw 16-bit counter

  • Extends it using self.timer_reloads to build a monotonic position

  • Computes delta = position - prev_count

  • Updates prev_count and computes elapsed time dt (ms)

zero()[source]

Tare / zero the encoder.

  • Reset reload counters and prev_count

  • Reset the hardware timer counter to 0

  • Call update() so subsequent reads are consistent with the new zero