Site Guide

Find your way around the Engineering Club.

Know what you need? Search for a component, concept or project.

Around the site

Start

Labs

TestingExperimental

Build

Club

LearnExperimental

Go a little deeper

Entry points to larger collections. Use Search for individual records.

Learning paths & reference

Inside PiCrawlerExperimental

Inside Inventory

← Mega Components

ELEGOO MEGA · LESSON 33

Controlling Stepper Motor With Rotary Encoder

Move a stepper with a rotary encoder and return to its counted starting point.

Handle encoder edges without waiting inside an interrupt.

Parts List

  • ELEGOO Mega 2560 R3 is a 5 V ATmega2560 AVR board with many I/O pins and four hardware UARTs for control systems with several peripherals. Long ELEGOO-branded Mega PCB with USB-B and barrel connector, ATmega2560 marking, extended side headers and a large double-row digital header at the end. Read printed Mega labels; its SPI hardware placement is not the same numeric pins as an Uno.
  • A USB-A to USB-B cable carries USB power and, when its data conductors are present, a host/device data link. USB-A plug and square USB-B plug. Inspect the plug shape; micro-USB is not USB-C, and USB-B is the squarer device connector.
  • An 830-contact solderless breadboard joins inserted leads through hidden spring strips so circuits can be rebuilt without solder. Full-size rectangular board, center channel, numbered five-hole terminal groups and side power rails. Counted contact holes are not component units.
  • A 28BYJ-48 is a small geared unipolar stepper that advances its output shaft when coil phases are energized in sequence. Small round motor can with mounting tabs, offset geared shaft and a five-wire plug on typical unipolar versions. Read its voltage label; 5 V and other winding variants exist.
  • The ULN2003 driver board lets low-power logic switch unipolar stepper coils by sinking their current through a Darlington transistor array. ULN2003-marked IC on a PCB with motor socket, input pins and often phase LEDs. Verify motor socket wiring and the board power/ground labels.
  • A breadboard power module distributes regulated low-voltage rails to compatible breadboard power strips. Board spanning breadboard rails with power socket, selector jumpers and pin contacts. Check rail polarity against the breadboard printed marks.
  • A source-listed 9 V, 1 A DC adapter supplies a compatible device’s power input; it is not a 5 V logic rail. Plug-in adapter with DC barrel cable and 9 V/1 A label. Read polarity symbol and barrel dimensions.
  • Male-to-female jumper leads make removable point-to-point connections for low-current prototype signals. Pin at one end and socket at the other. Check intact insulation and snug contacts before use.
  • Male-to-male jumper leads make removable point-to-point connections for low-current prototype signals. Pins at both ends; count individual leads rather than ribbon groups. Check intact insulation and snug contacts before use.
  • The AstroAI meter measures electrical quantities through selectable probe circuits; its exact model, fuse arrangement and safety category remain unverified. AstroAI-branded handheld display with rotary selector and COM/voltage/current sockets. Read the actual model number and socket legends before choosing its manual.
  • An incremental rotary encoder reports shaft movement as two phase-offset contact signals, often with a separate push switch. Metal shaft on a compact PCB with clock/data and possible switch labels; unlike a potentiometer it normally exposes digital quadrature outputs.

Assembly

  1. Disconnect all power and plug the matching 5 V five-wire motor into the driver’s keyed socket.
  2. Set the breadboard supply rail to 5 V; verify it before connecting the driver. Use the 9 V adapter at its DC input and leave its USB socket unused.
  3. Keep motor +5 V separate from Mega 5 V; join their grounds. Connect USB, then motor power.
  4. Connect encoder CLK/DT/SW to D2/D3/D4; turn slowly, and press SW to request the counted return.
Illustration © ELEGOO. All rights reserved.
Illustration © ELEGOO. All rights reserved. Open full-size ↗

Source-reviewed wiring. Hardware not bench-tested; firmware uploads have not been performed.

Code

Download complete PlatformIO project
ZIP includes platformio.ini, src/main.cpp, and bundled libraries (Stepper).

