Skip to main content

Build. Learn.
Innovate.

Measuring Motor Speed

Written By:

Published on:

Project Overview

This project uses a comparator-based speed sensor module to measure the rotation speed of a motor. Students will learn about using optical sensors and interpreting pulsed signals.

Educational Goals

  • Understand how optical sensors can be used for sensing motion.
  • Learn how to interpret pulsed signals from a sensor.
  • Calculate motor speed based on sensor readings and time.

Detailed Parts List

  • ESP32 – 1
  • Comparator Speed Sensor Module LM393 Chip – 1
  • DC Motor 1.5-3V or TT Motor – 1
  • Wheel or disk with encoder pattern (can be a simple paper disk with alternating black and white sections)
  • Breadboard – 1
  • Jumper Wires – Male-to-Male
  • External Power Supply for Motor

Circuit Diagram Description

Mount the speed sensor so that the wheel or disk with the encoder pattern passes through the sensor’s slot. Connect the VCC and GND pins of the speed sensor module to the 5V and GND pins on the ESP32. Connect the digital output pin (DO) of the speed sensor module to a digital GPIO pin on the ESP32. Connect the DC motor to an external power supply.

Software Functionality

The MicroPython code will use an interrupt on the chosen GPIO pin to detect the rising or falling edge of the pulse from the speed sensor as the encoder pattern passes through the slot. By counting the number of pulses over a specific time interval and knowing the number of segments on the encoder disk, the code can calculate the motor’s rotational speed (e.g., in rotations per minute – RPM). The speed will be printed to the console.

Web Interface Features

A web interface could display the motor’s current speed numerically.

Implementation Steps

  • Prepare a wheel or disk with a clear encoder pattern.
  • Mount the speed sensor and motor so the encoder passes through the sensor.
  • Connect the speed sensor circuit as described.
  • Write the MicroPython code to count pulses using interrupts and calculate speed.
  • Apply power to the motor and run the code on the ESP32.
  • Observe the calculated motor speed in the console.

Extensions and Challenges

  • Use the measured speed in a feedback loop to control the motor’s speed (requires a motor driver like the L298N and possibly PID control).
  • Measure the speed of both motors on the obstacle avoidance robot.
  • Display the speed on an OLED screen.

Troubleshooting Guide

  • Incorrect speed readings: Ensure the encoder pattern is clear and the sensor is correctly aligned. Verify the number of segments on the encoder disk is accurately reflected in the code’s calculation. Check the interrupt handling in the MicroPython code.
  • No speed readings: Confirm the speed sensor is powered correctly. Ensure the output pin is connected to the correct GPIO pin and configured for interrupts.

Project Code

# This script measures motor speed using a speed sensor and displays RPM on an OLED screen.

from machine import Pin, Timer, I2C # Import necessary classes
import time

# Import SSD1306 library.
try:
    import ssd1306
except ImportError:
    print("ssd1306.py library not found. Please upload it.")
    class MockSSD1306:
        def __init__(self, width, height, i2c): print(f"MockSSD1306 initialized ({width}x{height}).")
        def fill(self, color): pass
        def text(self, text, x, y, color): pass
        def show(self): print(f"OLED display content not shown (ssd1306 library missing): {text}")
    ssd1306 = type('ssd1306', (object,), {'SSD1306_I2C': MockSSD1306})()


# --- Speed Sensor Setup ---
speed_sensor_pin = 35
encoder_segments = 20 # Number of segments on your encoder disk
speed_sensor = Pin(speed_sensor_pin, Pin.IN)
pulse_count = 0
timer = Timer(0)

# Callback function for the interrupt.
def pulse_callback(pin):
    global pulse_count
    pulse_count += 1

speed_sensor.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=pulse_callback)

# Variable to store the start time for speed calculation.
start_time = time.ticks_ms()
calculation_interval_ms = 1000 # Calculate speed every 1 second

# --- OLED Setup ---
i2c_sda = 21
i2c_scl = 22
oled_width = 128
oled_height = 32

i2c = I2C(0, sda=Pin(i2c_sda), scl=Pin(i2c_scl), freq=400000)
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

# Clear the OLED display on startup
oled.fill(0)
oled.text("Speed Monitor", 0, 0, 1)
oled.show()
time.sleep(1)

print("Starting motor speed measurement script with OLED display...")

# Start an infinite loop for the main program.
while True:
    # Get the current time.
    current_time = time.ticks_ms()

    # Check if the calculation interval has passed.
    if time.ticks_diff(current_time, start_time) >= calculation_interval_ms:
        # Calculate the number of pulses in the interval.
        pulses_in_interval = pulse_count

        # Reset the pulse count and the start time for the next interval.
        pulse_count = 0
        start_time = current_time

        # Calculate rotations in the interval.
        # Assuming triggering on both rising and falling edges, divide pulses by (segments * 2).
        # If your sensor only triggers on one edge per segment, remove the / 2.
        rotations_in_interval = pulses_in_interval / (encoder_segments * 2)

        # Calculate RPM.
        interval_seconds = calculation_interval_ms / 1000
        rpm = (rotations_in_interval / interval_seconds) * 60

        # Print to console.
        print("Motor Speed: {:.2f} RPM".format(rpm))

        # --- Display on OLED ---
        oled.fill(0) # Clear display for fresh data
        oled.text("Motor Speed:", 0, 0, 1)
        oled.text("{:.1f} RPM".format(rpm), 0, 16, 1) # Display RPM on the next line
        oled.show()

    # Small delay in the main loop.
    time.sleep(0.01)

# This loop will run forever.

# Troubleshooting notes:
# - See troubleshooting notes from Project 8 and Project 2 (OLED).
# - Ensure ssd1306.py is on the ESP32.
# - Verify interrupt is working correctly and pulse_count is incrementing.
# - Adjust encoder_segments and the calculation formula if your sensor/encoder setup is different.

STEM Benefits

Science:

  • Rotary Motion: Understanding how motors spin.
  • Optics and Light (from Speed Sensor): How the sensor uses infrared light and detection to sense movement.

Technology:

  • Sensors: Using an optical sensor to detect rotation.
  • Interrupts: Learning how to use interrupts to respond to events (like the sensor detecting a segment).
  • Counting and Timing: Using the microcontroller to count events over time.

Engineering:

  • Measurement Systems: Designing a system to measure a physical property (rotational speed).
  • Sensor Placement and Alignment: Ensuring the sensor can accurately read the encoder.

Mathematics:

  • Counting: Counting the number of pulses.
  • Time Measurement: Measuring the time interval.
  • Calculations: Calculating speed based on the number of pulses, encoder segments, and time. This may involve concepts like frequency and converting between units (e.g., counts per second to RPM).

 

Projects
ShowCase

Real-World Projects
with Code & Hardware

Insights, Ideas
& How-Tos

Help, Support, and
Common Questions

What types of projects can I find on your website?

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.