Tag Archives: HC-SR04

Python with Ardiuno LESSON 3: Simple Virtual World Using Ultrasonic Sensor

In this tutorial we will show how you can use Python with the Vpython library to begin to create some pretty cool graphics for presenting sensor data from the Arduino. For this tutorial, we will be using the HC-SR04 ultrasonic sensor, which you learned about in Arduino LESSON 17,  Arduino LESSON 18, and Arduino LESSON 20. Please review those lessons if you are not familiar with the HC-SR04.

The circuit is very simple and can be connected from this schematic:

Simple Circuit for Operating the HC-SR04 Ultrasonic Sensor.

Since the object of this lesson is to show what you can do using Python and Vpython, I will not go through the arduino code step-by-step. You can go back to the earlier lessons for more info on the HC-SR04 sensor. The code that will allow the sensor to make distance measurements is presented again here. The one thing to note is that since we are going to be using Python to graphically present the data coming from the sensor, we want to simply send the distance measurement over the serial port, and no words or anything else, just the raw distance measurement. This will simplify things on the Python side. Remember that when we do a Serial.println() command in arduino, we can read whatever is printed into Python, as we learned in Arduino and Python LESSON 2.  The code below is what you need on the Arduino side.

This code will be constantly sending the distance to the target out over the Serial port.  On the Python side, our first task is to read that data in over the serial port.  To do this, you must import the serial library. (Instructions on installing Pyserial are in Arduino with Python LESSON2.) You then create a serial object which will be used to read the data. In the sample below, we call the object ‘arduinoSerialData’. We then create a While loop that loops continuously. Inside that loop we check to see if there is any data available on the serial port, and if there is, we read it into the variable myData, and print it.

Remember than in the line that creates the adruinoSerialData object, you need to change the com port to whatever com port your arduino is sending on. You can see this by looking under tools- port in your arduino IDE window. Also, this format is for windows machines. You would have to adjust for apple computers.

It is important to remember that the command .readline() in Python will read a string, so we need to remember that myData is a string, and if we want to use it as a number we will need to convert it to a float, with something like distance = float (myData). Then distance will be a normal number, not a string.

As a first demonstration lets create an object using the vPython library that is a cylinder. We will need to import the vPython library, and we will create the object before the while loop, and then inside the while loop, we will adjust the length parameter of the cylinder. We will make the cylinder with a length of six inches, we will make it yellow in color, and with a radius of 1/2 inch. Also, when we are using Vpython and dynamically updating a graphic object, inside the loop that is adjusting the graphic, we have to issue a rate() command. The rate command tells vPython how many times a second you want to go through the loop. You need to play with this command, so that it gives smooth graphics for the rate at which the Arduino is sending data. rate(20) is sometimes a good starting point. So, our code now looks like this:

So, this is pretty cool! It creates a little rod, and the length of the little rod dynamically changes in response to how far your target is from your sensor. This gives a very nice qualitative visual to what is happening in the real world with your sensor. Often times you also want quantitative indication of the data.  We can do that by adding a label. Before the while loop, we will create a label object called lengthLabel. We will position it up just a little bit, so it is not on top of the measuringRod. We will set the label initially to ‘Target Distance is: ‘. We will also want to set box=false, since we do not want a box around our text. Then, a good height for the label is about 30 pixels. You can play around with all these settings. We create the lengthLabel before the while loop, but then inside the while loop we dynamically update the lengthLabel.text parameter. We set it to our myLabel string, which is dynamically being updated to be the concatination of the string ‘Target Distance is: ‘ and the string myData. Remember, myData is read as a string, and so we use that variable, and not distance, which is a number, not a string. Pulling this together leads to this code:

Lets keep playing around with this. The graphic will begin to look more like a’Virtual World’ if we create a box to represent the target we are using in the real world.  I will make the box the dimensions of the real target, which is .2 X 3 X 3. Also, I will make it green, just like the target in the real world. In order to better fill our viewing window, I will move the cylinder down by about 2 inches, so its new position will be (-3,-2,0). For box type objects position is measured from the center, so I will need to also move the target box down by about .5, so it will coincide with the measuring rod. this is because 1/2 the target would be 1.5, and moving down by an additional .5 will make it coincide with the measuringRod.

Finally, I need to dynamically update the position of the target box in the while loop. I will need it to be placed at target.pos=(-3+distance,-.5,0). Along the x-axis this will put it right at the end of the rod, and will keep it properly positioned in y, as before. Bringing all this code together we get:

 Play around with the parameters until you get something you are happy with. Also, you can change your view of the visual once the program is running. Right mouse click and you can change your positional view of the virtual world you have created. Press and scroll the mouse wheel to change the zoom.

