Arduino Project
Speed Detection 2.0
Course Introduction
This Arduino project detects speed using two IR sensors and a servo. When an object passes the first sensor, a timer starts; it stops at the second sensor.
Using the known distance, the system calculates speed and maps it to a servo angle.
Note
If this is your first time working with an Arduino project, we recommend downloading and reviewing the basic materials first.
1.1 Install Arduino IDE(Important)
1.2 Introduction of Arduino IDE
Wiring

Common Connections:
Digital Servo Motor
Connect to breadboard’s positive power bus.
Connect to breadboard’s negative power bus.
Connect to 9 on the Arduino.
IR Obstacle Avoidance Sensor Module Front
OUT: Connect to 2 on the Arduino.
GND: Connect to breadboard’s negative power bus.
VCC: Connect to breadboard’s red power bus.
IR Obstacle Avoidance Sensor Module Back
OUT: Connect to 3 on the Arduino.
GND: Connect to breadboard’s negative power bus.
VCC: Connect to breadboard’s red power bus
Writing the Code
Note
You can copy this code into Arduino IDE.
Don’t forget to select the board(Arduino UNO R4 WIFI) and the correct port before clicking the Upload button.
#include
#define IR1_PIN 2
#define IR2_PIN 3
#define SERVO_PIN 9
Servo myServo;
unsigned long t1 = 0;
unsigned long t2 = 0;
bool waitingForIR2 = false;
float distance_cm = 10.0; // Distance between IR1 and IR2 in cm
float speed = 0; // Speed in cm/s
void setup() {
Serial.begin(9600);
pinMode(IR1_PIN, INPUT);
pinMode(IR2_PIN, INPUT);
myServo.attach(SERVO_PIN);
// Initialize servo to -90° (corresponds to 180° in servo signal)
myServo.write(180);
delay(500);
}
void loop() {
// Detect vehicle passing IR1
if (digitalRead(IR1_PIN) == LOW && !waitingForIR2) {
t1 = millis();
waitingForIR2 = true;
Serial.println("IR1 triggered");
delay(50); // Debounce delay
}
// Detect vehicle passing IR2
if (waitingForIR2 && digitalRead(IR2_PIN) == LOW) {
t2 = millis();
waitingForIR2 = false;
Serial.println("IR2 triggered");
// Calculate speed in cm/s
float timeTaken = (t2 - t1) / 1000.0;
if (timeTaken > 0) {
speed = distance_cm / timeTaken;
Serial.print("Speed: ");
Serial.print(speed);
Serial.println(" cm/s");
// Map speed to servo angle (-90 to +90), max speed = 60 cm/s
int angle = map(constrain(speed, 0, 60), 0, 60, -90, 90);
angle = constrain(angle, -90, 90);
// Convert -90~90 to servo range 0~180 (-90° → 180, +90° → 0)
int servoPos = 90 - angle;
myServo.write(servoPos);
delay(1000); // Display time
// Return to -90° (servo signal 180°)
myServo.write(180);
delay(500);
}
}
}
