Components · 10 min read

N20 Motor Encoder Arduino: Measure RPM, Direction and PID Speed

N20 motor encoder Arduino guide: gear ratio and speed table, A/B quadrature signal, counting pulses with interrupts, RPM math, PID control; Uno, ESP32, Pico.

The N20 motor with encoder is the most popular way to both turn a wheel on a small robot and measure how far it has turned. The N20 is a micro gear DC motor whose metal gearbox measures just 12 × 10 mm. The magnetic encoder on its rear shaft produces a fixed number of pulses per revolution; by counting them, the Arduino learns the motor's speed, direction and position. That turns an ordinary DC motor into a precise actuator whose speed can be regulated and which can move to a requested angle.

In this article you'll learn the N20's dimensions and voltage options, how the gear ratio changes speed and torque, the encoder's A/B quadrature signal and the x1, x2 and x4 decoding methods. Then you'll count pulses with interrupts on an Arduino Uno to calculate RPM and direction, keep the speed steady under load with PID, drive the motor to any angle with an ESP32 and take the same measurement in MicroPython on a Raspberry Pi Pico.

N20 micro gear DC motor
The N20's metal gearbox is 12 × 10 mm; on the encoder version a magnetic disc sits on the rear shaft.

What is an N20 motor? Dimensions and voltage options

The N20 name comes from the size of the motor body: about 12 mm wide, 10 mm thick and 15 mm long. The metal gearbox in front turns the motor's fast but weak rotation into a slow, strong one, and the output is a 3 mm D-shaft. The motors are sold in 3 V, 6 V and 12 V versions. At the same gear ratio, the 12 V version reaches the same speed as the 6 V one with less current; but if you'll run the motor from 4 AA batteries or a single Li-ion cell, the 6 V version is the better fit. On the encoder version, a short shaft also comes out of the back of the motor; a small multi-pole magnet disc sits on it and a tiny board with two Hall sensors reads the disc. The connection is usually made with a 6-pin JST cable.

FeatureTypical value
Gearbox size12 × 10 mm, length 9–14 mm depending on ratio
Output shaft3 mm D-shaft, about 10 mm long
Voltage versions3 V, 6 V, 12 V
No-load currentAbout 40–120 mA
Stall current0.3–1.6 A depending on version
Torque the gearbox can handleAbout 2 kg·cm continuous
EncoderMagnetic, two Hall sensors, 3.3–5 V supply
WeightAbout 10–12 g with encoder

Gear ratio, speed and torque

With a 1:100 ratio, the output shaft makes 1 turn while the motor shaft makes 100. So output speed = motor speed / gear ratio. Torque changes the other way: output torque ≈ motor torque × gear ratio × efficiency. Every gear stage loses some energy, so efficiency drops to 50–60% at high ratios. The gearbox also has its own limit: the N20's small gears carry about 2 kg·cm continuously. At high ratios such as 1:298 or 1:1000 the motor may produce more on paper, but if you load the shaft beyond that the gears wear or break. The table below is calculated for a typical N20 whose motor shaft spins at about 15,000 rpm with no load at 6 V; your motor's figures are on the seller's page.

Gear ratioNo-load output speed (6 V)Relative torquePulses per output turn (x1 / x4)Typical use
1:10About 1500 rpm1×70 / 280Fan, light and fast mechanism
1:30About 500 rpmAbout 2.7×210 / 840Fast robot car, sumo
1:50About 300 rpmAbout 4.5×350 / 1400Line-following robot
1:100About 150 rpmAbout 8×700 / 2800General-purpose robot, PID experiments
1:150About 100 rpmAbout 12×1050 / 4200Heavy robot, climbing
1:298About 50 rpmAbout 22× (near the gear limit)2086 / 8344Door lock, curtain, turntable
1:1000About 15 rpmLimited by the gearbox7000 / 28000Slow positioning, camera slider
When choosing a ratio for a robot, start from your target speed. A wheel's circumference is π × diameter, so speed = π × diameter × rpm / 60. A 34 mm wheel at 300 rpm covers about 0.53 m per second, a good speed for a line follower. 150 rpm (1:100) is slower but stronger and easier to control with PID.