OK, you need to start exploring and creating your own virtual world. Go ahead and see if you can create additional objects to make your virtual world more realistic. Try creating a graphic for the sensor itself, and maybe even your PC board and arduino! You can refer to the Vpython site for more details on the 3D objects you can create, and their parameters at:

http://vpython.org/contents/docs/cylinder.html

Also, if the discription in this lesson is confusing at all please just watch the video, and I will take you through things one step at a time.

LESSON 20: Arduino LCD Project for Measuring Distance with Ultrasonic Sensor

In LESSON 18 you learned how to use an ultrasonic sensor to measure distance, and in LESSON 19 you learned how to connect an LCD to the arduino. In this lesson we will combine what you have learned to create a circuit for measuring distance, and displaying results on an LCD display.

This circuit displays the distance you measure on a cool LCD.

You can use the schematic below to connect the circuit. If you did LESSON 19,  you should already have the LCD hooked up. For more info on connecting to the LCD, and how it works, review LESSON 19. This schematic is for the LCD in the Sparkfun Inventor Kit, or similar LCD. If you have a different LCD, you will have to determine the proper connections. There are some helps in LESSON 19. If you need the ultrasonic sensor, you can pick one up HERE.

This diagram shows how to connect my LCD to the Arduino.

Be very careful connecting the circuit. Check your work, and it helps to work with a Buddy. Have one person looking at the schematic, and one looking at the circuit. Sometimes it is easier to get it right working in pairs.

Now the objective of this project is to measure distance using the ultrasonic sensor, and then display that value on the LCD display. You should have the skills you need from the earlier lessons. Try and do this project on your own, but if you get stuck, you can look at my code below. As always, don’t copy and paste my code, but it should be used as a guide to help you write yours if you get stuck.

Your assignment is to get this project going, and show that you can measure distance and then display it on the LCD. After showing me your work, then you need to take the project in your own unique direction. What can you make based on what you have learned in the last few lessons. You should use some combination of Ultrasonic Sensor, LCD, and Servo to make a project or product or your own invention. You have the technical skills, you have the equipment, now go be creative!

LESSON 18: Distance Meter Using Ultrasonic Sensor and Arduino

In Lesson 17 we learned to use an ultrasonic sensor to measure the speed of sound. There is a different way to use the sensor. Since we know the speed of sound, we can use it to measure distance, since d = r*t (distance = rate * time). You know the rate, that is the speed of sound. You can measure the ‘time’ using the ultrasonic sensor, just as you did in Lesson 17. This is the time for a ping to go from the sensor to the target and back. Knowing this, you can then calculate the distance to the target.

Arduino Distance Sensor Displays Measured Distance with a Servo

For you hackers, just jump right in and do the assignment. You should be able to do it with what you have already learned. What I want you to do, though, is come up with some creative way to display the distance . . . something better than just printing it on the Serial Monitor. I will make a scale and display it using a servo. You can do whatever you think would be most interesting. For those who need a little extra help, I will step you though my project below.  The first thing you need is to hook up your circuit. I have the sensor hooked up like in Lesson 17 and have added a servo. The servo black wire needs to hook to ground, the red wire to 5V from the arduino, and the white wire, which is the control wire, I have hooked to pin  6 of the arduino. Remember that you need to verify that your servo will not draw too much current from the Arduino. The servos in the Sparkfun Inventor Kits work fine, and can be driven directly from the arduino 5V power pin.  Also, your servo might have different colored wires. Many have Red for power, Orange for control , and Brown for Ground.  Always confirm the color code with the data sheet for the specific servo you are using. Also, remember that before using a servo, you need to determine its suitable range of motion. This was explained in Lesson 16.  For my project, I am using the following schematic. It would be better to hook to the ultrasonic sensor by putting the wires behind the sensor, so they do not interfere with the ‘ping’ coming from the front. I drew them in front so you could see them clearly, but wire them on the back side of the sensor.

Arduino Circuit for Measuring Distance.

When you get your circuit set up, we will need to do some math. Our objective is to measure distances between 0 and 7 inches. This sensor could probably do a good job measuring distances up to three feet, but for this project we will focus on 0 to 7 inches. We then want to put a pointer on the servo, and have it point at a scale that will indicate distance. Since the servo swings in an arc, we can best thing about the output of the servo as an angle. On the scale I draw, I want to have the numbers be between angles of 37 degrees and 143 degrees. For a distance measured of 0 inches, I want the servo to point at 37 degrees. For a distance measured of 7 inches, I want to point to 143 degrees. Then, everything should scale between those numbers.  You can see that I drew my scale for my servo above on a piece of polar graph paper. Polar graph paper makes it easy to draw specific angles and ranges of angle. You can print your own polar graph paper at HERE.  Now, the math that has to be done is to calculate the angle you should set your servo at based on what distance measurement you are reading. The numbers have to match the scale you draw for the servo. For mine, I want a measurement of 0 inches to put the servo at 37 degrees, and a measurement of 7 inches to put the servo at 143 degrees. These match the positions of the ‘0’ and ‘7’ on my scale. By this time you should be comfortable doing the math, but if you need help, you can check my notes below.

