Measure Car Speed with Arduino Nano, IR Sensors, OLED, and Buzzer

Build an Arduino Nano car speed detector using two IR sensors, an OLED display, and a buzzer that alerts when measured speed exceeds 40 km/h.

  • 11 min read
On this pageIntroduction

Introduction

Measuring the speed of a moving object is a fun way to explore how sensors and Arduino work together. I built this Arduino Nano speed detection project using two IR sensor modules, a 128×64 OLED display, and a buzzer.

The idea behind this project is simple. I placed two IR sensors a fixed distance apart along the path of a moving object. When the object passes the first sensor and then the second, the Arduino Nano measures the time taken to travel between them. Using the sensor distance and the measured time, it calculates the speed of the object.

The calculated speed is displayed on the OLED screen in kilometers per hour (km/h). I also added a buzzer that activates whenever the detected speed goes above 40 km/h, making the project a simple speed alert system.

In this tutorial, I’ll show you how I connected the IR sensors, OLED display, and buzzer to the Arduino Nano. We’ll also go through the Arduino sketch, understand the speed calculation, and test how the system works with a moving object.

Note: I designed this project for electronics experiments and small model cars on a controlled track. The speed measurement depends on the sensor spacing and reliable detection of the moving object. It is a DIY demonstration and not a certified road-speed measurement device.

YouTube Demonstration Video

Watch the speed detector time a toy car between the two IR sensors and show its speed on the OLED:

🚗 Can 2 IR Sensors Measure a Car’s Speed? | Arduino DIY Speed Detector 🔥#arduino #shortsWatch on YouTube

What Is a Two-IR-Sensor Speed Detector?

A two-IR-sensor speed detector uses two infrared sensor modules placed a known distance apart to measure how long a moving object takes to travel between them.

Each sensor detects the object and sends a digital signal to the Arduino Nano. By recording the detection times, the Arduino calculates the object’s speed and displays it on an OLED.

This method uses the basic relationship between distance, time, and speed. Similar Arduino projects use two sensors and the elapsed time between detections to calculate speed. Arduino Project Hub+1

The system has three main functions:

  • Speed measurement: Calculate speed in kilometers per hour (km/h).
  • OLED display: Show the measured speed and sensor status.
  • Overspeed alert: Activate a buzzer when the measured speed exceeds 40 km/h.

For a tabletop demonstration, a model car can pass the sensors on a track. The same principle can measure other objects, provided the sensors reliably detect the object at both positions.

Features and Specifications

The following specifications describe the assumed hardware configuration. Individual sensor modules and OLED boards may differ.

ComponentSpecificationDetails
Arduino NanoOperating voltage5 V for the classic Nano
Arduino NanoMicrocontrollerATmega328P on the classic version
IR modulesOutputDigital HIGH/LOW
IR modulesDetection methodInfrared reflection or interruption, depending on module type
OLED displayResolution128 × 64 pixels
OLED interfaceCommunicationI2C
OLED controllerAssumed modelSSD1306
BuzzerType5 V active buzzer, compatible with the chosen driver
Sensor spacingExample10 cm (0.10 m)
Speed thresholdConfigured value40 km/h

The sensor spacing is a user-defined measurement, not a built-in sensor specification. Measure the distance between the two actual detection points and enter it into the sketch.

IR Sensor Pinout Explained

This tutorial assumes two common three-pin IR obstacle-detection modules with VCC, GND, and OUT connections. These modules usually contain an infrared emitter and receiver, and many use a comparator to generate a digital output.

PinFunctionArduino Connection
Sensor 1 VCCModule power5V
Sensor 1 GNDGroundGND
Sensor 1 OUTDigital detection signalD2
Sensor 2 VCCModule power5V
Sensor 2 GNDGroundGND
Sensor 2 OUTDigital detection signalD3

The code assumes each sensor output goes LOW when an object is detected. Some modules behave differently, so check the output with the Serial Monitor or a multimeter before testing.

OLED pinout

OLED PinArduino Nano PinFunction
VCC5V, if supported by the modulePower
GNDGNDGround
SDAA4I2C data
SCLA5I2C clock

Check the OLED module’s specifications before connecting its power. Some displays require 3.3 V, while others include a regulator and support 5 V.

Buzzer connections

The buzzer connection depends on its type and current requirement. This tutorial assumes an active buzzer operated through a suitable driver connected to D8. A low-current buzzer can sometimes be driven directly, but its current must remain within the Arduino pin’s rating.

Components Required

Gather the following hardware:

