Gear motor with encoder
A gearbox motor with a two-channel Hall encoder, the JGA25-370, N20 or TT kind. Aliases: encoder motor, quadrature encoder motor.
The motor and gearbox are the plain DC motor, the same model. On the back is a magnet disc and two Hall sensors a quarter of a pulse apart, which is what lets a sketch count how far the wheel has turned, how fast, and which way.
Pins
| Pin | What it does |
|---|---|
M1, M2 |
The motor. To a driver: a board pin cannot run it. |
VCC |
The encoder's supply, 3.3 V to 5 V. |
GND |
The encoder's ground. |
A, B |
The two Hall outputs (C1 and C2 on some boards), driven from VCC. |
Properties
The plain motor's voltage, rpm (at the wheel), resistance, inertia and
back_emf, and two for the encoder: ppr, pulses per turn of the motor shaft on
each channel, 11 by default; and ratio, the gearbox, 30 by default.
How to count it
The wheel makes ppr x ratio pulses a turn on each channel, 330 by default. Count
only the rising edges of A and you get 330 a turn; count every edge on both
channels and you get four times that, 1320.
Forward (current from M1 to M2, positive rpm) A leads B: when A rises, B
is still low. Backward, B leads, so B is already high when A rises. That is the
whole direction test:
void onA() { // attachInterrupt on A, RISING
if (digitalRead(B) == LOW) count++;
else count--;
}
What the model gets right
The pulses follow the shaft. Each edge happens when the modeled shaft reaches it, and the shaft chases the applied voltage with the motor's lag. So a sketch sees the motor run up, coast after a brake, and slow when a battery sags, and can close a speed or position loop on it. At the default 200 rpm that is 1100 pulses a second on each channel.
Quadrature. The channels are exactly a quarter of a pulse apart, and the order flips with the direction.
What it does not model
What the plain motor leaves out: the load on the shaft, the flyback kick and stiction. The Hall sensors' own timing and uneven magnet poles are not modeled, so the duty is exactly half and the phase exactly 90 degrees. The encoder is on the motor side of the gearbox, as on the real motors, so gearbox backlash never reaches it.
Common mistakes
Counting on a pin without an interrupt. At full speed there are over a thousand
pulses a second, and a loop() with a delay() in it misses most of them. Use
attachInterrupt on A.
Reading a multi-byte count in loop() while the interrupt changes it. Copy it with
interrupts off, as the dosing pump sketch does.
Forgetting the encoder's VCC and GND. The motor turns without them, and the
count stays at zero.
See it in action
Dosing pump counts the encoder to pump exactly 5 ml. Open it at /templates.