These notes show you how to calculate servo position based on measured distance.

You will need to draw our own servo scale. You can arrange the scale however you like, but in the end, you have to do the math so that your servo points at the right distance number on your scale.

With that out of the way, we now need to do the coding. There is not really anything new to learn as far as coding goes. This is really a combination of what you learned in lesson 16 and lesson 17.  In this project though, instead of measuring the speed of sound, we will be measuring the distance to a target, given the known speed of sound. Then we use the math above to calculate where to point the servo. The video above will take you through the code step by step, but I include the code below. You should not copy and paste the code, but just look at it if you get stuck. For those of you in my class when I check you project for a grade, I will be looking to see if you are working independently, or just copying what I am doing.

Now your assignment is to come up with a new and different way to display the distance. On this new assignment measure distances between 0 and 18 inches. Figure out a cool way to convey that distance to the user. Think of a good idea. If you are having trouble coming up with an idea, maybe build a bar graph with 10 LED’s, and the number of lit LED’s indicating distance. In any event, you will need to do your math on the project, and an important part of the grade is showing me your graph where you map your output values onto your input values, like I did above.

LESSON 17: Measuring the Speed of Sound with Arduino and Ultrasonic Sensor

Now that we know the basics of Arduino from the first 15 lessons,  we can begin to focus on more and more cool projects.

Simple Circuit for measuring the speed of sound

I think you will be surprised to see how many sophisticated things you can do with the simple arduino skills you have already learned. In this project, we are going to measure the speed of sound using the arduino and an ultrasonic sensor. We will use the Virtuabotix ultrasonic sensor which you can get HERE for about nine bucks. This sensor measures the time it takes an ultrasonic ping to go out,  bounce off a target, and come back. The time it takes for the ping to leave and come back to the sensor depends on the speed of sound and the distance to the target. This sensor works in the same way a bat uses high pitched tones to navigate in the dark. It is also the same principle used in submarine sonar. The Arduino circuit for this project is very simple, and shown in the following schematic:

Simple Circuit for Measuring Speed of Sound

This sensor is fairly easy to use. To hook it up, we take the sensor VCC pin and hook it to the arduino 5V pin. We take the sensor GND and connect to Arduino GND. The Trig pin on the sensor we take to pin 13 on the arduino and the Echo pin on the sensor we connect to the arduino pin 11.

The sensor works as follows.  You take the trigger pin LOW with a digital write. You then pause, take the trigger pin HIGH, pause, and then take the trigger pen LOW again.  This LOW-HIGH-LOW sequence creates a high pitched ultrasonic tone, or ping, which is sent out from the sensor. This ping will go out and bounce off the first thing in front of it, and bounce back to the sensor. The sensor will output a HIGH pulse on its echo pin, and the length of the pulse in microseconds indicates the time it took the ping to travel to the target and return. We can measure the length of this pulse using the pulseIn command we learned in lesson 15.

Once you make the pulseIn measurement, and know the time it took for the ping to travel to the target and return, you can use that to calculate the speed of sound. Since

distance = rate * time.

Distance is the distance traveled by the ping, time is how long it took the ping to travel to the target and return. With this we can rearrange the equation to solve for rate, which would be the speed of sound:

rate = time/distance

Since pulse in returns the ping travel time in microseconds, and if you measure the distance to the target in inches, the units on the rate will be in inches per microsecond. We would need to use dimensional analysis to convert this to miles per hour as follows:

(rate in inches/mircrosecond)*(1000000 microsecond/second)*

(3600 seconds/hour)*(1 mile/63360 inches)

This will then give rate in miles per hour, as you can see as the units cancel out. The video explains this in more detail.

Key thing to remember in doing this calculation is that the ping has to travel to the target and then return. If the target is 6 inches from the sensor, how far did the ping travel? It traveled 12 inches. Six to get to the target and six to return from the target.

Try and put it all together into a program that will measure the speed of sound. I have included the code below. Try and write the program yourself, but if you get stuck you can look at the code below. It is important not to copy and paste this code, but only use it as a guide. You need to type your programs in yourself.

Check this out and see how close it is to published values for the speed of sound. Pretty Cool!