How does a magnetic encoder work? The A/B quadrature signal

The north and south poles of the encoder magnet alternate around the disc. As the disc turns, the Hall sensors on the board see the poles change and each produces a square wave. The two sensors are placed so that the A and B waves are a quarter period, or 90 degrees, out of phase; this is called quadrature. When the motor turns one way, A changes before B; the other way, B leads. This order lets a single counter give you both the pulse count and the direction: if B is LOW when A rises, count up; if it is HIGH, count down. Most N20 encoders on the market give 7 pulses per channel per motor revolution (7 PPR); some brands use 3 or 12. To be sure, turn the output shaft one full turn by hand without powering the motor and read the counter. You can see the same A/B logic on a hand-turned knob in the rotary encoder article.

Decoding methodEdges countedCounts per motor turn (7 PPR)Per output turn at 1:100Interrupts needed
x1Rising edge of A only77001 pin (B read normally)
x2Both edges of A1414001 pin
x4All edges of A and B2828002 pins

Wiring: Arduino Uno, ESP32 and Raspberry Pi Pico

The pins on the encoder cable are usually ordered M1 (motor +), GND, C1 (channel A), C2 (channel B), VCC (encoder supply) and M2 (motor -), but the order can vary by manufacturer; check the labels on the board. The motor leads M1 and M2 go straight to a motor driver. This article uses the cheap, small, dual-channel L9110S; the DRV8833 and TB6612FNG are also great for the N20. An L298N works too, but its voltage drop of about 2 V makes a 6 V motor run slowly. On the Uno only D2 and D3 support hardware interrupts, so x4 counting uses these two pins. On the ESP32 and Pico almost every GPIO supports interrupts.

ConnectionArduino UnoESP32Raspberry Pi Pico
Encoder VCC5V3V33V3(OUT)
Encoder GNDGNDGNDGND
C1 (channel A)D2 (INT0)GPIO 18GP2
C2 (channel B)D3 (INT1)GPIO 19GP3
L9110S A-IA (PWM)D5GPIO 25GP14
L9110S A-IB (PWM)D6GPIO 26GP15
L9110S VCC / GND6 V battery / common GND6 V battery / common GND6 V battery / common GND
Motor M1 / M2L9110S MOTOR-A outputsL9110S MOTOR-A outputsL9110S MOTOR-A outputs
On the 6-pin cable the motor leads sit right next to the encoder supply. If you accidentally put the 6 V or 12 V motor voltage on VCC, the Hall sensors burn out, so always check the pin order before connecting. Don't power the motor from the Arduino's 5V pin: the start-up current can reach 1 A and the board resets. Use a separate battery for the motor, join the driver's GND with the Arduino's GND and solder a 100 nF ceramic capacitor across the motor terminals; noise on the encoder lines drops noticeably.

Counting pulses with interrupts and calculating RPM

Pulse counting must be done with interrupts, because an unloaded N20's motor shaft spins 250 turns per second and x4 counting produces about 7000 edges per second; you can't catch them with digitalRead inside loop(). The onEdge() function in the code runs on every change of A and B, turns the old and new states of the two pins into a 4-bit number and adds +1, -1 or 0 from a 16-entry table to the counter. An invalid transition (both channels changing at once) gives 0, so a single noise spike doesn't shift the count. RPM uses the fixed-window method: RPM = (count difference / counts per output turn) / elapsed time × 60. For example, if 560 counts arrive in 200 ms at 1:100, the output shaft turned 0.2 revolutions, which is 60 revolutions per minute. At very low speeds only a few pulses fall into the window, so measuring the time between two pulses gives a more precise result.

  1. Wire the motor, encoder and L9110S as in the table; power the motor from a separate 6 V battery.
  2. Set PPR and GEAR in the code for your motor (for example 7 and 100).
  3. Upload the code, open the Serial Monitor at 115200 baud and set the line ending to 'Newline'.
  4. Type 150 and send it: the motor spins and the RPM is shown with 'forward'; -150 turns it the other way.
  5. If the RPM is negative while the motor turns forward, swap the C1 and C2 wires.
  6. Send 0 to stop the motor, turn the output shaft one full turn by hand and check that the count rises by about 2800.
