Skip to main content

Build. Learn.
Innovate.

Measuring Motor Speed

Written By:

Published on:

Project Overview

This project helps students measure the speed of a DC motor using a basic optical encoder or a Hall effect sensor with a magnet. Students will collect data on motor revolutions and calculate the speed in RPM using the ESP32 and MicroPython. This lays the foundation for closed-loop control and robotic feedback systems.

Educational Goals

  • Understand the concept of RPM and how to calculate it from sensor pulses
  • Learn to use interrupts to count revolutions
  • Practice time measurement and calculation in MicroPython
  • Relate motor speed to PWM duty cycle and observe the effect

Detailed Parts List

  • 1x ESP32 Dev Board (36-pin)
  • 1x DC Motor (preferably with encoder or magnet + Hall sensor)
  • 1x IR or Hall Effect Sensor Module
  • 1x L298N Motor Driver Module
  • 1x Magnet (if using Hall sensor)
  • Jumper wires
  • Breadboard or robot chassis
  • Power source for motors

Circuit Diagram Description

  • Motor control pins:
    • IN1 → GPIO 26
    • IN2 → GPIO 25
    • ENA (PWM) → GPIO 14
  • Sensor signal pin:
    • Hall/IR Sensor OUT → GPIO 34 (input only)
  • Shared GND between ESP32, motor driver, and sensor

ESP32 GPIO26 —> IN1 (L298N)
ESP32 GPIO25 —> IN2 (L298N)
ESP32 GPIO14 —> ENA (PWM)
Sensor OUT —> GPIO34 (Input)
5V/3.3V —> Sensor VCC
GND —> Shared Ground

Software Functionality

  • Count pulses from the sensor using interrupts
  • Calculate RPM based on pulse count and time interval
  • Control motor speed using PWM
  • Serve an HTML dashboard displaying real-time RPM updates via Chart.js

Web Interface Features (Integrated)

  • Live graph of RPM values using Chart.js
  • JavaScript-based dynamic data update via polling
  • Responsive and dark-themed dashboard design

Implementation Steps

  1. Wire the motor driver and sensor to ESP32
  2. Flash ESP32 with MicroPython firmware
  3. Upload “** and the embedded HTML dashboard**
  4. Test motor at different PWM values
  5. Access dashboard via IP address on local network

Extensions and Challenges

  • Measure speed of two motors and compare
  • Plot speed vs PWM to see linearity
  • Implement PID control to maintain target speed
  • Use encoder instead of Hall sensor for more precise RPM

Troubleshooting Guide

  • RPM always 0: Check sensor signal pin and orientation of magnet/encoder disk
  • Inconsistent values: Use debounce or average multiple readings
  • ESP32 crashes: Check interrupt logic and sensor power
  • Motor doesn’t respond: Recheck motor driver wiring and external power

Project Code


from machine import Pin, PWM, Timer
import socket
from time import ticks_ms, ticks_diff
import network

# Setup Wi-Fi
ssid = 'YOUR_SSID'
password = 'YOUR_PASSWORD'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
ip = wlan.ifconfig()[0]
print('Web interface at:', ip)

# Motor control
in1 = Pin(26, Pin.OUT)
in2 = Pin(25, Pin.OUT)
pwm = PWM(Pin(14), freq=1000)
pwm.duty(800)

# Sensor input
pulse_pin = Pin(34, Pin.IN)
pulse_count = 0
last_time = ticks_ms()
rpm_value = 0

# Interrupt handler
def count_pulse(pin):
global pulse_count
pulse_count += 1

pulse_pin.irq(trigger=Pin.IRQ_RISING, handler=count_pulse)

# Timer callback to calculate RPM
rpm_timer = Timer(0)

def calc_rpm(timer):
global pulse_count, last_time, rpm_value
now = ticks_ms()
dt = ticks_diff(now, last_time) / 1000
rpm_value = (pulse_count / dt) * 60
pulse_count = 0
last_time = now

rpm_timer.init(period=1000, mode=Timer.PERIODIC, callback=calc_rpm)

# Start motor
in1.on()
in2.off()

# HTML + Chart.js page
html = """<!DOCTYPE html>
<html>
<head>
<title>Motor RPM Dashboard</title>
<script src='https://cdn.jsdelivr.net/npm/chart.js'></script>
<style>
body { font-family: Arial; background: #111; color: white; text-align: center; }
canvas { background: #222; border-radius: 10px; margin-top: 30px; }
</style>
</head>
<body>
<h1>Real-Time Motor RPM</h1>
<canvas id='rpmChart' width='400' height='200'></canvas>
<script>
const ctx = document.getElementById('rpmChart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{ label: 'RPM', data: [], borderColor: 'lime', fill: false }]
},
options: {
animation: false,
responsive: true,
scales: { y: { min: 0, title: { display: true, text: 'RPM' } }, x: { title: { display: true, text: 'Time' } } }
}
});
async function updateChart() {
const res = await fetch('/rpm');
const data = await res.json();
const t = new Date().toLocaleTimeString();
if(chart.data.labels.length > 20) { chart.data.labels.shift(); chart.data.datasets[0].data.shift(); }
chart.data.labels.push(t);
chart.data.datasets[0].data.push(data.rpm);
chart.update();
}
setInterval(updateChart, 1000);
</script>
</body>
</html>"""

# Web server
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)

while True:
cl, addr = s.accept()
request = cl.recv(1024).decode()
if 'GET /rpm' in request:
cl.send('HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n')
cl.send('{{"rpm": {}}}'.format(round(rpm_value, 2)))
else:
cl.send('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n')
cl.send(html)
cl.close()

STEM Benefits

  • Science: Explore rotational motion and how speed translates to physical displacement.
  • Technology: Learn how to use sensors for feedback in control systems.
  • Engineering: Build and test feedback systems for performance monitoring.
  • Math: Measure revolutions per minute (RPM), use timing calculations, and apply formulas to compute speed.

Project Code

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.