Arduino Playground is read-only starting December 31st, 2018. For more info please look at this Forum Post

Parallax Ping

Ultrasonic Sensor

Better library: NewPing

The example below is a simple implementation that is easy to understand and great for simple testing. However, it is slow, is not meant to be run from interrupt code, and does not bound the pulseIn call by adding ", 38000" or whatever the appropriate maximum timeout (in microseconds) is for your sensor. In other words this code can introduce up to a 1 second delay as the worst case timeout to pulseIn.

Simple example to play with

// * Copyleft 2007 Jason Ch

This code returns the distance in Inches... I think it's more accurate than other code I have seen online and returns more usable results. Remove the *.39 to return cm instead of inches. You could make float ultrasoundValue = 0; but then you can't print it unless you transfer it into another type, but it could be used for further calculations.

unsigned long echo = 0;
int ultraSoundSignal = 9; // Ultrasound signal pin
unsigned long ultrasoundValue = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(ultraSoundSignal,OUTPUT);
}

unsigned long ping()
{
  pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output
  digitalWrite(ultraSoundSignal, LOW); // Send low pulse
  delayMicroseconds(2); // Wait for 2 microseconds
  digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
  delayMicroseconds(5); // Wait for 5 microseconds
  digitalWrite(ultraSoundSignal, LOW); // Holdoff
  pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
  digitalWrite(ultraSoundSignal, HIGH); // Turn on pullup resistor
  // please note that pulseIn has a 1sec timeout, which may
  // not be desirable. Depending on your sensor specs, you
  // can likely bound the time like this -- marcmerlin
  // echo = pulseIn(ultraSoundSignal, HIGH, 38000)
  echo = pulseIn(ultraSoundSignal, HIGH); //Listen for echo
  ultrasoundValue = (echo / 58.138) * .39; //convert to CM then to inches
  return ultrasoundValue;
}

void loop()
{
  int x = 0;
  x = ping();
  Serial.println(x);
  delay(250); //delay 1/4 seconds.
}