C++ (Arduino IDE)
1// N20 enkoderli motor: x4 darbe sayma, RPM ve yön / N20 encoder motor: x4 counting, RPM and direction
2const byte ENC_A = 2;              // enkoder A (C1), INT0 / encoder A (C1), INT0
3const byte ENC_B = 3;              // enkoder B (C2), INT1 / encoder B (C2), INT1
4const byte IN_A = 5;               // L9110S A-IA (PWM)
5const byte IN_B = 6;               // L9110S A-IB (PWM)
6
7const float PPR = 7;               // motor milinde kanal başına darbe / pulses per channel per motor turn
8const float GEAR = 100;            // dişli oranı 1:100 / gear ratio 1:100
9const float COUNTS_PER_REV = PPR * 4 * GEAR;   // çıkış mili turu başına sayım (x4) / counts per output turn (x4)
10
11// eski durum (2 bit) + yeni durum (2 bit) -> adım / old state + new state -> step
12const int8_t QEM[16] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
13volatile long count = 0;
14volatile uint8_t lastState = 0;
15
16void onEdge() {
17  uint8_t s = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
18  count += QEM[(lastState << 2) | s];
19  lastState = s;
20}
21
22void setMotor(int pwm) {           // -255..255, işaret yön / sign is direction
23  pwm = constrain(pwm, -255, 255);
24  if (pwm >= 0) {
25    analogWrite(IN_A, pwm);
26    analogWrite(IN_B, 0);
27  } else {
28    analogWrite(IN_A, 0);
29    analogWrite(IN_B, -pwm);
30  }
31}
32
33void setup() {
34  Serial.begin(115200);
35  pinMode(ENC_A, INPUT_PULLUP);
36  pinMode(ENC_B, INPUT_PULLUP);
37  pinMode(IN_A, OUTPUT);
38  pinMode(IN_B, OUTPUT);
39  lastState = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
40  attachInterrupt(digitalPinToInterrupt(ENC_A), onEdge, CHANGE);
41  attachInterrupt(digitalPinToInterrupt(ENC_B), onEdge, CHANGE);
42  Serial.println("-255..255 arasi PWM yaz / type a PWM value from -255 to 255");
43}
44
45void loop() {
46  static long lastCount = 0;
47  static unsigned long lastMs = 0;
48
49  if (Serial.available()) {
50    String line = Serial.readStringUntil('\n');
51    line.trim();
52    if (line.length() > 0) setMotor(line.toInt());
53  }
54
55  unsigned long now = millis();
56  if (now - lastMs >= 200) {       // 200 ms'lik pencere / 200 ms window
57    noInterrupts();
58    long c = count;
59    interrupts();
60    float dt = (now - lastMs) / 1000.0;
61    float rpm = (c - lastCount) / COUNTS_PER_REV / dt * 60.0;
62    float angle = fmod(c / COUNTS_PER_REV * 360.0, 360.0);
63    lastCount = c;
64    lastMs = now;
65
66    Serial.print("Sayim / count: ");
67    Serial.print(c);
68    Serial.print("  Aci / angle: ");
69    Serial.print(angle, 1);
70    Serial.print("  RPM: ");
71    Serial.print(rpm, 1);
72    Serial.println(rpm > 0.5 ? "  ileri / forward" : (rpm < -0.5 ? "  geri / reverse" : "  duruyor / stopped"));
73  }
74}

The code shows both the count and the angle of the output shaft; the angle is the count divided by the counts per revolution, times 360. Since the counter is a long, it won't overflow until about 2 billion counts, or 760,000 turns at 1:100. Before reading a multi-byte variable changed in an interrupt, briefly disable interrupts with noInterrupts(); otherwise half of the value may change while it is being read. With the PWM value you send over serial you can measure the motor's no-load speed: that value is MAX_RPM in the next sketch. You'll see the motor doesn't turn at all below a PWM of about 60–80; this dead zone comes from friction and is taken into account in position control.

Holding speed steady with PID