Where to buy the components

Affiliate disclosure: some links in this article are Amazon affiliate links. As an Amazon Associate I earn from qualifying purchases, at no extra cost to you.

Optional components

  • Transistor or logic-level MOSFET for driving the buzzer if its current exceeds the GPIO rating.
  • External regulated supply if the combined circuit needs more current than the USB connection can safely provide.
  • Multimeter for checking supply voltage and sensor output states.

Wiring Diagram and Connections

Complete wiring table

Component PinArduino Nano PinDescription
IR Sensor 1 OUTD2First detection signal
IR Sensor 2 OUTD3Second detection signal
Both sensor VCC pins5V, if supportedSensor power
Both sensor GND pinsGNDCommon ground
OLED SDAA4I2C data
OLED SCLA5I2C clock
OLED VCCSuitable supply for the moduleOLED power
OLED GNDGNDCommon ground
Buzzer driver inputD8Overspeed alert control
Buzzer/driver groundGNDGround reference

Wiring instructions

  1. Connect the first sensor’s output to D2 and the second sensor’s output to D3.
  2. Connect the sensor power and ground pins according to their specifications.
  3. Connect the OLED’s SDA and SCL pins to A4 and A5, respectively, on the classic Nano.
  4. Connect the buzzer to D8 through a suitable driver if required.
  5. Ensure all circuit grounds are connected together.
  6. Position the two IR sensors along the track, facing the object at the same height, with a measured distance between their detection points.

Important: The classic Nano’s D2 and D3 pins support external interrupts. The sketch uses interrupts to record sensor events, which helps capture short detection intervals more reliably than continuously polling the sensors in the main loop. Arduino Official Store+1

The sensors must be positioned so that the moving object reliably triggers both. Depending on the module, you may need to adjust its detection distance or orientation. Reflective IR modules are sensitive to the object’s surface, color, and ambient light, so test the arrangement with the actual model car.

How the Arduino Car Speed Detector Works

The project measures the time taken for an object to travel between two known points.

  1. First detection: The object passes the first IR sensor, and the Arduino records the detection time.
  2. Second detection: The object passes the second sensor, and the Arduino records the next detection time.
  3. Elapsed time: The Arduino calculates the time difference between the two events.
  4. Speed calculation: The measured distance is divided by the elapsed time to calculate speed.
  5. OLED display: The calculated speed is displayed in km/h.

Speed calculation formula

To calculate the speed of a moving vehicle, we need to know the distance between the two IR sensors and the time taken by the vehicle to travel between them.

Speed Formula:

Speed (m/s) = Distance (m) ÷ Time (s)

To convert the speed into kilometers per hour (km/h):

Speed (km/h) = [Distance (m) ÷ Time (s)] × 3.6

Example Calculation

Suppose the distance between the two IR sensors is 0.10 meters (10 cm), and the vehicle takes 0.020 seconds to travel between them.

Distance = 0.10 m

Time = 0.020 s

Speed = (0.10 ÷ 0.020) × 3.6

Speed = 5 × 3.6

Speed = 18 km/h

The calculated speed of the vehicle is 18 km/h.

Note: The accuracy of the measurement depends on the sensor spacing, detection response, and Arduino timing accuracy.

Arduino Library Installation

The sketch uses two libraries for the OLED display:

  • Adafruit SSD1306: Controls compatible SSD1306 OLED displays.
  • Adafruit GFX Library: Provides text and graphics drawing functions.

Install both using the Arduino IDE Library Manager. Search for Adafruit SSD1306 and Adafruit GFX Library, then install them. The SSD1306 library depends on Adafruit GFX. GitHub+1

The sensor inputs, timing calculations, interrupts, and buzzer control use standard Arduino functions and do not require additional libraries.

Arduino Code

The following sketch assumes:

  • A classic Arduino Nano.
  • Two digital IR sensor modules with active-LOW outputs.
  • An SSD1306 128 × 64 I2C OLED at address 0x3C.
  • Sensor spacing of 10 cm.
  • An active buzzer controlled by D8 through a compatible circuit.

The sketch uses interrupts on D2 and D3 to timestamp the sensor detections. It includes a timeout for incomplete readings and displays the most recent measured speed.

