loading

hello Instructables,
I have had some trouble with my cheap ultrasonic sensor (hc-sr04) and today I found a really easy solution.
It is a really simple edit of the normal 3pin code.

I added the 4 int's to the beginning of the code, so you can changes the arduino pins very easily.

The new code(4pin):

int vcc = 2; //attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; //attach pin 4 to Echo
int gnd = 5; //attach pin 5 to GND

void setup() {

pinMode (vcc,OUTPUT);
pinMode (gnd,OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}

void loop()
{
digitalWrite(vcc, HIGH);
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;

// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(trig, OUTPUT);
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(5);
digitalWrite(trig, LOW);

// The same pin is used to read the signal from the PING))): 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(echo,INPUT);
duration = pulseIn(echo, 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();

delay(100);
}

long microsecondsToInches(long microseconds)
{
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PI...
return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}

Step 1: 3-pin code

Code
/* Ping))) Sensor
 
   This sketch reads a PING))) 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 the PING))) attached to +5V
    * GND connection of the PING))) attached to ground
    * SIG connection of the PING))) attached to digital pin 7

   http://www.arduino.cc/en/Tutorial/Ping
  
   created 3 Nov 2008
   by David A. Mellis
   modified 30 Aug 2011
   by Tom Igoe

   This example code is in the public domain.

*/

// this constant won't change.  It's the pin number
// of the sensor's output:
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): 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(pingPin, INPUT);
  duration = pulseIn(pingPin, 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();
 
  delay(100);
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}
<p>I built the hc-sr04 version, but modified it to use float data type for the variables inches and cm. Then changed microsecondsToInches and Centimeters to return a float and to divide by 74.0 instead of 74 or 29.0 instead of 29 - this causes a floating divide instead of a integer divide.</p>
<p>I put a little different twist on it. but thank you for the insperation.</p>
<p>hello, please i have a problem. My arduino keeps tripping off any time i connect the GND of the HCSR04 with the GND of my microcontroller. the ardunio uno micro controller keeps tripping off and i have tried this on two different micro-controller. the micro controller is powered by my laptop usb port. any idea how i can fix this problem?/</p>
<p>the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc. You will need the NewPing library which is far better.</p><p>A working code:</p><p>#include &lt;NewPing.h&gt;</p><p>#define TRIGGER_PIN 12</p><p>#define ECHO_PIN 11</p><p>#define MAX_DISTANCE 200</p><p>NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);</p><p>void setup() {</p><p>Serial.begin(9600);</p><p>}</p><p>void loop() {</p><p>delay(50);</p><p>unsigned int uS = sonar.ping();</p><p>pinMode(ECHO_PIN,OUTPUT);</p><p>digitalWrite(ECHO_PIN,LOW);</p><p>pinMode(ECHO_PIN,INPUT);</p><p>Serial.print(&quot;Ping: &quot;);</p><p>Serial.print(uS / US_ROUNDTRIP_CM);</p><p>Serial.println(&quot;cm&quot;);</p><p>}</p><p>link: <a href="http://forum.arduino.cc/index.php?topic=55119.15" rel="nofollow">http://forum.arduino.cc/index.php?topic=55119.15</a></p><p>NewPing link: http://playground.arduino.cc/Code/NewPing</p>
<p>Ive noticed that if I've aimed the sensor at something a long way away I start receiving 0cm, scrolls until I restart.<br><br>Reading the comments in the code again, I'm guessing the sensor is stuck sending HIGH to the trigger pin as the HIGH duration is the length of time from send to receive... but it doesnt receive as its too far away.</p><p>If I tap the sensor or table in front of it it seems to kick it off again.<br><br>Is there any way around this? Or rather, I know I want to write an &quot;If duration is longer than 1 second, restart &quot; but no idea how or where to add it yet.<br><br>&quot;// The same pin is used to read the signal from the PING))): a HIGH<br>// pulse whose duration is the time (in microseconds) from the sending<br>// of the ping to the reception of its echo off of an object.</p><p>pinMode(pingPin, INPUT);<br>duration = pulseIn(pingPin, HIGH);&quot;</p>
<p>the solution to the sensor being stuck at zero is in this link. its the 2. post, by docdoc. You will need the NewPing library which is far better.</p><p>A working code:</p><p>#include &lt;NewPing.h&gt;</p><p>#define TRIGGER_PIN 12</p><p>#define ECHO_PIN 11</p><p>#define MAX_DISTANCE 200 </p><p>NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); </p><p>void setup() {</p><p>Serial.begin(9600); </p><p>}</p><p>void loop() {</p><p>delay(50); </p><p>unsigned int uS = sonar.ping();</p><p>pinMode(ECHO_PIN,OUTPUT);</p><p>digitalWrite(ECHO_PIN,LOW);</p><p>pinMode(ECHO_PIN,INPUT);</p><p>Serial.print(&quot;Ping: &quot;);</p><p>Serial.print(uS / US_ROUNDTRIP_CM); </p><p>Serial.println(&quot;cm&quot;);</p><p>}</p><p>link: <a href="http://forum.arduino.cc/index.php?topic=55119.15" rel="nofollow"> http://forum.arduino.cc/index.php?topic=55119.15</a></p><p>NewPing link: http://playground.arduino.cc/Code/NewPing</p>
<p>Please tell me if it works or what works, so I can add it to the troubleshooting. Good luck</p>
<p>Still not sure whats happening because (see last post) and I added an ELSE to show when it was over a certain duration, and it can come back from that. It somehow dies when its pointed a certain distance away.<br><br>if (duration &lt;= 15000)<br>{<br>// Display results<br>Serial.print(&quot;Distance is &quot;);<br>Serial.print(cm);<br>Serial.print(&quot;cm&quot;);<br>Serial.println();<br>Serial.println(duration);<br>delay(500); <br>} //end if<br>else<br>{<br>Serial.print(&quot;uh oh, I cant see that far!&quot;);<br>Serial.println();<br>delay(500);<br>}<br></p><p>----------------------------<br>Distance is 159cm<br>9272<br>Distance is 159cm<br>9271<br>uh oh, I cant see that far!<br>Distance is 160cm<br>9322<br>Distance is 160cm<br>9322<br>uh oh, I cant see that far!<br>uh oh, I cant see that far!<br>uh oh, I cant see that far!<br>uh oh, I cant see that far!<br>uh oh, I cant see that far!<br>uh oh, I cant see that far!<br>Distance is 160cm<br>9281<br>Distance is 160cm<br>9307</p><p>-----------------------------</p>
<p>Peter - was running into the same problem <br>of the sensor getting &quot;stuck&quot; - I debugged by digitialRead()-ing the <br>Echo pin value before sending the digital pulse and afterward. What I <br>found was that the Echo pin was staying HIGH all the time when you point<br> it far away and get it stuck; when it's operating normally the pin is <br>zero to start with. I updated the code above a bit: Before <br>digitalWrite(trig, LOW) I call resetPingSensorIfStuck() which looks <br>like:</p><p>// When the sensor gets aimed at &quot;nothing&quot; (too far away for a return) it can get<br>// &quot;stuck&quot;. If you flick one of the &quot;eyes&quot; on the sensor it wakes up. We can get around this<br>// by resetting the Echo pin to zero manually. Typically this should be called<br>// just before sending the pulse via Trig.<br>void resetPingSensorIfStuck()<br>{<br> int echoValue = digitalRead(echo);<br> if (echoValue != 0) {<br> pinMode(echo, OUTPUT);<br> digitalWrite(echo, LOW);<br> pinMode(echo, INPUT);<br> }<br>}</p>
<p>As far as I can tell this is normal. As the sound generated by the trigger gets further away it gets less intense, so there will be a point where the echo can not be distinct from random noise. </p>
<p>I worked out why the delay is ignored.<br>There is a default of 1 second before pulseIn gives up listening. <br><a href="http://www.arduino.cc/en/Reference/PulseIn" rel="nofollow">http://www.arduino.cc/en/Reference/PulseIn<br><br></a>Id really like to understand though how to restart the whole process once it dies.<br></p><p>Thanks for the help so far. Ill post back if I work it out! :)<br></p>
<p>I guess it would be something like this:</p><p>pinMode(echo,INPUT);<br>duration = pulseIn(echo, HIGH);</p><p>if(duration&lt;=VALUE){</p><p>Serial.print(inches);<br>Serial.print(&quot;in, &quot;);<br>Serial.print(cm);<br>Serial.print(&quot;cm&quot;);<br>Serial.println();</p><p>}</p><p>delay(100);</p><p>}<br></p><p>Where VALUE would be the duration in seconds at the max range. You can test this by replacing the part after duration=pulseIn(.....); with Serial.println(duration);</p>
<p>Thanks for the reply!</p><p>This (1) is the serial monitor output I get just before I point the sensor at the ceiling at work (can you tell im busy at work?).</p><p>The ceiling is way higher that 400cm which I believe is the max range of the HC-SR04?</p><p>I added the IF statement (3) and end up getting this (2) but still get the repeating 0cm after pointing at far away objects. The delay(500) goes out of the window too, it takes 2 or 3 seconds before it outputs the next 0cm</p><p>If I give it a flick then it does restart (4). Resetting the arduino and closing/reopening the serial monitor does nothing either. Pulling the power (USB) and re-plugging does work.</p><p>Confused!</p><blockquote>*(4)********************<br>Distance is 0cm<br>0<br>Distance is 0cm<br>0<br>Distance is 0cm<br>0<br>FLICK!!!<br>Distance is 159cm<br>9245<br>Distance is 158cm<br>9221<br>Distance is 159cm<br>9223<br>Distance is 158cm<br>9221<br>*(4)*********************</blockquote><blockquote>*(3)********************************</blockquote><blockquote>if (duration &lt;= 20000)</blockquote><blockquote>{</blockquote><blockquote>// Display results<br>Serial.print(&quot;Distance is &quot;);<br>Serial.print(cm);<br>Serial.print(&quot;cm&quot;);<br>Serial.println();<br>Serial.println(duration);<br>delay(500); //print line after every delay<br>} //end if<br>*(3)*************************</blockquote><blockquote>*(2)*************************</blockquote><blockquote>Distance is 269cm<br>15622<br>Distance is 269cm<br>15646<br>Distance is 268cm<br>15601<br>Distance is 271cm<br>15745<br>Distance is 271cm<br>15719<br>Distance is 238cm<br>13837<br>Distance is 0cm<br>0<br>Distance is 0cm<br>0<br>*(2)************************</blockquote><blockquote>*(1)******************<br>Distance is 389cm</blockquote><blockquote>22586<br>Distance is 418cm<br>24283<br>Distance is 417cm<br>24209<br>Distance is 417cm<br>24218<br>Distance is 0cm<br>0<br>Distance is 0cm<br>0<br>Distance is 0cm<br>0<br>*(1)*****************************</blockquote>
<p>I am using a HC-SR04 hooked up to a Arduino Nano. I have it mounted on my quad-copter (drone) to control the retractable landing gear. I have it set to 3 feet and it works reliably when closer than 3 feet to the ground. My problem is when it is flying, the sensor is &quot;seeing&quot; my rotor wash from the props and generating false triggers. When my quad is up high flying, the landing gear goes up and down at random. </p><p>I think I need to look at the distance, wait a second and look again. If the two answers match, then perform an action. My problem is I'm not a programmer. Can anyone give me a clue or just do it for me? </p><p>Here is my code that I stole so far. Any help will be greatly appreciated and I promise I won't spy on you with my drone. :) Thanks in advance</p><p>#include &lt;Servo.h&gt;<br><br>Servo servoLeft; <br>Servo servoRight; <br>#define echoPin 2 <br>#define trigPin 3<br><br>void setup() { <br> servoLeft.attach(5); <br> servoRight.attach(6); <br> Serial.begin (9600);<br> pinMode(trigPin, OUTPUT);<br> pinMode(echoPin, INPUT);<br>} <br><br>void loop() { <br> long duration, distance;<br> digitalWrite(trigPin, LOW); <br> delayMicroseconds(2); <br> digitalWrite(trigPin, HIGH);<br> delayMicroseconds(10); <br> digitalWrite(trigPin, LOW);<br> duration = pulseIn(echoPin, HIGH);<br> distance = (duration/2) / 74; // 74=inches 29=cm<br> if (distance &lt; 36) { // 160cm=5' 62cm=2' 60&quot;=5' 24&quot;=2'<br> servoLeft.write(80);<br> servoRight.write(90); //LANDING<br> }<br> else {<br> servoLeft.write(180);<br> servoRight.write(0); //FLYING<br> }<br> delay(2000);<br>}</p>
<p>I have a confusion with HC-SR04. I tried your code and it works very well. I got the output on the Serial Monitor just fine. The problem is, when I take out the trig pin (detach) from pin 3. I still got the reading just fine? I thought that the TRIG is for sending pulse and the ECHO is for receiving pulse. Somebody please explain what is the case here?</p>
<p>Hey, This was great help. Thanks!</p><p> <br>However, I have a question about the use of the pulseIn function here. Aduino Documentauin tells me that this function starts timing when the pin gets a high signal, and then stops timing when the pin gets a low signal. So in our context it will record the &lsquo;duration&rsquo; as the time between when it started hearing the reflected sound, and when it stopped hearing the reflected sound. But I don't think that is what we want. That duration will always be 10 microsecond, since that was the length of our pulse (assuming that any obstacle is further than 5 sound-microseconds). Don't we want something that starts timing whn the signal is first sent, and then stops timing when the signal is first received? I may be wrong. The code works perfectly, but it doesn't make theoretical sense to me. </p>
<p>Thanks for this! :)<br>I found that I was getting 0 inch and 0CM but going through a breadboard and hooking Ground to Ground (instead of pin 5) and VCC to 5V (instead of pin 2) I started to get readings! Might help other people trying this?!<br>Not sure my readings are all that accurate at the moment but im already late for work. ;) Ill take a look at the code/calculations and the actual sensor etc and see if there is a reason for it and maybe fudge the calculation to match my sensor.</p>
<p>is it the connection fault or some kind of noise error??</p>
<p>why do i get zero reading from ultrasonic sensors???</p>
<p>thanks a lot</p>
hey wondering why my robot runs into walls still. i changed distance from 40cm to 20 cm any thoughts?
<p>Ok I made it and implemented the code however It won't display anything, Is there something with my sensor?</p>
<p>i used this code and the sensor will give me correct data for a bit but then it will stop for a seconds then only output 0in and 0cm once per second any idea what could be causing this? thank you </p>
<p>is it possible that you did not define your pin modes for your echo and trig pins?</p><p>Your trig pin mode should be output and your echo pin mode should be input</p>
<p>hey guys it works fine but the problem is when i upload the program on to the board it shows zero cm although the intensity of the 0cm changes as i get a obstacle in front of the hc-sr04 but it still shows 0cm .any help would be really appreciated thank you in advance</p>
<p>If you have a cheap arduino the ground pins may not be connected, so try an other ground pin. </p><p>Try dubble checking the connections, is it hooked up correctly? </p><p>otherwhise the arduino or the sensor might be broken, so try an other senser or an other arduino or at least other pin(make sure to change them in de code too).</p><p>Good luck</p>
<p>hello sir can im doing obstacle avoidance robot with vacuum cleaning robot.im need to use 3 ultrasonic HC-SR04 sensors in front of the robot.can i connect VCC and Gnd pin directly to the regulated 5V from IC7805 will affect the working of sensors.if not is there any way to connect 3 sensors</p>
<p>You can just use the normal 5v and GND pins on the arduino. Just connect all 5v pins on the sensors to the 5v on the board, do the same for the GND. If you do this you can leave the two &quot;pinmode&quot; and the &quot;digitalWrite(2, HIGH);&quot; lines out.</p><p>I just used these so I could plug the sensor directly into the arduino. </p><p>Also if the sensors do not work properly try connecting them to another 5v powersupply as the current on the arduino may not be sufficient to power sensors and motors. Good luck!</p>
<p>my module iz not working properly, is there any solution to fixed it, anyone plz help....</p>
<p>I could be anything. Can you be more specific?</p><p>Also try dubble checking the connections and the code and if you have an other arduino try that one.</p>
<p>Actually my sensor HC-SR04 iz not working, i doubt whether it is damage or not! is there any method to repair it or nt, and bundle of thanx 4 ur response</p>
<p>I dont think repairing is an option. You could try to remove the calculations from the code, so it displays the direct signal. &quot;serial.println(duration)&quot; </p><p>Other whise ask it on a forum like reddit.com/r/arduino</p><p>Good luck</p>
<p>I would do it this way, cause pulseIn() hang the system for a certain time and interrupt does not.<br><br>Code:<br><br>#define broche_Trig 12<br>#define broche_Echo 3<br>#define broche_Piezo 8<br><br>volatile unsigned long last_detection = 0;<br>unsigned long last_detection2 = 0;<br>const int Ping_interval = 150;<br><br>const double k_Mach = 29.4117647;<br><br>int duration;<br>double distance;<br><br>void setup() {<br><br>&nbsp;&nbsp;attachInterrupt(1, got_echo, FALLING);<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;pinMode(broche_Trig, OUTPUT);<br>&nbsp;&nbsp;pinMode(broche_Echo, INPUT);<br><br>&nbsp;&nbsp;Serial.begin (115200);<br>&nbsp;&nbsp;<br>}<br><br>void loop() {<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;if(millis() - last_detection &gt;= Ping_interval) {<br>&nbsp;&nbsp;<br>&nbsp;&nbsp; &nbsp;digitalWrite(broche_Trig, HIGH);<br>&nbsp;&nbsp; &nbsp;delayMicroseconds(5);<br>&nbsp;&nbsp; &nbsp;digitalWrite(broche_Trig, LOW);<br>&nbsp;&nbsp; &nbsp;last_detection = millis(); &nbsp;&nbsp;<br>&nbsp;&nbsp; &nbsp;last_detection2 = micros();<br>&nbsp;&nbsp; &nbsp;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;<br>&nbsp;&nbsp;<br>}<br><br>void got_echo(){<br>&nbsp;&nbsp;<br>&nbsp;&nbsp; &nbsp; duration = micros() - last_detection2 ;<br>&nbsp;&nbsp; &nbsp; distance = (0.5&nbsp; *(duration / k_Mach)) - 8 &nbsp;; // - 8 ???<br>&nbsp;&nbsp; &nbsp; Serial.println((String)distance + F(&quot; cm&quot;));<br><br>}<br><br></p>
<p>ahah I got this code from my BF Frederic Plante. ;)</p>
<p>Awesome bt didnt get it!</p>
can i just short the echo and trig pin in the ultra sonic sensor so that i dont have to changed anything in the code?
<p>ya u can short trig pulse but cant echo b/c it depends upon module!</p>
<p>someone did: </p><p>http://www.instructables.com/id/Hack-an-HC-SR04-to-a-3-pin-sensor/</p>
Probably not, wouldn't try it
<p>ahhh but you are wrong my freind tolstoyan is correct that is how i do myne and yes you should hear it i have no clue why but you can anyway you can short them Becouse! if you short them they still have enouph time to jump from the arduino then both ways then into them both (The Echo Pin Practicly Ignores The Input Signal) Then The Trig Pin TAkes That Power Gladly And Actavates The Sensor While Still Dischargeing Intime To Have The Sensor Send Power Back To The Arduino And It Dose This The Whole Time You Want It To Contnue Runing.</p>
<p>Hi! I was wondering if the 3 pin was better than the four pin or is there no big difference between them?</p>
<p>There is difference! 3 pin gives out 4 byte serial output! but 4 pin is not like that. </p>
<p>There is not too much of a difference. Just the fact that it saves one pin on the arduino and that you can use it if giving your robot a wide angle sight or about 4 or more sensors.</p>
<p>Also this was by far the cheapest sensor I could get :)</p>
<p>oh yes. forgot about that</p>
<p>How does one perform this process in reverse? Using a 4-pin sensor code and converting it to 3-pin?</p>
<p>&quot;Using a 4-pin sensor code and converting it to 3-pin?&quot;</p><p>I did exactly that! I started with the 4 pin code:<a href="http://arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor" rel="nofollow">http://arduino.cc/en/Tutorial/Ping?from=Tutorial.U...</a></p>
<p>how would i display the serial on an lcd? </p>
<p>Try combining code. I mostly used to take code from arduino.cc and make little changes or combine multiple examples. If you combine this code and a simple sensor-to-lcd code you should be able to get it to work. Good luck!</p>
<p>#include &lt;LiquidCrystal.h&gt;<br><br>LiquidCrystal lcd(12, 11, 5, 4, 3, 2);<br>int backLight = 13; // pin 13 will control the backlight<br><br>void setup() <br>{<br> pinMode(backLight, OUTPUT);<br> digitalWrite(backLight, HIGH);<br> pinMode (2,OUTPUT);//attach pin 2 to vcc<br> pinMode (5,OUTPUT);//attach pin 5 to GND<br> lcd.begin(16, 2);<br> // initialize the serial communications:<br> Serial.begin(9600);<br>}<br>void loop()<br>{<br>digitalWrite(2, HIGH);<br> // establish variables for duration of the ping,<br> // and the distance result in inches and centimeters:<br> long duration, inches, cm;<br><br> // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.<br> // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:<br> pinMode(3, OUTPUT);// attach pin 3 to Trig<br> digitalWrite(3, LOW);<br> delayMicroseconds(2);<br> digitalWrite(3, HIGH);<br> delayMicroseconds(5);<br> digitalWrite(3, LOW);<br><br> // The same pin is used to read the signal from the PING))): a HIGH<br> // pulse whose duration is the time (in microseconds) from the sending<br> // of the ping to the reception of its echo off of an object.<br> pinMode (4, INPUT);//attach pin 4 to Echo<br> duration = pulseIn(4, HIGH);<br><br> // convert the time into a distance<br> inches = microsecondsToInches(duration);<br> cm = microsecondsToCentimeters(duration);<br> <br> Serial.print(inches);<br> Serial.print(&quot;in, &quot;);<br> Serial.print(cm);<br> Serial.print(&quot;cm&quot;);<br> Serial.println();<br> <br> delay(150);<br>}<br><br>long microsecondsToInches(long microseconds)<br>{<br> // According to Parallax's datasheet for the PING))), there are<br> // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per<br> // second). This gives the distance travelled by the ping, outbound<br> // and return, so we divide by 2 to get the distance of the obstacle.<br> // See: <a href="http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf" rel="nofollow"> http://www.parallax.com/dl/docs/prod/acc/28015-PI...</a><br> return microseconds / 74 / 2;<br>}<br><br>long microsecondsToCentimeters(long microseconds)<br>{<br> // The speed of sound is 340 m/s or 29 microseconds per centimeter.<br> // The ping travels out and back, so to find the distance of the<br> // object we take half of the distance travelled.<br> return microseconds / 29 / 2;<br> // when characters arrive over the serial port...<br> if (Serial.available()) {<br> // wait a bit for the entire message to arrive<br> delay(100);<br> // clear the screen<br> lcd.clear();<br> // read all the available characters<br> while (Serial.available() &gt; 0) {<br> // display each character to the LCD<br> }<br> }<br> }</p><p>That's my current code, any reccomendations?</p>

About This Instructable

165,126views

107favorites

License:

More by Giedow:Physical USB Drive protectionElectronic part organizer - 3d printedphoton blaster
Add instructable to: