11 November 2012

HC-SR04 Ultrasonic Sensor


Introduction:

The HC-SR04 Ultrasonic Sensor is a very affordable proximity/distance sensor that has been used mainly for object avoidance in various robotics projects . It essentially gives your Arduino eyes / spacial awareness and can prevent your robot from crashing or falling off a table. It has also been used in turret applications, water level sensing, and even as a parking sensor. This simple project will use the HC-SR04 sensor with an Arduino and a Processing sketch to provide a neat little interactive display on your computer screen.



Parts Required:
Freetronics Eleven or any compatible Arduino.
HC-SR04 Ultrasonic Sensor
Mini Breadboard 4.5cm x 3.5cm
Protoshield and female header pins (not essential - but makes it more tidy)
Wires to connect it all together




The Video:




The Arduino Sketch:



     The above sketch was created using Fritzing.





Arduino Code:
You can download the Arduino IDE from this site.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
 HC-SR04 Ping distance sensor:
 VCC to arduino 5v 
 GND to arduino GND
 Echo to Arduino pin 7 
 Trig to Arduino pin 8
 
 This sketch originates from Virtualmix: http://goo.gl/kJ8Gl
 Has been modified by Winkle ink here: http://winkleink.blogspot.com.au/2012/05/arduino-hc-sr04-ultrasonic-distance.html
 And modified further by ScottC here: http://arduinobasics.blogspot.com.au/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html
 on 10 Nov 2012.
 */


#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */ 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10); 
 
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;
 
 if (distance >= maximumRange || distance <= minimumRange){
 /* Send a negative number to computer and Turn LED ON 
 to indicate "out of range" */
 Serial.println("-1");
 digitalWrite(LEDPin, HIGH); 
 }
 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW); 
 }
 
 //Delay 50ms before next reading.
 delay(50);
}

The code above was formatted using hilite.me





Processing Code:
You can download the Processing IDE from this site.

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/* The following Processing Sketch was created by ScottC on
 the 10 Nov 2012 : http://arduinobasics.blogspot.com/
 
 Inspired by this Processing sketch by Daniel Shiffman:
 http://processing.org/learning/basics/sinewave.html
 
*/
import processing.serial.*;


int numOfShapes = 60; // Number of squares to display on screen 
int shapeSpeed = 2; // Speed at which the shapes move to new position
 // 2 = Fastest, Larger numbers are slower

//Global Variables 
Square[] mySquares = new Square[numOfShapes];
int shapeSize, distance;
String comPortString;
Serial myPort;

/* -----------------------Setup ---------------------------*/
void setup(){
 size(displayWidth,displayHeight); //Use entire screen size.
 smooth(); // draws all shapes with smooth edges.
 
 /* Calculate the size of the squares and initialise the Squares array */
 shapeSize = (width/numOfShapes); 
 for(int i = 0; i<numOfShapes; i++){
 mySquares[i]=new Square(int(shapeSize*i),height-40);
 }
 
 /*Open the serial port for communication with the Arduino
 Make sure the COM port is correct - I am using COM port 8 */
 myPort = new Serial(this, "COM8", 9600);
 myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
}

/* ------------------------Draw -----------------------------*/
void draw(){
 background(0); //Make the background BLACK
 delay(50); //Delay used to refresh screen
 drawSquares(); //Draw the pattern of squares
}


/* ---------------------serialEvent ---------------------------*/
void serialEvent(Serial cPort){
 comPortString = cPort.readStringUntil('\n');
 if(comPortString != null) {
 comPortString=trim(comPortString);
 
 /* Use the distance received by the Arduino to modify the y position
 of the first square (others will follow). Should match the
 code settings on the Arduino. In this case 200 is the maximum
 distance expected. The distance is then mapped to a value
 between 1 and the height of your screen */
 distance = int(map(Integer.parseInt(comPortString),1,200,1,height));
 if(distance<0){
 /*If computer receives a negative number (-1), then the
 sensor is reporting an "out of range" error. Convert all
 of these to a distance of 0. */
 distance = 0;
 }
 }
}


/* ---------------------drawSquares ---------------------------*/
void drawSquares(){
 int oldY, newY, targetY, redVal, blueVal;
 
 /* Set the Y position of the 1st square based on 
 sensor value received */
 mySquares[0].setY((height-shapeSize)-distance);
 
 /* Update the position and colour of each of the squares */
 for(int i = numOfShapes-1; i>0; i--){
 /* Use the previous square's position as a target */
 targetY=mySquares[i-1].getY();
 oldY=mySquares[i].getY();
 
 if(abs(oldY-targetY)<2){
 newY=targetY; //This helps to line them up
 }else{
 //calculate the new position of the square
 newY=oldY-((oldY-targetY)/shapeSpeed);
 }
 //Set the new position of the square
 mySquares[i].setY(newY);
 
 /*Calculate the colour of the square based on its
 position on the screen */
 blueVal = int(map(newY,0,height,0,255));
 redVal = 255-blueVal;
 fill(redVal,0,blueVal);
 
 /* Draw the square on the screen */
 rect(mySquares[i].getX(), mySquares[i].getY(),shapeSize,shapeSize);
 }
}

/* ---------------------sketchFullScreen---------------------------*/
// This puts processing into Full Screen Mode
boolean sketchFullScreen() {
 return true;
}

/* ---------------------CLASS: Square ---------------------------*/
class Square{
 int xPosition, yPosition;
 
 Square(int xPos, int yPos){
 xPosition = xPos;
 yPosition = yPos;
 }
 
 int getX(){
 return xPosition;
 }
 
 int getY(){
 return yPosition;
 }
 
 void setY(int yPos){
 yPosition = yPos;
 }
}

The code above was formatted using hilite.me


76 comments:

  1. Cool. I got it working and it's pretty neat. Gonna toss around some ideas in my head of what I can do with it.

    Thanks.

    ReplyDelete
    Replies
    1. I would be interested to know what you come up with :)

      Delete
  2. My processing screen is all black, i get distance readings in the arduino IDE. why is this?

    ReplyDelete
    Replies
    1. Make sure that you close the Serial Monitor on the Arduino IDE before running the processing sketch.

      Delete
  3. Hello, how could i make it so that when at specific distance the sensor triggers different video clips to be projected on the wall?

    ReplyDelete
    Replies
    1. Hi MJ, This is not very easy to explain in a comment but I will try my best. In the Processing example above on line 57, you have the distance variable. You would map the distance variable to the number of videos you want to play. So if you have 10 videos, you would map the distance variable like this:


      distance = int(map(Integer.parseInt(comPortString),1,200,1,10));



      You may need to constrain the distance value.

      Then you would select the video based on the distance variable using switch-case. With each case set up to play each video.

      Click on the links provided within my answer for more information.
      Hope that helps

      Delete
  4. Cool project!
    Where have you downloaded the fritzing part for the ultrasonic sensor?

    ReplyDelete
    Replies
    1. I am pretty sure from the Fritzing website. From memory I think they had a forum where people could contribute Fritzing parts. Have not been to that site for a while but I am pretty sure that's where I got it from. However Fritzing has been through some major changes since then.

      Delete
    2. Here is the download link as of the 21st May 2013:
      DOWNLOAD HERE

      Or alternatively visit the page yourself and search for HC-SR04:
      Fritzing custom parts Webpage

      Delete
  5. Beginner here, I have a 64 bit system therefore I downloaded the 64 bit version of Processing, but when I try to run this example appears "serial is only compatible with the 32-bit download of Processing"

    Any help? Thanks

    ReplyDelete
    Replies
    1. Hi Dan zl,

      I think I fell for the same trap. I had to resort to downloading the 32-bit version instead, because the 64 bit version does not support Serial.

      Scott

      Delete
    2. Thank you very much for taking the time to help me, ...and I´m sorry for taking so long in answer back. At the moment I was hurry trying to finishing a little project, and I have another Chromebook with Ubuntu 12.04 installed, I check there if was working and it does so I just finish it and forget it for about a week. Now in vacation I´m checking some other project to learn something else from your page. Thanks again for all your amazing work.

      Delete
  6. echopin will be high once it receives back the signal. therefore pulsein(echopin, HIGH) will give the duration for which the echopin receives the signal..it will not give the total time for the signal.. but only the time for which the echo sensor receives it..

    ReplyDelete
    Replies
    1. I am not sure what you mean. Can you please explain further. Thanks Scott

      Delete
    2. I am also confused about the same thing. pulseIn reads the length of time where echoPin receives the signal, but shouldn't it read the time between sending the pulse and receiving it with echoPin? In other words woudn't it make more sense to set duration = pulseIn(echoPin, LOW);?

      Delete
    3. Hey Scott,
      I think I'm confused about the same thing here (I'm a beginner so I'm confused a lot).

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

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

      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);

      //Calculate the distance (in cm) based on the speed of sound.
      distance = duration/58.2;

      From what I see, you send a pulse that is 10 microseconds long and then use PulseIn to read the length of that pulse again? Shouldn't it be using LOW instead of HIGH to read the time it takes before receiving the pulse? Maybe I don't understand the PulseIn function well enough or I don't understand the sensor (haven't received mine yet).

      Thanks, Steve

      Delete
    4. HI Steve,

      All examples that I have seen on the net seem to have it set this way.
      I am pretty sure the digitalWrites are there to initialise the sensor, and then the pulseIn measures the pulse. I have read that by setting pulseIn to High, that the sensor will pulse:
      LOW_HIGH_LOW...
      You can try setting it to LOW and see what happens... but I have not seen it setup that way.
      If you do decide to do it that way - then please let me know how you go.

      Regards
      Scott

      Delete
    5. Thanks Scott, I will test this when my sensor arrives.

      Delete
  7. Hello Scott. I would like to ask something. I am new to arduino. I wanna do a project that is a power line detection. So, can this HC-SR04 sensor detect the distance of tight surface like a finger? Have you try to distance measure of tight surface? Thank you.
    Md

    ReplyDelete
    Replies
    1. if it can bounce sound waves, then it will work.

      Delete
  8. New to Arduino IDE. I couldn't get any communication from Arduino Mega 2560 to Processing PDE on my Mac. I couldn't figure out which serial com port to use, so I changed this piece of code;

    /*Open the serial port for communication with the Arduino
    Make sure the COM port is correct - I am using COM port 8 */
    myPort = new Serial(this, "COM8", 9600);
    myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
    }

    to this;

    /*Open the serial port for communication with the Arduino
    Make sure the COM port is correct - I am using COM port 8 */
    myPort = new Serial(this, Serial.list()[0], 9600);
    myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
    }

    Now it works fine. I used Daniel Schiffman's sketch Example 19-8: Reading From Serial Port as a basis for making this change. On my Mac /dev/tty.usbmodemfaXXX is the port used for communication with Arduino and Processing. However obvious, I did not realize it was [0].

    How can I determine the actual port number?

    Thanks for the sketch!

    ReplyDelete
    Replies
    1. I know nothing about macs - but I would say you could have a look at the port being used by the Arduino IDE (normally displayed at the bottom of the Arduino IDE)

      Delete
  9. Thats Awesome men, thank for share this !

    ReplyDelete
  10. snowwite and the 7 monkeys11 November 2013 00:15

    perrrrrrrrrrrrrrrrrrrrrrrrrfecto! well as i do say so myself this really helped except i just had to make a weensy change from the diagram with tons of research :)

    ReplyDelete
  11. If found an error ..
    Change : comPortString = cPort.readStringUntil('\n');
    To comPortString = (new String(cPort.readBytesUntil('\n')));

    ReplyDelete
    Replies
    1. thank you now it is working.

      Delete
  12. Hey thank you so much for the diagram and code. The code helped me a lot, since I'm a beginner and I can't write codes yet, although I have started to copy and paste from different codes into one code for my own robot (and it worked:D). Since I have the kind of breadboard that has negatives and positives, I had to bring the wires from the 5V and GND into the - and +. But the sensor is awesome, thank you so much!

    ReplyDelete
    Replies
    1. yea, hashbrown's right. thnx a lot scott!

      Delete
    2. That's great hashbrown, and you are welcome anonymous.
      Feel free to post a link to your project or share a video of your robot in action.

      Delete
  13. Hello, I am having trouble with the execution of this code. I copy all the code for both the arduino and the processing but it does not recognize the "comPortString = cPort.readStringUntil('\n');". I get the error "The function readStringUntil(char) does not exist.

    ReplyDelete
    Replies
    1. Sorry just saw the post above. Thanks!

      Delete
  14. Hello.
    I have question and I need help. For my project I need to program ultrasonic distance sensor and volume control. Does anyone have an idea how I can connect those two things?

    ReplyDelete
    Replies
    1. Hi balkanskikanali,
      Which volume control?... ie on your computer or on a stereo or a shield?
      Are you planning on using an Arduino?
      I assume you want to change the volume based on the distance?

      Delete
    2. Hello. Thanks for answering, If you can write me on my e-mail, if you know the solution. Yes I will do it for computer volume control based on distance... filipetus@yahoo.com

      Delete
    3. Have a look here:
      http://processing.org/discourse/beta/num_1224778221.html
      and here:http://forum.processing.org/one/topic/volume-control.html
      It may be worth asking for some help in the processing or arduino forums. I am sure many will learn from your efforts.

      Delete
    4. Hello. Thanks for answer. I triend to adjust the volume based on the distance with processing, but I just cannot solve it. Any help maybe? How I can do it with HC-SR04?

      Delete
    5. First set up the sensor as per this example and send the values to the computer. Using processing, you will listen for these values over the serial port. Based on the values received you will "map" these to the limits of your volume control. Now it depends on what exactly you are trying to adjust the volume of?? A sound, a movie? Or just the computer volume. I have never done this before which is why I provided you with the links. Try the processing forums for specific help on your project. They will help you very quickly.

      Delete
    6. First, your blog is awesome. I like it very much. Second, Processing forums that i found are close one or more years ago. Do you know one that is still open where I can ask this?
      Your example works fine for me. Can you send me maybe a processing code that just change colors from black to white or reverse according to distance sensor if you have?

      Delete
    7. Here is the link to the active processing forum.
      Use the Arduino sketch as per this example, then use this code in Processing:

      import processing.serial.*;

      String comPortString;
      Serial myPort;
      int distance;

      /* -----------------------Setup ---------------------------*/
      void setup(){
      size(displayWidth,displayHeight); //Use entire screen size.
      background(0); //Make the background BLACK
      myPort = new Serial(this, Serial.list()[0], 9600);
      myPort.bufferUntil('\n'); // Trigger a SerialEvent on new line
      distance = 0;
      }

      /* ------------------------Draw -----------------------------*/
      void draw(){
      background(distance);
      delay(50); //Delay used to refresh screen
      }


      /* ---------------------serialEvent ---------------------------*/
      void serialEvent(Serial cPort){
      comPortString = (new String(cPort.readBytesUntil('\n')));
      if(comPortString != null) {
      comPortString=trim(comPortString);
      distance = int(map(Integer.parseInt(comPortString),1,200,1,255));
      if(distance<0){
      /*If computer receives a negative number (-1), then the
      sensor is reporting an "out of range" error. Convert all
      of these to a distance of 0. */
      distance = 0;
      }
      }
      }


      /* ---------------------sketchFullScreen---------------------------*/
      // This puts processing into Full Screen Mode
      boolean sketchFullScreen() {
      return true;
      }

      Delete
    8. Thank you very much. I do not want to bother you anymore. YOu have done well all. This processing works fine, and you know maybe which part here i can change so it can be rgb colors change according to distance? Thanks in advance :)

      Delete
    9. This is the processing code I tried for volume control but it does not work....just to post so you can have a look. It is based on the same arduino code like here on blog.

      import processing.serial.*;
      import ddf.minim.*;

      Serial myPort;

      AudioPlayer player;
      Minim minim;
      int volume = 0;
      int distance; // Data received from the serial port

      void setup()
      {
      size(512, 200, P2D);
      String portName = Serial.list()[5];
      myPort = new Serial(this, portName, 9600);

      minim = new Minim(this);
      player = minim.loadFile("myfile.mp3");
      player.play();
      player.loop();
      println(player.hasControl(Controller.GAIN));
      }

      void draw()
      {
      background(0);
      if ( myPort.available() > 0) { // If data is available,
      distance = myPort.read(); // read it and store it in val
      println(distance);
      }
      distance = constrain(distance, 1 , 40);
      float volume = map(distance, 1, 40, -20, 20);
      //println(volume);
      //println("");
      player.setGain(volume);
      delay(100);

      }

      void stop()
      {
      // always close Minim audio classes when you are done with them
      player.close();
      minim.stop();

      super.stop();
      }

      Delete
    10. In terms of rgb background based on distance - you will have to change the code within draw():
      The code that will need to change is
      background(distance);

      Have a look at how to change the background here.

      And with regards to your sound volume code,
      Why are you choosing the 6th com port:
      String portName = Serial.list()[5];
      myPort = new Serial(this, portName, 9600);


      Perhaps change it to
      myPort = new Serial(this, Serial.list()[0], 9600);

      Especially considering that you said that my code worked for you.
      Also you did not say what part of it was not working.
      And once again - this type of help is best addressed in a forum - rather than a comment section of a blog - I promise - it is a whole lot easier and quicker.

      Regards
      Scott


      Delete
    11. I wanted that from distance my color starts from white, goes throw yellow, red, blue and on the far distance finishes on black or reverse it is the same. Now I need to see how to do that.... Your code works fine for me, all the parts. Port 0 sends error that is why I am using port 5(com11), my arduino is on that port as well. For volume, I posted question on forum, we will see if anyone knows the answer...

      Delete
    12. Can you send me that part of the code how not to change black to white color then rgb colors?
      I know it is better on forums but here people that visit your great profile can see if they have similar problems. :))

      Delete
    13. May not be exactly what you need but put this in the setup() section:
      colorMode(HSB);

      Then change background(distance); in the draw() section to this;
      background(distance,255,255);

      Delete
    14. Thanks Scott, it works fine. Now just to see how to change that code for volume control of one song. On forum nobody is answering, but I will wait a little bit, if you have time and look on my code for volume control i can appreciate that. Thanks anyway. :(

      Delete
    15. When you say the code for volume control does not work... Where is it failing? Is it loading the song? Is it receiving values from the Arduino? Is it playing the song? Are you seeing a distance being printed? Rather than try to just copy and paste someone else's code... Start with the bare minimum. Make sure that works. Then add some code with some println snippets to make sure the values are doing what you expect. Use google to find out more about what each section of code is doing. Try and understand the code, and you will get a whole lot more out of it in the end.

      Delete
    16. I have done it, now volume control works. If you can I can post here for your visitors or I can send to you :))

      Delete
    17. You can post here or
      post on Processing forum and then put a link to the forum post
      Either way - I don't mind.

      Glad to hear that you managed to get it to work.
      Well done.

      Delete
  15. When I try to run the processing sketch, an error comes up saying; the function readStringUntil(char) does not exist. When that happens, this line of code is highlighted; comPortString = cPort.readStringUntil('\n');
    I'm a beginner, and would appreciate the help

    ReplyDelete
    Replies
    1. This is a problem with the new version of Processing:
      Change : comPortString = cPort.readStringUntil('\n');
      To: comPortString = (new String(cPort.readBytesUntil('\n')));

      Delete
  16. i did what you explainned in the picturte should i copy the code on the arduino program by the word or i'm going to takeoff some things

    ReplyDelete
    Replies
    1. If you plan to run this complete project. You can copy and paste the arduino sketch and upload it to the arduino. And then copy and paste the processing sketch to the processing IDE, and run it. However you may need to modify the com port based on you specific setup and operating system.

      Delete
  17. One question about the cubes Scott, which part needs to be changed so when the application starts cubes are up and with going far from sensor they come down?

    Thanks...you are the best

    ReplyDelete
    Replies
    1. I cannot remember if this works or not - but feel free to try
      change this:
      distance = int(map(Integer.parseInt(comPortString),1,200,1,height));
      to
      distance = int(map(Integer.parseInt(comPortString),1,200,height,1));

      Delete
  18. hi can anyone help me? i got a problem running the code its say that >processing.app.SerialNotFoundException: Serial port 'COM1' not found. Did you select the right one from the Tools > Serial Port menu?

    please help me, thanks!

    ReplyDelete
    Replies
    1. Make sure to connect and upload the Arduino Sketch to the Arduino before running the Processing sketch. Make note of which com port you are using for your Arduino. Look at the bottom right hand side of the Arduino IDE (after upload).
      Also make sure to close the Arduino IDE Serial Monitor before running the Processing sketch.

      Delete
    2. thanks Scott i solve the problem, but i have another problem here > avrdude: stk500_getsync(): not in sync: resp=0x00

      can u help me again? thanks in advance!

      Delete
    3. What Arduino board are you using? Have you selected this board in the Arduino IDE?
      And have you confirmed you are using the correct COM port?

      Delete
  19. Good day Scott, awesome blog. I need some help with my little project. I am trying to make a system for my RC car that could detect traffic. My idea would be to count the the distance measure by the ultrasonic, if the distance doesn't change for (for example) 10 seconds then it would trigger to light an LED. Can u help me with this please ? Or do you have any idea how I could possibly do that ? thanks in advance Scott and more power !

    ReplyDelete
    Replies
    1. I am assuming that you will only detect distance while the RC car is motionless?
      You could use a loop and counter - checking the distance on each iteration, if the distance changes by more than a certain amount then digitalwrite(ledPin, HIGH).
      Or if the distance is less than a certain amount - trigger the digitalwrite.
      Loop 100 times or 1000 times - or however many times you think is appropriate.
      Once the counter reaches a certain number - you can exit the loop.

      Delete
    2. This comment has been removed by a blog administrator.

      Delete
    3. Hi Allencio,
      Is it possible to upload video to YouTube? Leave link in comment below.
      I would also advise to post your query on the Arduino forum, which is much better geared for troubleshooting specific issues. You could post your entire code there, plus there would be many experts that would jump at the occasion of helping you. Feel free to leave a link to the Arduino forum query in the comments below. And after seeing the entire code will be in a better position to help you. This blog is not really set up for troubleshooting issues.
      Your project looks interesting, and I am keen to help.

      Delete
  20. Is there any codings for crack detection in a plain surface using Ulrasonic sensor??..

    ReplyDelete
    Replies
    1. not on this blog - but someone surely has done this somewhere on the internet

      Delete
  21. Hello Scott, I would like to ask something. I am some what weak in arduino programming . I wanna do a project with one ultra sonic sensor (HC sr04) in arduino and my task is to find the speed ((Velocity Km/H) Using Ultrasonic Sensor ) of the object crossing through my US sensor (HC sr04) ,all i need is coading for this task ..I'm sorry to force you , but i need as soon as possible ...More over your blog is AWESOME ....
    regards,
    shiva

    ReplyDelete
    Replies
    1. Hi Shiva,
      Is the object coming towards the sensor or crossing it's path?
      If it is crossing it's path, I would guess that you have more than one sensor? And I would say that this is not the best sensor to measure an object's speed. But with 2 sensors, I guess it is possible. With one sensor - I guess you have to tell me how you plan to achieve the multiple measurements to convert distance to speed.

      If it is coming towards the sensor, once again, probably not the best sensor for your project.
      It depends on how fast and how large your speeding object is.

      Speed = change in distance / time.
      I hope you got that far :)

      Delete
  22. Thanks for your replay scott, actually it's my class assignment given by my staff , he just simply given me a arduino and one ultra sonic sensor (HC sr04) and he told me to find the object speed which is CROSSING through the sensor's path ..he(staff) said that it is possible to find the speed using one sensor itself .. what i all need is object speed in (km/h),i am extremely sorry for my poor english

    ReplyDelete
    Replies
    1. Hi Shiva,
      This is how I would do it. But not sure how accurate it would be.
      Secure the sensor and get a baseline reading. There may be some variation between readings, but get to know the sensor and understand the amount of error (ie difference in readings). Then move your object across the path of the sensor, ensuring that the distance is notably different from the original readings.
      You will have to establish a trigger distance, so that when your sensor detects the shorter distance it will measure the time or start a clock. When it detects the baseline distance +/- error , then it will stop the clock or measure the time again.
      The return to baseline should trigger the code to do time calculation (ie end time - start time). Now all you have left to do is get a tape measure and measure the length of the object. Use this measurement to calculate the speed.
      Speed = length of object(km). / time (hr).

      By the way, I am not going to write you the code, because that is the whole point of your assignment, and how else are you supposed to learn, unless you work it out ;)

      Delete
  23. Another example of the code you can find here http://thechipcode.com/article.php?artical_id=147

    ReplyDelete
  24. how to interface between this prog and matlab to get final graph

    ReplyDelete
    Replies
    1. Hi Mahmoud - This is one for the forums. Never done it. Sorry.

      Delete
    2. Hi mahmoud
      Please if you get solution for that tell me.....

      Delete
  25. Hiii
    Please if I have parallax ping ultrasonic sensor how I connected it with arduino and how programming it to send data through xbee sheild and module? .
    I hope to help me....

    ReplyDelete
    Replies
    1. I don't have a parallax ping ultrasonic sensor - but this site may help.
      As for XBee communication - I have an partially completed tutorial which may help you to get started, but there are many tutorials out there on the internet that show you how to do this.
      Try to do each of these separately before trying to join or combine them.

      Delete

Feel free to leave a comment :