Code
1#include <Wire.h>2#include <Adafruit_GFX.h>3#include <Adafruit_SSD1306.h>4 5// OLED configuration6#define SCREEN_WIDTH 1287#define SCREEN_HEIGHT 648#define OLED_RESET -19#define OLED_ADDRESS 0x3C10 11Adafruit_SSD1306 display(12  SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET13);14 15// Pin definitions16const byte SENSOR1_PIN = 2;  // External interrupt INT017const byte SENSOR2_PIN = 3;  // External interrupt INT118const byte BUZZER_PIN  = 8;19 20// Adjust to match your sensor spacing21const float SENSOR_DISTANCE_M = 0.10;22 23// Overspeed threshold24const float SPEED_LIMIT_KMH = 40.0;25 26// Sensor output is assumed active LOW27const byte SENSOR_ACTIVE_LEVEL = LOW;28 29// Timeout for an incomplete sensor pair30const unsigned long PAIR_TIMEOUT_US = 2000000UL;31 32// Data shared with interrupt routines33volatile bool sensor1Triggered = false;34volatile bool sensor2Triggered = false;35 36volatile unsigned long sensor1TimeUs = 0;37volatile unsigned long sensor2TimeUs = 0;38 39float measuredSpeedKmh = 0.0;40bool speedAvailable = false;41bool overspeed = false;42 43unsigned long lastTriggerUs = 0;44 45void sensor1ISR() {46  if (!sensor1Triggered) {47    sensor1TimeUs = micros();48    sensor1Triggered = true;49  }50}51 52void sensor2ISR() {53  if (!sensor2Triggered) {54    sensor2TimeUs = micros();55    sensor2Triggered = true;56  }57}58 59void showDisplay(const char* status) {60  display.clearDisplay();61  display.setTextColor(SSD1306_WHITE);62 63  display.setTextSize(1);64  display.setCursor(0, 0);65  display.println(F("CAR SPEED DETECTOR"));66 67  display.drawLine(0, 12, 127, 12, SSD1306_WHITE);68 69  display.setCursor(0, 19);70  display.print(F("Speed: "));71 72  display.setTextSize(2);73  display.setCursor(0, 30);74 75  if (speedAvailable) {76    display.print(measuredSpeedKmh, 1);77    display.print(F(" km/h"));78  } else {79    display.print(F("--.- km/h"));80  }81 82  display.setTextSize(1);83  display.setCursor(0, 54);84  display.print(status);85 86  display.display();87}88 89void setup() {90  Serial.begin(9600);91 92  pinMode(SENSOR1_PIN, INPUT);93  pinMode(SENSOR2_PIN, INPUT);94  pinMode(BUZZER_PIN, OUTPUT);95 96  digitalWrite(BUZZER_PIN, LOW);97 98  if (!display.begin(99        SSD1306_SWITCHCAPVCC, OLED_ADDRESS)) {100    Serial.println(F("OLED initialization failed."));101    while (true) {}102  }103 104  display.clearDisplay();105  display.display();106 107  attachInterrupt(108    digitalPinToInterrupt(SENSOR1_PIN),109    sensor1ISR, FALLING110  );111 112  attachInterrupt(113    digitalPinToInterrupt(SENSOR2_PIN),114    sensor2ISR, FALLING115  );116 117  showDisplay("Waiting for car...");118  Serial.println(F("Arduino car speed detector ready."));119}120 121void loop() {122  unsigned long nowUs = micros();123 124  bool firstSeen;125  bool secondSeen;126  unsigned long t1;127  unsigned long t2;128 129  // Safely copy shared variables and clear a completed pair130  noInterrupts();131 132  firstSeen = sensor1Triggered;133  secondSeen = sensor2Triggered;134  t1 = sensor1TimeUs;135  t2 = sensor2TimeUs;136 137  if (firstSeen && secondSeen) {138    sensor1Triggered = false;139    sensor2Triggered = false;140  }141 142  interrupts();143 144  // Start the timeout when either sensor triggers145  if (firstSeen || secondSeen) {146    if (lastTriggerUs == 0) {147      lastTriggerUs = nowUs;148    }149  }150 151  // Calculate speed when both sensors have triggered152  if (firstSeen && secondSeen) {153    // Unsigned subtraction handles micros() rollover154    unsigned long deltaUs =155      (t2 >= t1) ? (t2 - t1) : (t1 - t2);156 157    lastTriggerUs = 0;158 159    if (deltaUs > 0) {160      float timeSeconds = deltaUs / 1000000.0;161 162      float speedMs =163        SENSOR_DISTANCE_M / timeSeconds;164 165      measuredSpeedKmh = speedMs * 3.6;166      speedAvailable = true;167 168      overspeed = measuredSpeedKmh > SPEED_LIMIT_KMH;169 170      digitalWrite(171        BUZZER_PIN, overspeed ? HIGH : LOW172      );173 174      const char* status =175        overspeed ? "OVERSPEED! BUZZER ON" : "Speed normal";176 177      showDisplay(status);178 179      Serial.print(F("Elapsed time: "));180      Serial.print(deltaUs);181      Serial.print(F(" us | Speed: "));182      Serial.print(measuredSpeedKmh, 2);183      Serial.print(F(" km/h | "));184      Serial.println(overspeed ? F("OVERSPEED") : F("NORMAL"));185    }186  }187 188  // Clear an incomplete measurement if the second189  // sensor is not triggered before the timeout.190  if (lastTriggerUs != 0 &&191      (unsigned long)(nowUs - lastTriggerUs) >192        PAIR_TIMEOUT_US) {193 194    noInterrupts();195    sensor1Triggered = false;196    sensor2Triggered = false;197    interrupts();198 199    lastTriggerUs = 0;200 201    digitalWrite(BUZZER_PIN, LOW);202    overspeed = false;203 204    showDisplay("Waiting for car...");205    Serial.println(F("Measurement timed out."));206  }207}

Understanding the Arduino Code

1. Pin definitions and sensor spacing

The code connects the two sensors to D2 and D3, the buzzer to D8, and the OLED through I2C. SENSOR_DISTANCE_M defines the distance between the sensor detection points in meters.

If the sensors are 15 cm apart, change the value to 0.15.

2. Interrupt-based timing

The sensor1ISR() and sensor2ISR() functions record timestamps when the sensor outputs transition from HIGH to LOW. Using interrupts helps the Arduino capture short detection intervals even while the main program updates the OLED.

The micros() function measures elapsed time in microseconds, which is useful when measuring fast-moving model cars.

3. Calculating speed

Once both sensors have triggered, the program calculates the time difference, divides the sensor spacing by the elapsed time, and converts the result to km/h.

The calculated speed is compared with SPEED_LIMIT_KMH. If it is greater than 40, the buzzer activates.

4. OLED and Serial Monitor

The showDisplay() function refreshes the OLED with the latest speed and status. The Serial Monitor displays the elapsed time, calculated speed, and whether the speed limit was exceeded.

5. Handling incomplete measurements

If only one sensor detects an object, the sketch waits for the second detection. If no matching detection arrives within two seconds, it clears the incomplete measurement and returns to waiting for the next object.

Testing the Interface

  1. Connect the Arduino Nano to your computer using a data-capable USB cable.
  2. In the Arduino IDE, select the appropriate Nano board and serial port.
  3. Install the Adafruit SSD1306 and Adafruit GFX libraries.
  4. Upload the complete sketch.
  5. Open the Serial Monitor and select 9600 baud.
  6. Confirm that the OLED displays the waiting message.
  7. Move a model car past both sensors and observe the calculated speed.
  8. Verify that the buzzer activates when the calculated speed exceeds 40 km/h.

For the initial test, use a measured sensor spacing of 10 cm and move the model car at a controlled speed. Make sure the object triggers each sensor exactly once per pass.

Example Serial Monitor output

The following values are illustrative, not guaranteed measurements.

Code
1Arduino car speed detector ready.2Elapsed time: 20000 us | Speed: 18.00 km/h | NORMAL3Elapsed time: 8000 us | Speed: 45.00 km/h | OVERSPEED

At 10 cm spacing, a travel time of 20 milliseconds corresponds to 18 km/h. A travel time of 8 milliseconds corresponds to 45 km/h, which exceeds the configured threshold.

Understanding the Output

The OLED displays the calculated speed in km/h and a status message.

  • Speed normal: The calculated speed is 40 km/h or lower, so the buzzer remains off.
  • Overspeed: The calculated speed exceeds 40 km/h, so the buzzer turns on.
  • Waiting for car: The Arduino is waiting for a valid pair of sensor detections.
  • Measurement timed out: One sensor detected an object, but the second sensor did not trigger within the allowed interval.

The speed is calculated from the distance and timing values; it is not measured directly by either IR sensor. Accuracy depends on the measured sensor spacing, the reliability of each detection, and the object’s path.

This prototype is intended for controlled experiments. It should not be used for enforcement, vehicle safety decisions, or official road-speed measurements.

Common Problems and Troubleshooting

1. OLED display remains blank

Possible causes: Incorrect I2C wiring, a different I2C address, or an incompatible display controller.

Solutions:

  • Check SDA on A4 and SCL on A5.
  • Confirm the OLED’s supply voltage.
  • Try address 0x3D if the module uses that address instead of 0x3C.
  • Verify that the display uses an SSD1306-compatible controller.

2. The speed always shows zero or no result

Possible causes: One or both sensors are not detecting the object, or their outputs are not triggering the expected interrupts.

Solutions:

  • Check the sensor output states.
  • Confirm that the sensors connect to D2 and D3.
  • Verify that the modules use active-LOW outputs.
  • Adjust sensor alignment and detection distance.

3. The calculated speed is incorrect

Possible causes: Incorrect sensor spacing, unreliable detection points, or multiple triggers.

Solutions:

  • Measure the distance between the actual detection points.
  • Update SENSOR_DISTANCE_M.
  • Ensure the object triggers each sensor once per pass.
  • Secure the sensors so they cannot move during testing.

4. The buzzer never turns on

Possible causes: The calculated speed never exceeds 40 km/h, or the buzzer wiring is incorrect.

Solutions:

  • Check the displayed speed and Serial Monitor output.
  • Verify that the buzzer is connected to D8 through a suitable circuit.
  • Test the buzzer independently.
  • Confirm that the buzzer is compatible with HIGH/LOW control.

5. The Arduino resets during operation

Possible causes: An inadequate supply, loose wiring, or a buzzer drawing too much current.

Solutions:

  • Check the supply voltage and ground connections.
  • Use a suitable driver for the buzzer.
  • Ensure that the USB supply can power the complete circuit.

6. The sketch does not compile

Possible causes: Missing OLED libraries or an incorrect board selection.

Solutions:

  • Install the Adafruit SSD1306 and Adafruit GFX libraries.
  • Select the appropriate Arduino Nano board.
  • Check the error message for missing headers or typing mistakes.

Practical Applications

This project can be used for:

  1. Measuring the speed of model cars on a track.
  2. Demonstrating distance and time calculations.
  3. Learning interrupt-based timing with Arduino.
  4. Building a classroom speed-measurement experiment.
  5. Displaying speed measurements on a compact OLED.
  6. Creating a threshold-triggered audible alert.
  7. Exploring optical object detection and embedded-system timing.

These applications are suitable for educational demonstrations and controlled experiments, not certified vehicle-speed measurement.

Frequently Asked Questions

1. Can I use an Arduino Uno instead of a Nano?

Yes. The classic Uno and Nano use compatible ATmega328P-based hardware and support the same interrupt pins used in this sketch. Connect the sensors to D2 and D3, and the other components as shown in the wiring table.

2. Why are two IR sensors required?

One sensor provides a detection event, but two sensors at a known distance allow the Arduino to measure travel time and calculate speed.

3. Can I change the speed limit from 40 km/h?

Yes. Change SPEED_LIMIT_KMH to the desired threshold. The code will activate the buzzer when the calculated speed is greater than that value.

4. How do I change the distance between the sensors?

Update SENSOR_DISTANCE_M to the measured spacing in meters. For example, 20 cm should be entered as 0.20.

5. Can I use a 0.96-inch OLED display?

Yes, provided it is compatible with the assumed SSD1306 controller and I2C interface. Check the module’s pinout and I2C address before connecting it.

6. Can this project measure the speed of a real car?

The principle can be used in specialized optical measurement systems, but this basic prototype is not suitable for reliable road-speed measurement. Real vehicles require carefully designed sensors, precise alignment, validated timing, and appropriate safety and environmental testing.

7. Why does the speed reading fluctuate?

The object may trigger the sensors inconsistently because of its surface, alignment, or speed. Check the sensor spacing and positioning, and ensure that each sensor produces one reliable detection per pass.

Conclusion

In this Arduino car speed detector tutorial, you learned how to use two IR sensors, an Arduino Nano, an OLED display, and a buzzer to calculate and display the speed of a moving object.

The Arduino records the detection times on D2 and D3, calculates speed from the known sensor spacing, displays the result on the OLED, and activates the buzzer when the calculated speed exceeds 40 km/h.

By experimenting with sensor spacing and controlled model-car movement, you can learn how interrupts, timing, and basic physics work together in an embedded system.

  1. Arduino IR Obstacle Detection Sensor Tutorial
  2. Arduino OLED Display Using the SSD1306 Library
  3. Arduino Ultrasonic Distance Measurement with OLED
  4. Arduino Speed Measurement Using Two IR Sensors
  5. Arduino Buzzer Alarm Using a Digital Sensor