At the same PWM value, a motor that spins at 150 rpm with no load drops to 110 rpm when you press the wheel on the floor, and it slows as the battery voltage falls. PID control solves this: it looks at the difference (error) between target and measured speed and corrects the PWM continuously. The P term reacts in proportion to the error, the I term adds up past errors to remove a steady offset, and the D term looks at how fast the error changes to brake overshoot. Speed measurements are a bit noisy, so D is usually left off in speed control and PI is enough. Two improvements in the code make the job easier: feed-forward estimates the PWM for the target speed in advance so PID only corrects the difference, and an integral limit (anti-windup) stops the integral from growing forever when the motor is overloaded and can't reach the target. The theory is covered in the what is PID control article.

C++ (Arduino IDE)
1// N20 motor için PID hız kontrolü / PID speed control for an N20 motor
2const byte ENC_A = 2, ENC_B = 3;   // enkoder / encoder
3const byte IN_A = 5, IN_B = 6;     // L9110S girişleri / L9110S inputs
4
5const float PPR = 7, GEAR = 100;
6const float COUNTS_PER_REV = PPR * 4 * GEAR;
7const float MAX_RPM = 150;         // 6 V'ta yüksüz devir (ölç ve yaz) / no-load speed at 6 V (measure it)
8const unsigned long DT_MS = 50;    // kontrol periyodu / control period
9
10float kp = 0.8, ki = 3.0, kd = 0.0;   // başlangıç kazançları / starting gains
11float targetRpm = 80;
12
13const int8_t QEM[16] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
14volatile long count = 0;
15volatile uint8_t lastState = 0;
16
17void onEdge() {
18  uint8_t s = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
19  count += QEM[(lastState << 2) | s];
20  lastState = s;
21}
22
23void setMotor(int pwm) {
24  pwm = constrain(pwm, -255, 255);
25  analogWrite(IN_A, pwm >= 0 ? pwm : 0);
26  analogWrite(IN_B, pwm < 0 ? -pwm : 0);
27}
28
29void setup() {
30  Serial.begin(115200);
31  pinMode(ENC_A, INPUT_PULLUP);
32  pinMode(ENC_B, INPUT_PULLUP);
33  pinMode(IN_A, OUTPUT);
34  pinMode(IN_B, OUTPUT);
35  lastState = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
36  attachInterrupt(digitalPinToInterrupt(ENC_A), onEdge, CHANGE);
37  attachInterrupt(digitalPinToInterrupt(ENC_B), onEdge, CHANGE);
38  Serial.println("Hedef RPM yaz (eksi = geri) / type target RPM (negative = reverse)");
39}
40
41void loop() {
42  static long lastCount = 0;
43  static unsigned long lastMs = 0;
44  static float rpm = 0, integral = 0, lastError = 0;
45  static byte printDiv = 0;
46
47  if (Serial.available()) {
48    String line = Serial.readStringUntil('\n');
49    line.trim();
50    if (line.length() > 0) {
51      targetRpm = constrain(line.toFloat(), -MAX_RPM, MAX_RPM);
52      integral = 0;                // yeni hedefte integrali sıfırla / reset integral on a new target
53    }
54  }
55
56  unsigned long now = millis();
57  if (now - lastMs < DT_MS) return;
58  float dt = (now - lastMs) / 1000.0;
59  lastMs = now;
60
61  noInterrupts();
62  long c = count;
63  interrupts();
64  float measured = (c - lastCount) / COUNTS_PER_REV / dt * 60.0;
65  lastCount = c;
66  rpm = 0.7 * rpm + 0.3 * measured;          // basit alçak geçiren süzgeç / simple low-pass filter
67
68  float error = targetRpm - rpm;
69  integral = constrain(integral + error * dt, -50, 50);   // integral sınırı (anti-windup)
70  float derivative = (error - lastError) / dt;
71  lastError = error;
72
73  float feedForward = targetRpm * 255.0 / MAX_RPM;        // ileri besleme / feed-forward
74  float out = feedForward + kp * error + ki * integral + kd * derivative;
75  if (targetRpm == 0) {
76    out = 0;
77    integral = 0;
78  }
79  setMotor((int)out);
80
81  if (++printDiv >= 4) {           // 200 ms'de bir yaz (Seri Çizici) / print every 200 ms (Serial Plotter)
82    printDiv = 0;
83    Serial.print("hedef:");
84    Serial.print(targetRpm);
85    Serial.print(" rpm:");
86    Serial.print(rpm);
87    Serial.print(" pwm:");
88    Serial.println(constrain((int)out, -255, 255));
89  }
90}
ParameterWhat happens when you raise itStarting valueTuning tip
KpFaster response, too much causes oscillation0.8With Ki and Kd at zero, raise it until it oscillates, then halve it
KiSteady error disappears, too much causes overshoot3.0Raise it until the motor settles on target in 0.5–1 s under load
KdReduces overshoot, amplifies noise0Usually not needed for speed control
DT_MSShorter means faster response but noisier measurement50 msAt least 50–100 counts should fall into one window
Filter factor0.1 instead of 0.3: smoother but slower0.3Lower it if the rpm curve jitters in the Serial Plotter

