Skip to main content

Arduino Proximity Sensors

Introduction

Proximity sensors are essential components in many Arduino projects, allowing your creations to detect nearby objects, measure distances, and interact with the environment. These sensors enable behaviors like obstacle avoidance in robots, automatic door systems, and interactive art installations.

In this guide, we'll explore various proximity sensors compatible with Arduino, how they work, and how to implement them in your projects. By the end, you'll be able to select the right proximity sensor for your needs and integrate it into your Arduino sketches.

Types of Proximity Sensors

Arduino projects commonly use several types of proximity sensors:

  1. Ultrasonic sensors - Use sound waves to measure distance
  2. Infrared (IR) proximity sensors - Detect objects using infrared light
  3. Time-of-Flight (ToF) sensors - Measure distance using light pulses
  4. Capacitive proximity sensors - Detect objects without physical contact

Let's explore each type in detail.

Ultrasonic Sensors

Ultrasonic sensors like the HC-SR04 are among the most popular proximity sensors for Arduino. They work by sending out ultrasonic pulses and measuring the time it takes for the echo to return.

How Ultrasonic Sensors Work

  1. The Arduino sends a pulse to the sensor's trigger pin
  2. The sensor emits an ultrasonic sound wave
  3. The sound wave bounces off objects and returns to the sensor
  4. The sensor detects the echo and sends a signal to the Arduino
  5. The Arduino calculates the distance based on the time between sending and receiving

HC-SR04 Ultrasonic Sensor Example

Wiring Diagram

  • Connect VCC to Arduino 5V
  • Connect GND to Arduino GND
  • Connect Trig to Arduino digital pin 9
  • Connect Echo to Arduino digital pin 10

Code Example

cpp
const int trigPin = 9;
const int echoPin = 10;

// Variables for duration and distance
long duration;
int distance;

void setup() {
// Initialize Serial communication
Serial.begin(9600);

// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}

void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Set trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the echoPin, return sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculate distance
// Speed of sound is approximately 343 meters per second or 0.0343 cm/microsecond
// The sound wave travels to the object and back, so we divide by 2
distance = duration * 0.0343 / 2;

// Print distance to Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

delay(500);
}

Expected Output

Distance: 15 cm
Distance: 16 cm
Distance: 14 cm
Distance: 50 cm
Distance: 120 cm

Limitations

  • Ultrasonic sensors may not detect soft, fabric-covered, or angled objects well
  • They typically have a range of 2cm to 400cm
  • They're less accurate in extreme temperatures or humid conditions

Infrared (IR) Proximity Sensors

IR proximity sensors use infrared light to detect objects. They're generally less expensive than ultrasonic sensors but have a shorter range.

Sharp GP2Y0A21YK Example

This popular IR distance sensor can measure distances between 10cm and 80cm.

Wiring Diagram

  • Connect VCC to Arduino 5V
  • Connect GND to Arduino GND
  • Connect OUT to Arduino analog pin A0

Code Example

cpp
const int irSensorPin = A0;
int distance;

void setup() {
Serial.begin(9600);
}

void loop() {
// Read the analog value from the sensor
int sensorValue = analogRead(irSensorPin);

// Convert the analog reading to distance in cm
// This formula is specific to the GP2Y0A21YK sensor
// For other sensors, consult the datasheet
distance = 4800 / (sensorValue - 20);

// Print the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

delay(500);
}

Digital IR Proximity Sensor

Some IR sensors simply detect if an object is within a certain range rather than measuring the exact distance.

Wiring Diagram

  • Connect VCC to Arduino 5V
  • Connect GND to Arduino GND
  • Connect OUT to Arduino digital pin 7

Code Example

cpp
const int irSensorPin = 7;

void setup() {
Serial.begin(9600);
pinMode(irSensorPin, INPUT);
}

void loop() {
// Read the digital value
int objectDetected = digitalRead(irSensorPin);

if (objectDetected == LOW) {
Serial.println("Object detected!");
} else {
Serial.println("No object detected");
}

delay(500);
}

Time-of-Flight (ToF) Sensors

ToF sensors like the VL53L0X use light pulses to measure distance with high precision. They're more accurate than IR sensors and work well in varying lighting conditions.

VL53L0X Example

Required Libraries

For this example, you'll need to install the Adafruit_VL53L0X library through the Arduino Library Manager.

Wiring Diagram

  • Connect VIN to Arduino 5V
  • Connect GND to Arduino GND
  • Connect SCL to Arduino SCL (A5 on Uno)
  • Connect SDA to Arduino SDA (A4 on Uno)

Code Example

cpp
#include <Wire.h>
#include <Adafruit_VL53L0X.h>

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

void setup() {
Serial.begin(9600);

// Wait until serial port opens
while (!Serial) {
delay(1);
}

Serial.println("VL53L0X Time-of-Flight Sensor Test");

// Initialize the sensor
if (!lox.begin()) {
Serial.println("Failed to initialize VL53L0X");
while (1);
}
}

void loop() {
VL53L0X_RangingMeasurementData_t measure;

// Perform a measurement
lox.rangingTest(&measure, false);

// Check if the measurement is valid
if (measure.RangeStatus != 4) {
Serial.print("Distance (mm): ");
Serial.println(measure.RangeMilliMeter);
} else {
Serial.println("Out of range");
}

delay(500);
}

Capacitive Proximity Sensors

Capacitive proximity sensors detect objects by measuring changes in capacitance. They can detect objects without direct contact and can even detect objects through thin non-metallic barriers.

Building a Simple Capacitive Sensor

You can create a basic capacitive sensor using just a high-value resistor and the Arduino's built-in capacitive sensing ability.

Required Components

  • Arduino board
  • 1MΩ resistor
  • Aluminum foil or copper tape (for the sensing pad)
  • Connecting wires

Wiring

  • Connect one end of the resistor to digital pin 2
  • Connect the other end to digital pin 4
  • Connect pin 4 to your sensing pad (foil or copper)

Code Example

cpp
#include <CapacitiveSensor.h>

// Create a capacitive sensor using pins 2 and 4
CapacitiveSensor capSensor = CapacitiveSensor(2, 4);

// Threshold for detecting proximity
long threshold = 200;

void setup() {
Serial.begin(9600);
}

void loop() {
// Get sensor reading
long sensorValue = capSensor.capacitiveSensor(30);

// Print the sensor value
Serial.print("Sensor value: ");
Serial.println(sensorValue);

// Check if the value is above the threshold
if (sensorValue > threshold) {
Serial.println("Proximity detected!");
}

delay(200);
}

Real-World Applications

Automatic Hand Sanitizer Dispenser

This project uses an IR proximity sensor to detect a hand and activate a pump.

cpp
#include <Servo.h>

const int irSensorPin = 7;
const int servoPin = 9;

Servo dispenserServo;
bool dispensing = false;

void setup() {
Serial.begin(9600);
pinMode(irSensorPin, INPUT);
dispenserServo.attach(servoPin);
dispenserServo.write(0); // Initial position
}

void loop() {
// Read the sensor
int objectDetected = digitalRead(irSensorPin);

if (objectDetected == LOW && !dispensing) {
// Hand detected, dispense sanitizer
dispensing = true;
dispense();
delay(1000); // Prevent immediate re-triggering
dispensing = false;
}

delay(100);
}

void dispense() {
Serial.println("Dispensing sanitizer");
dispenserServo.write(180); // Activate pump
delay(500);
dispenserServo.write(0); // Return to initial position
}

Parking Distance Sensor

This project uses an ultrasonic sensor to help with parking by indicating how close you are to a wall or obstacle.

cpp
#include <NewTone.h>

const int trigPin = 9;
const int echoPin = 10;
const int buzzerPin = 8;
const int ledGreenPin = 5;
const int ledYellowPin = 6;
const int ledRedPin = 7;

void setup() {
Serial.begin(9600);

pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledGreenPin, OUTPUT);
pinMode(ledYellowPin, OUTPUT);
pinMode(ledRedPin, OUTPUT);
}

void loop() {
// Measure distance
int distance = measureDistance();

// Update indicators based on distance
updateIndicators(distance);

delay(100);
}

int measureDistance() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Set trigPin HIGH for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Read the echoPin
long duration = pulseIn(echoPin, HIGH);

// Calculate distance
int distance = duration * 0.0343 / 2;

Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");

return distance;
}

void updateIndicators(int distance) {
// Turn off all LEDs initially
digitalWrite(ledGreenPin, LOW);
digitalWrite(ledYellowPin, LOW);
digitalWrite(ledRedPin, LOW);

// Update indicators based on distance
if (distance > 100) {
// Safe distance, green light
digitalWrite(ledGreenPin, HIGH);
// No sound
}
else if (distance > 50) {
// Getting closer, yellow light
digitalWrite(ledYellowPin, HIGH);
// Slow beeping
NewTone(buzzerPin, 1000, 50);
delay(500);
}
else {
// Too close, red light
digitalWrite(ledRedPin, HIGH);
// Rapid beeping
NewTone(buzzerPin, 2000, 100);
delay(200);
}
}

Troubleshooting Common Issues

Noisy Readings

Proximity sensors, especially ultrasonic ones, can produce noisy readings. To smooth out the values, you can take multiple readings and average them:

cpp
int getAverageDistance(int numReadings) {
int total = 0;

for (int i = 0; i < numReadings; i++) {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

long duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.0343 / 2;

total += distance;
delay(10);
}

return total / numReadings;
}

Interference Between Multiple Sensors

If you're using multiple ultrasonic sensors, they can interfere with each other. To prevent this, trigger them sequentially with delays between readings.

Summary

Proximity sensors expand your Arduino projects by enabling them to detect and respond to the physical world. In this guide, we covered:

  • Ultrasonic sensors - Great for accurate distance measurement over a wide range
  • IR proximity sensors - Useful for shorter-range detection with lower cost
  • Time-of-Flight sensors - Provide high precision measurement regardless of lighting conditions
  • Capacitive sensors - Detect objects without direct contact

Each sensor type has its strengths and limitations, making them suitable for different applications.

Exercises

  1. Build a simple robot that can navigate around obstacles using an ultrasonic sensor.
  2. Create a "virtual theremin" musical instrument that changes tone based on hand proximity using an IR sensor.
  3. Develop a smart trash can that opens its lid when someone approaches using a ToF sensor.
  4. Design an interactive art installation that responds when people come near it using a capacitive proximity sensor.

Additional Resources

  • Explore more Arduino sensor tutorials in our Arduino Sensors section
  • Try combining proximity sensors with other inputs like buttons or light sensors
  • Experiment with setting different thresholds for different behaviors

Happy tinkering!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)