Tag Archives: Tutorial

Python with Arduino LESSON 5: Finishing our Virtual Reality Example

This Lesson finishes the work that was begun in Python with Arduino LESSON 4. In that lesson we built the circuit and programmed the arduino to measure the distance to a target and the color of the target. The program then output that data to the serial port. In today’s lesson we will use python to read that data stream, and use the data to dynamically update a virtual world we create.

You will need to start with the work in LESSON 4 to get your circuit working, and your arduino programmed up. Once you have done that, you are ready to use Python to program up your virtual world. Remember you will need to have the pyserial and the vPython libraries loaded. We showed how to install the software in Python with Arduino LESSON 2.

In the video we will go through the process step-by-step to create a virtual world. The code we end up with is posted below. You should not copy and paste the code, but just glance at it if you get stuck. In the end, you should develop your own virtual world and just use mine as a guide if you need more help.

 The video explains each line of the code.  Play around and tweak the values and see the effect on your virtual scene. Now your assignment is to take what you have learned here, and continue to expand your virtual world. Add objects to your virtual scene. Perhaps build an object for the breadboard, color sensor and arduino. I will give you several days to do this, and then when I come around for a project grade, I will want to see who has built the most impressive virtual scene. You should go well beyond the simple demonstration I have done here.

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:

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.

Python with Arduino LESSON 2: Installing the Software

There are some really incredible things we can do when we get our little Arduino to talk to the big bad Python programming language. To do that, we have to start by downloading some software. Never fear . . . it is all free and I will take you step by step through the installation. The video above shows you how to do it. If you are the impatient and technically adept type, you can download these three software packages:

1) Download and Install Python 2.7.8. Please note all my tutorials use this flavor of python. If you want to follow my tutorials, do not download a Python 3.x. Also download 32 bit version of the software, even if you have a 64 bit windows machine.

2) Download and Install Pyserial version 2.7. Again, download the 32 bit version of the software.

3) Download and install the Vpython library for 32 bit windows.

Now, lets get python and arduino talking together. First up, we need a simple program to get the Arduino sending data over the serial port. The following program is a simple program that will have the Arduino count and send the data to the serial port.

Now, open the VIDLE environment which you downloaded with the Vpython library. Once you have done that, you are ready to write a Python Program that will go out and read the data over the serial port. Full explanation is in the video. Do note, however, that the line:

This is for a windows machine. Also, the ‘com11’ has to be adjusted and set to whatever com port your arduino is talking on. You can figure that out by looking at Tools – Port on the Arduino. Set this parameter to whatever port your Arduino is talking on. Then, the baud rate needs to match as well. You can use whatever you want by Arduino and Python need to be on the same baud rate, which you set on this line of code. OK, the complete Python code to read the Arduino data from the serial port is here:

Simple as that! Welcome to the world of having the Power of Python now at your fingertips.

LESSON 19: Arduino LCD Display

In this lesson we are going to learn to use an LCD display. This really allows us to take our Arduino projects to that next level! We will first get the LCD hooked up and show we can display a simple welcome message. Then we will use it to display the distance measurement being made from the ultrasonic sensor. So, do not take your project apart from LESSON 18.

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

This table shows you how to connect your Sparkfun Inventor Kit LCD to your arduino. (If you do not have the kit, and want an LCD like the one in this tutorial you can order it HERE.) When oriented like the photograph above, pin one is the pin in the upper left corner, and they are numbered sequentially from left to right. The table below shows the connections needed to allow the arduino to work with this LCD using the code we will write in this lesson. The pinout of other LCD might be different, but if you connect the LCD named pins in column 2 to the Arduino pins in column 3 in the table below, you should be able to get many of the 16X2 LCD’s to work.

Connections for Sparkfun Inventor Kit LCD
(for others column 1 might be different)
LCD Pin #LCD PIN NAMEArduino Pin
1VSSGND
2VDD5V
3V0Pot Center Pin
4RS10
5RWGND
6E9
7DB0NOT CONNECTED
8DB1NOT CONNECTED
9DB2NOT CONNECTED
10DB3NOT CONNECTED
11DB4Pin 5
12DB5Pin 4
13DB6Pin 3
14DB7Pin 2
15Backlight LED +V5V
16Backlight LED GNDGND

For this project, you can use the table above to connect your LCD to the Arduino.  The diagram below is a graphical representation of the connections for LCD like mine.

 

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

These LCD are tricky to hook up because there are so many wires. You have to be very careful,  and you have to make sure your LCD is oriented properly. Check the spec sheet that comes with you LCD carefully to verify connections are correct.

Once the LCD is wired up, it is fairly straightforward to use.

 At the top of your code, you will want to make sure that you load the LCD library. This is a standard library that comes with your arduino software.  You load the library by putting the following code at the top of your program:

Also at the top of the code, you want to create you LCD object, which also tells Arduino how you are connected to it:

The numbers tell Arduino that we have RS hooked to pin 10, E hooked to pin 9, DB4-DB7 connected to Arduino pins 5-2, as shown in the table above.

In the void setup, you will want to tell the Arduino that your LCD has 16 columns and 2 rows.  You should put this code in your void setup, since you only need to do it one time:

You are now just about ready to start sending messages to the LCD. You need to start by telling the Arduino where on the LCD to begin the message. Remember that it always wants column first, then row, and that it starts with ‘0’. Therefore, the upper left character would be column 0, row 0, or (0,0). To set the cursor to the upper left corner, you would send command:

So now lets make a simple Counter. We will count off seconds. We start by printing “My Timer” on the first row. We do that with the command:

Now we would go to the second row and print a counter. Lets bring all the code together in the following working program.

Run this program. If you have your LCD hooked up correctly, you should see the counter working. If it is not showing, you probably have miswired the circuit. Go back and check your circuit carefully. You also might need to play with the setting on the potentiometer to get the contrast set correctly.

Now, watch the counter count up and down carefully. You should notice something peculiar as the counter counts backwards. What do you see that is not good? What you should see is that as you count down from 10 to 9, you end up with an extra ‘s’ on the word ‘Seconds’. You end up with ‘Secondss’. This is a vexing problem which occurs just about every time you try and use an LCD. The reason is that when you go from 10 to 9,  printing the number goes from needing two digits to one digit. Then, when you print ‘Seconds’ it is shifted to the left by one character, and you are still left with the last ‘s’ from the previous time you printed ‘Seconds’. Hence you are left with a mess.

There are two ways to clear this up. One way would be to specifically set the cursor to a correct position before printing ‘Seconds’. This would put it in the same place every time, and alleviate the problem. The other possibility is to print a blank line each time through the loop to clear the second line of the LCD. This is something you need to play around with and understand, because it seems to come up every time I try and use an LCD. Look at this code, and try it, and make sure you understand why it fixes the problem.

OK, your assignment is to play around with the LCD and become comfortable with it. Show me that you can make it do some new and interesting things. Write a program of your choosing that uses the LCD as a display. You might consider making it the display for one of the projects you did in one of our earlier lessons.

 

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
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.

Ardunio-distance-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.

Servo Math
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.