HC-SR04 is inexpensive and practical, use Arduino with LCD Keypad Shield, you can make a standalone rangefinder device ranging 2cm to 400cm.
Connections:
VCC--5V
GND--GND
Trig--D2
Echo--D3
Output:
Code:
/* HC-SR04 Sensor
This sketch reads a device ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to
the distance of the object from the sensor.
The circuit:
* +V connection of thj device attached to +5V
* GND connection of the device attached to ground
* SIG connection of the device attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
created 3 Nov 2008
by David A. Mellis
modified 30 Jun 2009
by Tom Igoe
Added on Mar. 31, 2013 by Befun Hung to fit pins of cheaphousetek LCD Keypad Shield
This example code is in the public domain.
*/
#include <LiquidCrystal.h> // include LiquidCrystal library
LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // modified to fit cheaphousetek LcdKeypad Shield
// this constant won't change. It's the pin number
// of the sensor's input and output:
const int triggerPin = 2;
const int echoPin = 3;
void setup() {
// initialize serial communication. We are going to watch our progress in the monitor
Serial.begin(9600);
lcd.begin(16, 2);
// lcd.clear();
lcd.print("testing...");
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The device is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(triggerPin, OUTPUT);
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(5);
digitalWrite(triggerPin, LOW);
// The echo pin is used to read the signal from the device: a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(inches);
lcd.print("in, ");
lcd.print(cm);
lcd.print("cm");
delay(1000);
}
long microsecondsToInches(long microseconds)
{
// *** THIS NEEDS TO BE CHECKED FOR THE HC-SR04 ***
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
// *** THIS NEEDS TO BE CHECKED FOR THE HC-SR04 ***
return microseconds / 29 / 2;
}
No comments:
Post a Comment