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:

Ultrasonic Sensor Circuit
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:

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.

38 thoughts on “Python with Ardiuno LESSON 3: Simple Virtual World Using Ultrasonic Sensor”

  1. I want to know how you place color sensor , mean its wiring diagram or just verbally inform me, what pin no to where on Ardiuno. ? i only want to use color sensor.

  2. has any one complained that your programs don’t run well on window 8? I tried lesson 3, arduino/Vpython, the square and distance works fine, but the yellow cylinder fly’s of the screen.
    Lesson 4, and 5, starts to run and locks up. Any suggestions??
    I really enjoy your web sight, it has taught me more about arduino than any tutorials I’ve study. One more question, when are you going to have more on the accelerometer?

    1. William,
      I have not tried the lessons on Windows 8. The issue is that there are so many versions of python, the various libraries, and then the computer operating system, I get it working on one set up and then move on.

      I made the videos last summer while I was off from school. It will probably be next summer before I do more videos.

  3. I have installed vpython several times as indicated in your video. While serial and arduino data capture works fine, ” from visual import *” does not work. There is error message ” pythonq.exe” has encountered a problem and needs to close down. Could you help me . I am running this on Dell laptop.

  4. I’ve just found this video series and I absolutely love you projects.

    I’d been trying to pair my Arduino boards with Python on my Mac Book Pro ( OS X 10.6.8) for months and could never get it to work. But after following your videos, I’m up and running with Arduino and Python!

    Thank you!

  5. Hi

    Your tutorial is fantastic! I am beginner in Python, so your website is very helpful for me.

    By the way, when I tried first sample code of LESSON 3, Python Shell shows the following Warning message.
    Warning (from warnings module):
    File “C:\Python27\Lib\site-packages\visual_common\”, line 70
    self.__setattr__(key, value)
    FutureWarning: comparison to None will result in an elementwise object comparison in the future.
    Do you know the meaning of this? (Can I fix the Warning?)

    Thank you very much in advance.
    Best regards.
    Hiroyoshi Suzuki.

  6. Hi. Great tutorial! Question: I made a similar program, with more sensors attached. It runs well, but after a while it starts to get slow and it ends up not responding. My baud rate is 115200 and the serial refreshment rate is about 10 hz. I played with the frame rate (less refreshment), but no difference was seen.
    Thanks you very much in advance.

    1. You might have to continue to play with the vPython “rate” and delays in the program. You need to tweak the settings to get it to run smoothly. Make sure you are not sending data faster than vPython can process it. Sometimes slowing things down will make it run better.

  7. hello ….
    I am student in computer engineering and need your help in Arduino Intel Galileo Board … because I used this code but not work ….
    if you can contact me at :

    thank you so much for your help.

  8. Hi Paul,

    Thumbs up for your tutorials of Arduino and Python as a combination, it happens to be my hobby projects for a temperature measurement and Your tutorials are a real help for me!
    I’m running Linuxmint 17 , and so far all is working fine!

    Keep up the good work!


  9. Hi and thanks for a fantastic video and a great tutorial!
    I got everything to work and, but I’m still wondering. How does the communication between the Arduino and the python works?
    We are not specifying anything both in the arduino code or the python code what to look after while working with the data from the arduino? Or since you are specifying serial.println(distance) in the arduino and then arduinoSerialData.readline() on the python-side, is the python script looking for the printing line? 🙂

  10. I am a physics teacher new to Python with arduino. Your tutorials are just so good to follow and learn from I just had to write a comment. thank you so much for them, I am loving working through them all and can’t wait to get some of this stuff in my lessons in Wales,UK. Thanks again.

  11. I found that setting the measuringRod .length to 0 (zero) seems to destroy the object. But this did work.
    distance = float(myData) + 0.0000001

    1. Excellent suggestion David. The rod disappeared on 2 out of 3 computers where I tried the code. After adding some length, it worked. Thanks a lot.

  12. Great tutorials. I do not have bandwidth on satelite network for the youtube tutorials but I’m getting enough from the text for most of it. In lesson 3 of python with arduino, I got the expected response in the python shell where it simply prints the value from the sensor, but in the other examples where “distance = float(myData)” is used, I get the following error:

    Traceback (most recent call last):
    File “/home/anne/Documents/python script lesson”, line 12, in
    distance = float(myData) #convert reading to a floating point number
    ValueError: could not convert string to float:

    I have no idea why. Copied and pasted code to both arduino and IDLE with no success.

    Any pointers would be great:-)

    1. Hello, I seem to be having the same problem that you were having.
      Did you by any chance figure out what was wrong?

      Thank you

    2. I had same problem I got rid of the text in the arduino code. Python is trying to read it as distance.

  13. Thanks for everything . I want to drive motors and make a robot. I need some help about this topic. How I menage the ports of the arduino in python code?

    Thank you so much.

    1. I do it for the sake of clarity . . . all of our if statements have had an operator . . . =, >, or <. So, I am using a technique familiar with my students who have had the earlier lessons. I did not want to introduce the new concept of "True" with no operator at this time.

  14. I have had success sending sensor data from the arduino to vpython, but when I converted myData to a float I keep getting and error that it cannot convert the string to a float. I’ve also has issues when I kill the program and suddenly all of the key words in the VIDLE change from their traditional color (orange, purple, etc) to black. I experience the same issue in IDLE when converting to a float. Does anyone have a solution for this issue?

  15. Hello Paul,

    First, let me say that I appreciate your videos and intend on becoming a student of them. (They stick out above MUCH of what is online.) Second, forgive me if this comment is somewhat misplaced. (feel free to follow up with my email, if you so choose.)

    I am wondering if you can give a suggestion for me. I am intending to build an image comparison device to determine when a conveyor belt is moving. (More accurately to alarm/alert when it stops moving.) My initial concern was image sensitivity not being able to distinguish an empty belt that is in fact moving. My thought to remedy this was to compare maybe 3 images at half-second intervals and if they do not show more than say 2% (some percentage) of ‘change’ to trigger the alert.

    In your opion, does this sound:
    1. feasible?
    2. practical?
    3. doable with an arduino?

    Assuming that I don’t want a shaft sensor, or anything making contact with the conveyor assembly, would you recommend another method.

    I am a newbie to the Arduino environment, but incredibly excited about learning and building for work and personal use.

    THANK YOU… and thank you again for your tutorials.

  16. Hi Sir,

    I’d like to ask, is that possible to control computer with hand gesture using Ultrasonic and Arduino?


  17. sir,
    i am connecting sensor but it is not showing anydata or any response everything(versions) is same as you used in

  18. hi !!

    i did everything like in the tutorial but the cylinder doesn’t move at all ????? i use python 2.7.9 and vpython 2.7.6 and dont know what i should change ???

  19. Hello.
    First of all, great tutorials. I absolutely love it.
    I am facing a little problem in importing ‘serial’ library in phython.
    The shell window shows an error saying “ImportError: No module named serial”/
    How do you rectify this error

Comments are closed.