Position control with an ESP32

The encoder gives position as well as speed, so you can drive the N20 to any angle like a small servo. In the ESP32 code you type a target in degrees over serial (such as 90, 360 or -720); the code converts it to counts and drives the motor there with a PD controller. Within 4 counts (about 0.5 degrees) of the target the motor stops; this deadband keeps the motor from jittering around the target. MIN_PWM is the smallest PWM the motor needs to overcome friction, so it moves even for small errors. The ESP32 generates PWM at 20 kHz, so the motor whine disappears. To compile with both core 2.x and 3.x, the LEDC calls are separated with #if ESP_ARDUINO_VERSION_MAJOR: 3.x uses ledcAttach(pin, frequency, bits), 2.x uses ledcSetup and ledcAttachPin. The interrupt function goes into RAM with IRAM_ATTR and the table with DRAM_ATTR, so the interrupt works safely even while flash is being written. Because the encoder is powered from 3V3, its A and B outputs can go straight to the ESP32.

C++ (Arduino IDE)
1// ESP32 + N20: enkoderle konum kontrolü (PD) / ESP32 + N20: position control with the encoder (PD)
2const int ENC_A = 18, ENC_B = 19;  // enkoder, 3,3 V ile beslenir / encoder powered from 3.3 V
3const int IN_A = 25, IN_B = 26;    // L9110S ya da DRV8833 girişleri / L9110S or DRV8833 inputs
4const int PWM_FREQ = 20000;        // 20 kHz: duyulmaz / inaudible
5const int PWM_BITS = 8;            // 0..255
6
7const float COUNTS_PER_REV = 7 * 4 * 100;   // PPR x 4 x dişli oranı / PPR x 4 x gear ratio
8const int DEADBAND = 4;            // bu kadar sayım hata kabul / accepted error in counts
9const int MIN_PWM = 70;            // sürtünmeyi yenen en küçük PWM / smallest PWM that beats friction
10float kp = 0.6, kd = 0.02;
11
12DRAM_ATTR static const int8_t QEM[16] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
13volatile long count = 0;
14volatile uint8_t lastState = 0;
15portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
16long targetCount = 0;
17
18void IRAM_ATTR onEdge() {
19  uint8_t s = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
20  portENTER_CRITICAL_ISR(&mux);
21  count += QEM[(lastState << 2) | s];
22  portEXIT_CRITICAL_ISR(&mux);
23  lastState = s;
24}
25
26void pwmSetup() {
27#if ESP_ARDUINO_VERSION_MAJOR >= 3
28  ledcAttach(IN_A, PWM_FREQ, PWM_BITS);      // çekirdek 3.x / core 3.x
29  ledcAttach(IN_B, PWM_FREQ, PWM_BITS);
30#else
31  ledcSetup(0, PWM_FREQ, PWM_BITS);          // çekirdek 2.x / core 2.x
32  ledcSetup(1, PWM_FREQ, PWM_BITS);
33  ledcAttachPin(IN_A, 0);
34  ledcAttachPin(IN_B, 1);
35#endif
36}
37
38void writeDuty(int pin, int channel, int duty) {
39#if ESP_ARDUINO_VERSION_MAJOR >= 3
40  ledcWrite(pin, duty);
41#else
42  ledcWrite(channel, duty);
43#endif
44}
45
46void setMotor(int pwm) {
47  pwm = constrain(pwm, -255, 255);
48  writeDuty(IN_A, 0, pwm >= 0 ? pwm : 0);
49  writeDuty(IN_B, 1, pwm < 0 ? -pwm : 0);
50}
51
52void setup() {
53  Serial.begin(115200);
54  pinMode(ENC_A, INPUT_PULLUP);
55  pinMode(ENC_B, INPUT_PULLUP);
56  pwmSetup();
57  lastState = (digitalRead(ENC_A) << 1) | digitalRead(ENC_B);
58  attachInterrupt(digitalPinToInterrupt(ENC_A), onEdge, CHANGE);
59  attachInterrupt(digitalPinToInterrupt(ENC_B), onEdge, CHANGE);
60  Serial.println("Hedef aciyi derece olarak yaz (or. 90, -720) / type a target angle in degrees");
61}
62
63void loop() {
64  static unsigned long lastMs = 0;
65  static long lastError = 0;
66  static byte printDiv = 0;
67
68  if (Serial.available()) {
69    String line = Serial.readStringUntil('\n');
70    line.trim();
71    if (line.length() > 0) targetCount = lround(line.toFloat() / 360.0 * COUNTS_PER_REV);
72  }
73
74  unsigned long now = millis();
75  if (now - lastMs < 10) return;   // 100 Hz kontrol döngüsü / 100 Hz control loop
76  float dt = (now - lastMs) / 1000.0;
77  lastMs = now;
78
79  portENTER_CRITICAL(&mux);
80  long c = count;
81  portEXIT_CRITICAL(&mux);
82
83  long error = targetCount - c;
84  float out = kp * error + kd * (error - lastError) / dt;
85  lastError = error;
86
87  if (labs(error) <= DEADBAND) {
88    out = 0;                       // hedefte dur / stop at the target
89  } else if (out > 0) {
90    out += MIN_PWM;                // ölü bölgeyi aş / overcome the dead zone
91  } else {
92    out -= MIN_PWM;
93  }
94  setMotor((int)out);
95
96  if (++printDiv >= 20) {          // 200 ms'de bir / every 200 ms
97    printDiv = 0;
98    Serial.printf("Hedef / target: %.1f  Konum / position: %.1f derece / deg\n",
99                  targetCount * 360.0 / COUNTS_PER_REV, c * 360.0 / COUNTS_PER_REV);
100  }
101}

