Advertisement
arduino proximity sensor circuit

Arduino Ultrasonic Proximity Sensor

This is an Arduino-based Proximity Sensor circuit wired using the popular HC-SR04 Ultrasonic ranging module,used here for non-contact object detection purpose. The HC-SR04 module includes ultrasonic transmitters, receiver and control circuit. You only need to supply a short pulse to the trigger input to start the ranging, and then the module will send out burst of ultrasound at 40 kHz and raise its echo.

The set-up process is very simple, and best understood by referring the wiring diagram. If everything goes right,you should see the burning eye of the red LED when there is no object in the safe-zone (within 5 cm from the HC-SR04 module), and an ear-splitting beep from the piezo-buzzer otherwise.

Arduino Ultrasonic Sensor Wiring Diagram

arduino proximity sensor circuit

Arduino Sketch

/*
Project: Ultrasonic Proximity Sensor
Sensor: HC-SR04
Courtesy Note: Inspired by the Arduino Ping Sketch
Tested At: TechNode Protolabz / June 2014
*/
//Pins for HC-SR04
const int trigPin = 13;
//Pin which delivers time to receive echo using pulseIn()
int echoPin = 12;
int safeZone = 5;
// Pins for Indicators
int statusLed = 11;
int pzBzr = 10;
void setup() {
}
void loop()
{
	//raw duration in milliseconds, cm is the
	//converted amount into a distance
	long duration, cm;
	//initializing the pin states
	pinMode(trigPin, OUTPUT);
	pinMode(statusLed, OUTPUT);
	pinMode(pzBzr, OUTPUT);
	//sending the signal, starting with LOW for a clean signal
	digitalWrite(trigPin, LOW);
	delayMicroseconds(2);
	digitalWrite(trigPin, HIGH);
	delayMicroseconds(10);
	digitalWrite(trigPin, LOW);
	//setting up the input pin, and receiving the duration in uS
	pinMode(echoPin, INPUT);
	duration = pulseIn(echoPin, HIGH);
	// convert the time into a distance
	cm = microsecondsToCentimeters(duration);
	//Checking if anything is within the safezone
	// If not, keep status LED on
	// Incase of a safezone violation, activate the piezo-buzzer
	if (cm > safeZone)
	{
		digitalWrite(statusLed, HIGH);
		digitalWrite(pzBzr, LOW);
	}
	else
	{
		digitalWrite(pzBzr, HIGH);
		digitalWrite(statusLed, LOW);
	}
	delay(100);
}
long microsecondsToCentimeters(long microseconds)
{
	// The speed of sound is 340 m/s or 29 microseconds per centimeter
	// The ping travels forth and back
	// So to calculate the distance of the object we take half of the travel
	return microseconds / 29 / 2;
}

5 Comments

Join the conversation!

Error! Please fill all fields.
Looking for the latest from TI?