Ultrasonic Sensor (HC-SR04) — Robot Ears
The HC-SR04 is the most popular distance sensor in robotics kits because it is cheap (Rs. 40–60), easy to use, and reliable for most applications. It works exactly like a bat's echolocation — it emits a short burst of ultrasonic sound (40 kHz, inaudible to humans), then measures how long the echo takes to return. Distance = speed of sound × time / 2.
- Range: 2 cm to 400 cm (practical accuracy up to about 300 cm)
- Accuracy: ±3 mm in good conditions
- Pins: VCC (5V), GND, TRIG (trigger), ECHO (receive)
- Cone angle: ~15 degrees — any object in that cone will be detected
// HC-SR04: TRIG → pin 9, ECHO → pin 10
const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
}
long measureDistance() {
// Send 10-microsecond pulse on TRIG
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// pulseIn measures how long ECHO stays HIGH (in microseconds)
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // 30ms timeout
if (duration == 0) return -1; // No echo received (out of range)
// Distance = duration × speed of sound / 2
// Speed of sound = 0.0343 cm/microsecond
long distance = duration * 0.0343 / 2;
return distance; // In centimetres
}
void loop() {
long dist = measureDistance();
if (dist == -1) {
Serial.println("Out of range");
} else {
Serial.print("Distance: ");
Serial.print(dist);
Serial.println(" cm");
}
delay(200);
}
Soft materials like foam, carpet, and fabric absorb sound waves and give false or no readings. Surfaces at steep angles reflect sound away from the sensor. In direct sunlight outdoors, results can be inconsistent. For these environments, consider IR or LIDAR instead.
IR Sensor — Seeing Darkness and Light
IR (Infrared) sensors emit infrared light and detect how much is reflected back. They come in two main forms for robotics: proximity IR modules (the kind with a potentiometer for adjusting detection range) and IR arrays (multiple sensors in a row for line following).
- Proximity IR: detects if an object is present within 2–30 cm (adjustable via potentiometer)
- Output: digital HIGH (no object/white surface) or LOW (object detected/black surface)
- Very fast response — no timing needed, just read the digital pin
// IR sensor OUT pin → Arduino pin 4
const int IR_PIN = 4;
void setup() {
pinMode(IR_PIN, INPUT);
Serial.begin(9600);
}
void loop() {
int irValue = digitalRead(IR_PIN);
// IR sensor outputs LOW when obstacle detected (counterintuitive!)
if (irValue == LOW) {
Serial.println("OBSTACLE DETECTED — stop or turn!");
} else {
Serial.println("Path clear — continue.");
}
delay(100);
}
IMU / Gyroscope (MPU-6050) — Knowing Your Orientation
The MPU-6050 is a 6-axis IMU (Inertial Measurement Unit) — it measures both linear acceleration and rotational rate, which together let you calculate the orientation of your robot in space. It communicates over I2C and is one of the most useful sensors you can add to a project.
- Accelerometer (3-axis) — measures acceleration including gravity. Tilt the sensor and gravity's component on each axis changes. That is how your phone knows if you tilted it.
- Gyroscope (3-axis) — measures the rate of rotation in degrees per second. Integrate over time to get angle.
- Address: 0x68 (pin AD0 LOW) or 0x69 (pin AD0 HIGH)
#include <Wire.h>
#include <math.h>
const int MPU = 0x68;
void setup() {
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B); Wire.write(0); // Wake up
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop() {
// Request accelerometer data (6 bytes from 0x3B)
Wire.beginTransmission(MPU);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(MPU, 6, true);
int16_t ax = (Wire.read() << 8) | Wire.read();
int16_t ay = (Wire.read() << 8) | Wire.read();
int16_t az = (Wire.read() << 8) | Wire.read();
// Convert raw to g-force (±2g range, 16384 LSB/g)
float ax_g = ax / 16384.0;
float ay_g = ay / 16384.0;
float az_g = az / 16384.0;
// Calculate pitch (fore-aft tilt) and roll (side tilt) in degrees
float pitch = atan2(ax_g, sqrt(ay_g * ay_g + az_g * az_g)) * 180.0 / PI;
float roll = atan2(ay_g, sqrt(ax_g * ax_g + az_g * az_g)) * 180.0 / PI;
Serial.print("Pitch: "); Serial.print(pitch, 1);
Serial.print("° Roll: "); Serial.print(roll, 1);
Serial.println("°");
delay(200);
}
Encoder — Knowing Exactly Where You Are
A wheel encoder counts the rotations (or fractions of rotations) of a motor shaft. Each count corresponds to a tiny fixed distance traveled. Accumulate the counts and you know exactly how far your robot has moved. With encoders on both wheels, you can calculate not just distance but heading — even without a compass or GPS.
The cheapest encoders for student projects are Hall effect encoders — a small magnet on the motor shaft triggers a sensor once per revolution (or multiple times per revolution for better resolution). Most yellow TT gear motors come with this option.
// Encoder signal → Arduino pin 2 (must be interrupt pin: 2 or 3 on Uno)
const int ENCODER_PIN = 2;
const float WHEEL_CIRCUMFERENCE = 21.5; // cm for a typical 68mm wheel
const int PULSES_PER_REV = 20; // Depends on your encoder disc
volatile long pulseCount = 0; // volatile: modified in interrupt
// This function runs automatically every time the encoder pulse rises
void countPulse() {
pulseCount++;
}
void setup() {
pinMode(ENCODER_PIN, INPUT_PULLUP);
// Attach interrupt: call countPulse() on every rising edge
attachInterrupt(digitalPinToInterrupt(ENCODER_PIN), countPulse, RISING);
Serial.begin(9600);
}
void loop() {
// Safely read pulseCount (disable interrupts briefly)
noInterrupts();
long count = pulseCount;
interrupts();
float revolutions = (float)count / PULSES_PER_REV;
float distance = revolutions * WHEEL_CIRCUMFERENCE;
Serial.print("Pulses: "); Serial.print(count);
Serial.print(" Distance: "); Serial.print(distance, 1);
Serial.println(" cm");
delay(500);
}
How to Choose the Right Sensor
| Sensor | Measures | Interface | Typical Range | Best For |
|---|---|---|---|---|
| HC-SR04 | Distance | 2 digital pins | 2–400 cm | Obstacle avoidance, parking |
| IR Module | Proximity / reflection | 1 digital pin | 0–30 cm | Line following, object detection |
| MPU-6050 | Orientation, motion | I2C | N/A (angular) | Drones, balance robots, gesture |
| Hall Encoder | Wheel rotation | Digital interrupt | N/A (count) | Odometry, speed control |
Need distance from an obstacle? → Ultrasonic (HC-SR04). Need to follow a line or detect a dark surface? → IR sensor. Need to know which way the robot is tilted or how fast it is turning? → IMU (MPU-6050). Need to know exactly how far the robot has traveled? → Wheel encoder.
Combine HC-SR04 with your line follower: when an obstacle is detected within 15 cm, stop the robot. When it clears, resume. This is a two-sensor fusion — distance tells you when to stop, IR tells you where to go. Most real AGV systems use exactly this combination of sensors.