Extract the ZIP, then open its lesson-33-project/workspaces/lesson-33 folder in VS Code. Keep the adjacent third-party folder in place.

PlatformIO configuration
platformio.ini
[env:mega]
platform = atmelavr@5.3.0
board = megaatmega2560
framework = arduino
monitor_speed = 9600
lib_deps =
  file://../../third-party/Stepper
main.cpp
#include <Arduino.h>
#include <Stepper.h>
const uint8_t CLK_PIN = 2;
const uint8_t DT_PIN = 3;
const uint8_t SWITCH_PIN = 4;
Stepper motor(32, 8, 10, 9, 11);  // Same rotor-step units as Lesson 32.
// volatile tells the compiler these values are changed by an interrupt outside loop().
volatile int8_t pendingTurns = 0;
volatile unsigned long lastEdgeMicros = 0;
int32_t commandedSteps = 0;  // A software count, not a measurement of physical shaft position.
bool switchWasDown = false;
void encoderEdge() {
  const unsigned long now = micros();
  if (now - lastEdgeMicros < 4000UL) return;  // Reject close contact-bounce edges without waiting.
  lastEdgeMicros = now;
  // On a falling CLK edge, the source's !DT rule makes HIGH request +50 steps.
  const int8_t direction = digitalRead(DT_PIN) ? 1 : -1;
  if ((direction > 0 && pendingTurns < 20) || (direction < 0 && pendingTurns > -20))
    pendingTurns += direction;  // Bounded queue: turn slowly while the blocking motor catches up.
}
void releaseMotor() {
  for (uint8_t pin = 8; pin <= 11; ++pin) digitalWrite(pin, LOW);
}
void setup() {
  pinMode(CLK_PIN, INPUT_PULLUP); pinMode(DT_PIN, INPUT_PULLUP); pinMode(SWITCH_PIN, INPUT_PULLUP);
  // Ask the board mapping for the interrupt instead of assuming a hardware interrupt number.
  attachInterrupt(digitalPinToInterrupt(CLK_PIN), encoderEdge, FALLING);
  motor.setSpeed(700);  // Internal-rotor RPM; about 10.9 nominal geared-output RPM.
}
void loop() {
  const bool switchDown = digitalRead(SWITCH_PIN) == LOW;
  if (switchDown && !switchWasDown) {
    // Return in int-sized chunks; Stepper.step accepts a 16-bit int on the Mega.
    while (commandedSteps != 0) {
      const int chunk = commandedSteps > 2048 ? 2048 : (commandedSteps < -2048 ? -2048 : int(commandedSteps));
      motor.step(-chunk); commandedSteps -= chunk;
    }
    noInterrupts(); pendingTurns = 0; interrupts();  // Discard turns arriving during the return.
  } else if (!switchDown) {
    // Copy and consume ONE queued event atomically, then let interrupts run during stepping.
    noInterrupts();
    const int8_t direction = pendingTurns > 0 ? 1 : (pendingTurns < 0 ? -1 : 0);
    pendingTurns -= direction;
    interrupts();
    if (direction != 0) {
      const int steps = direction * 50;
      motor.step(steps); commandedSteps += steps;
    }
  }
  switchWasDown = switchDown;
  releaseMotor();  // Released coils do not hold position; slip invalidates the software origin.
}

Source: SOURCE_RECONCILED. Compile: COMPILE_VERIFIED. Hardware: NOT_TESTED. Upload: NOT_PERFORMED.

Expected behavior

Each accepted falling CLK event commands ±50 full steps. Pressing SW reverses the software step count in chunks, then clears queued turns. This is not physical homing: slip, backlash, reset or turning the released shaft invalidate the origin.

Experiments & Challenges

  • Change the 50-step increment and update the matching count increment together; the motor still has no position sensor.

Troubleshooting

  • Missed turns: turn slowly; contact-bounce filtering and the bounded 20-event queue are not unlimited-speed tracking.