Raspberry Pi Pico and MicroPython

In the Pico code both edges of channel A trigger an interrupt (x2); if A and B are at the same level at that moment the motor is turning one way, and if they differ it's turning the other. So a single interrupt gives both direction and pulse. The motor is driven with 20 kHz PWM on GP14 and GP15; the set_motor() function takes a percentage from -100 to 100. In MicroPython each interrupt takes a few tens of microseconds, so above a few thousand edges per second you start to miss pulses. At 1:100 and higher ratios that's fine even at full speed; for very fast motors it's safer to count with the Pico's PIO or in C++ with the Arduino-Pico core. The encoder is powered from the 3V3(OUT) pin with the internal pull-ups enabled.

MicroPython
1# Raspberry Pi Pico + N20: RPM ve yön (MicroPython) / RPM and direction (MicroPython)
2from machine import Pin, PWM
3import time
4
5PPR = 7                      # motor milinde kanal başına darbe / pulses per channel per motor turn
6GEAR = 100                   # dişli oranı / gear ratio
7CPR = PPR * 2 * GEAR         # A'nın iki kenarı (x2) / both edges of A (x2)
8
9enc_a = Pin(2, Pin.IN, Pin.PULL_UP)    # GP2 = enkoder A / encoder A
10enc_b = Pin(3, Pin.IN, Pin.PULL_UP)    # GP3 = enkoder B / encoder B
11in_a = PWM(Pin(14))                    # GP14 -> L9110S A-IA
12in_b = PWM(Pin(15))                    # GP15 -> L9110S A-IB
13in_a.freq(20000)
14in_b.freq(20000)
15count = 0
16
17def on_a(pin):
18    global count
19    if enc_a.value() == enc_b.value():  # A ve B aynıysa bir yön / equal means one direction
20        count -= 1
21    else:
22        count += 1
23
24enc_a.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=on_a)
25
26def set_motor(percent):                 # -100..100, işaret yön / sign is direction
27    percent = max(-100, min(100, percent))
28    duty = int(abs(percent) * 65535 // 100)
29    if percent >= 0:
30        in_b.duty_u16(0)
31        in_a.duty_u16(duty)
32    else:
33        in_a.duty_u16(0)
34        in_b.duty_u16(duty)
35
36set_motor(60)                           # %60 ileri / 60 % forward
37last_count = 0
38last_ms = time.ticks_ms()
39while True:
40    time.sleep_ms(200)
41    now = time.ticks_ms()
42    c = count
43    dt = time.ticks_diff(now, last_ms) / 1000
44    rpm = (c - last_count) / CPR / dt * 60
45    last_count = c
46    last_ms = now
47    direction = "ileri / forward" if rpm > 0.5 else ("geri / reverse" if rpm < -0.5 else "duruyor / stopped")
48    print("RPM: {:.1f}  Sayim / count: {}  {}".format(rpm, c, direction))

Project ideas with an N20 encoder motor

  • Robot car that drives straight: Match the speed of both wheels with PID so the car goes dead straight without drifting; see the Arduino robot car build article for the basic chassis.
  • Odometry: Calculate the distance travelled and the turning angle from wheel revolutions and show them on a display.
  • Self-balancing robot: Measure tilt with an MPU6050 and wheel speed with the encoders and build a two-loop PID; details in the self-balancing robot article.
  • Motorized curtain or door lock: Track position from the encoder with a 1:298 ratio and store the open and closed points in EEPROM.
  • Camera slider: Shoot slow, constant-speed footage on a rail with a 1:1000 N20.
  • Mini turntable: Stop a turntable every 15 degrees for product photos and send a trigger signal.

Common mistakes and fixes

SymptomLikely causeFix
Counter never increasesEncoder VCC not connected or wrong pin orderMeasure VCC and GND, check the C1/C2 labels on the board
RPM negative while turning forwardChannels A and B swappedSwap the C1 and C2 wires or multiply the count by -1
RPM value keeps jumpingMotor noise gets onto the encoder lines100 nF across the motor terminals, keep wires twisted and short
Measured RPM is 4 times too highCounting x4 but calculating with x1COUNTS_PER_REV must be PPR × 4 × ratio
Motor won't turn at low PWMDead zone caused by frictionAdd feed-forward or a minimum PWM (MIN_PWM)
Motor oscillates under PIDKp or Ki too largeSet Ki to zero, halve Kp, then raise Ki slowly
Arduino resets when the motor startsMotor powered from the Arduino's 5VUse a separate battery and join only the grounds

The N20 encoder motor lets you learn the core ideas of robotics, gear ratio, quadrature signals, interrupts and PID, in one small part. The counter and PID code you wrote here works just the same on bigger gear motors. In the BlueGrays app you can open the Bluetooth-controlled car, obstacle-avoiding robot and PWM projects with step-by-step circuit diagrams and ready-to-use code, and take your robot to the next level by adding the N20 encoder motor to them.

Frequently asked questions

How many pulses does an N20 motor encoder give?

Most N20 magnetic encoders on the market give 7 pulses per channel per motor revolution; some brands use 3 or 12. Pulses per output-shaft turn are that number multiplied by the gear ratio, so at 1:100 you get 700 with x1 counting and 2800 with x4. To be sure, turn the output shaft one turn by hand and read the counter.

How do you calculate RPM from an encoder?

Divide the count difference over a set time by the counts per output turn; that gives the number of revolutions. Divide the result by the elapsed time in seconds and multiply by 60 to get RPM. For example, 0.2 revolutions in 200 ms is 60 revolutions per minute.

How does an encoder tell the direction of rotation?

Channels A and B are 90 degrees out of phase, and the one that changes first shows the direction. If B is LOW on the rising edge of A, the motor turns one way; if it is HIGH, it turns the other. In code this shows up as the counter going up or down.

Which motor driver should I use for an N20 motor?

The N20 draws little current, so small drivers such as the L9110S, DRV8833 or TB6612FNG are ideal, and they also work with 3.3 V logic. An L298N can be used, but it drops about 2 V, so a 6 V motor slows down. Never drive the motor directly from an Arduino pin.

Which Arduino Uno pins does an encoder connect to?

On the Uno, hardware interrupts exist only on D2 and D3, so for x4 counting A and B go to these two pins. For x1 or x2 counting it's enough to have A on D2, and B can go to any digital pin. If you need more channels, pin change interrupts can be used.

How much torque does an N20 motor have?

Torque rises almost in proportion to the gear ratio, but there are efficiency losses and a gearbox limit. The N20's gears carry about 2 kg·cm continuously, so even at high ratios you shouldn't load the shaft beyond that. The exact figure for your voltage and ratio is given on the seller's page.

See all projects
Bluetooth Controlled Car with L298N
AR-80Advanced
Premium

Bluetooth Controlled Car with L298N

Turn your phone into a remote and drive your own robot car. The Arduino receives commands from a remote-control app on your phone through a Bluetooth module and spins the wheels with a motor driver…

5.0(39)
66
Obstacle Avoidance Robot
AR-81Advanced
Premium

Obstacle Avoidance Robot

How about building a smart vehicle that finds its own way? The Obstacle Avoidance Robot constantly scans its surroundings thanks to the ultrasonic sensor in front of it.

5.0(38)
49
Using a Stepper Motor
AR-67Intermediate
Premium

Using a Stepper Motor

A motor that turns step by step, exactly as far as you want, like the hand of a clock.

4.5(31)
42
360-Degree Servo from a Stepper Motor
AR-68Intermediate
Premium

360-Degree Servo from a Stepper Motor

Teach an ordinary stepper motor to go to any angle you want, all the way around the circle.

4.5(22)
33
Using a Servo Motor
AR-35Beginner
Premium

Using a Servo Motor

The arm of a small servo motor turns to three positions in turn: all the way to the start, right to the middle and all the way to the end, waiting two seconds at each stop.

4.7(49)
69
ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)
ES-13Intermediate
Premium

ESP32 LED Brightness Control with a Potentiometer (Analog → PWM)

In this project, we control the brightness of an LED analogically using a potentiometer. The ESP32's ADC pin reads the 0-3.3V voltage from the potentiometer, and this value is then converted into a PWM (Pulse Width Modulation) signal and sent to the LED. As a result, as you turn the potentiometer, the LED gradually brightens and dims. With Arduino Core 3.0+, analogWrite() can be used directly; on the ESP32-S2/S3, the ADC resolution is fixed at 12-bit.

4.4(20)
32
ESP32 Servo Motor (Potentiometer Control)
ES-16Intermediate
Premium

ESP32 Servo Motor (Potentiometer Control)

In this project, we control an SG90 servo motor using a potentiometer. We adjust the servo angle by mapping the analog value read from the potentiometer to the 0–180-degree range. The ESP32Servo library generates servo signals on suitable output-capable GPIO pins of the ESP32; this project uses GPIO 18. This is a fundamental control method for robotic arms, camera gimbals, and automatic door mechanisms.

4.3(30)
42
Raspberry Pi Pico PWM LED Fade (Breathing Effect)
PI-14Beginner

Raspberry Pi Pico PWM LED Fade (Breathing Effect)

The LED doesn't just blink anymore, it breathes! With the Raspberry Pi Pico's PWM (Pulse Width Modulation), the LED's brightness slowly rises and then slowly fades, a calm "breathing" effect like a sleeping laptop's light. You'll learn the machine.PWM class, the 16-bit brightness value from 0–65535 with duty_u16() and the PWM frequency.

4