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!

LESSON 16: Controlling a Servo with Arduino

Its time to get moving! In this project we show you how to get things moving with Arduino. You will need an arduino, a servo, a potentiometer and some wires. If you have the sparkfun inventor kit, it has everything you need (You can pick up the inventor kit HERE).

Circuit for controlling a Servo from the Arduino using a Potentiometer

For this project, our objective is to control the position of a servo based on the setting of a potentiometer. The servo should “track” the position of the potentiometer. In order to do this, we will need to start with our Voltage Divider Potentiometer circuit from LESSON 10. In addition, we will need to hook the servo up. for the servo in the sparkfun kit, it has three wires . . . red, white, and black. The red line is for power, so it should be hooked up to 5V from the arduino. The black line is ground, and should be hooked up to ground on the arduino. The white line is the control line, and it should be hooked up to one of the arduino pins with a squiggly line.  For this example, I am using pin 9. The small servo that comes with the sparkfun kit can be powered directly from the arduino. Understand that many servos draw lots of power, and require a separate power supply, and just the control line connects to the arduino. Realize that you must be careful and not hook a larger servo to the arduino for power, as that can damage your arduino. The one in the sparkfun kit can be driven by the arduino without a problem.  Also, some servos have a different color code on the wires. Many have red/orange/brown wires. For many of these types, the red is for power, the orange is for the control line, and the brown is for ground. Be sure to check the instructions on your servo to verify the color code.  As a reminder, this is circuit diagram for the potentiometer, which you will be using in this project.

This simple circuit allows you to create a voltage divider with a potentiometer, which we will use to set position of the Servo.

Most servos are designed to be operational in a range from 0 degrees to 180 degrees. The truth is though, that most will not operate over that full range. Also, you need to know that overdriving the servo beyond the range it wants to be in can damage both your arduino and your servo. Each servo is different, and sometimes two servos with same model number from the same manufacturer will have different ranges. Especially in the cheap ones (like in the sparkfun kit) have very different ranges.

So before going to far in any project you need to determine the range that your particular servo will operate in. In order to do this we need to write a simple program that will move the servo. In order to control the servo from the arduino, there are several things that must be done. The first is that you must “load” a library. A library is a special set of code written by the folks who make or sell the device in order to make it easier for you to work with. Libraries allow us to work with components in a more intuitive way. For the servo, you need to load the servo library, which comes with the arduino software you originally downloaded. To load the library, you need the following code at the top of your program:

Then, you need to create a servo “object”. This object will then be something you interact with to make the servo move. You can all the object anything you want, but I think I will call mine “myPointer” since I am going to make my servo point at things. The code to create the servo object would then look like this:

OK, now to make the servo go to a certain position, I would just have to issue a command like this:

This command goes to ‘pos’ which should nominally be between 0 and 180.  But remember that most servos will not go over that full range, so we will need to play around to see what range our servo can safely achieve. Also, the short 15 millisecond delay after moving the servo gives it time to get there and settle down. Never try and write the servo faster than it can naturally move.

The one other thing you need to do is let the arduino know which pin the servo is connected to for the control line. We are using pin 9, and will set up a variable at the top of the code to set servoPin=9, but it can be any pin that can analogWrite (one with a squiggly line).  To tell your arduino where the servo is connected, for the case of my servo which I names myPointer, the following code should be put in the void setup:

What you need to do now is write a program that will input the user for a position, and then write that position to the servo. The purpose of this is to determine the natural range of your particular servo. You should write this program yourself, but if you get stuck you can look at my code below. You should use this as a help if you need it, but your should not cut and paste it. Write your own code!

OK, with this code we should see the arduino prompt the user to a position and then write that position to the servo. The thing to do with this code is play around and figure out what range of motion your arduino can achieve. If you arduino sits and twitches, you have probably overdriven it. Keep playing with the numbers until you determine the range your servo can sweep to without jittering.

Once you know that range, you can play around with the code and the servo. Create a program that will smoothly sweep the servo through its range of motion. For my servo, I created the following code. Again, play with it yourself, and use this code only if you get stuck. Also, realize that my servo operates from 15 to 170 degrees, so that is why I used those numbers. You need to determine the range of motion for your servo, and use those numbers in the program.

 Now we need to write a program that will set the position based on the position of the potentiometer. We want the servo to point to the left if the potentiometer is positioned all the way to the left. Similarly we want the servo to point to the right if the potentiometer is all the way to the right. We need to do the math carefully to make sure that we do not try and overdrive the servo.  You must assume the user has no knowledge of servos and will turn the potentiometer to any position. In order to make sure the servo is not over-driven, you must carefully do the math. For this case, what is the independent variable? It is the number coming off the potentiometer. That is what you or the user “sets”, that is the independent variable, that is the horizontal axis. Now, what is the dependent variable? That is the pos (position) number. That is what you want to calculate from the independent variable. To do the math, think about the two points you know. You know that the potentiometer reads from 0 to 1023. You know that for my servo (yours will be different) the range of useful motion is from 15 to 170. So, when the potentiometer is set to 0 we want the position to be 15. There, you have one point, the point (0,15). Now we also know that when the potentiometer reads 1023, we want to position the servo at 170. So, now we have another point, the point (1023, 170). Now we have two points and can create the equation that will allow us to calculate the Pos based on the reading from the potentiometer. You should be able to do this by yourself now, but if you get stuck you can look at my notes. Remember, you need to do it for your values of useful range on the servo, not my numbers of 15 and 170.

This shows the math to on how to calculate servo position based on potentiometer reading

So with this equation you can now calculate a pos for the servo based on the reading from the potentiometer. You should be able to write the code now to control the servo position from the potentiometer. If you get stuck watch the video that provides step-by-step directions on the code.

LESSON 15: Super Cool Arduino Color Sensor Project

This first video shows just the results of this extremely exciting project!  Watch the first video if you want a quick summary showing the working project.

The second video, below shows an in depth step-by-step tutorial on how to make the project work.

OK, in the first 14 lessons we were laying the ground work for circuits and programming. Now it is time we had a little fun. This project will show you how to do an insanely cool circuit based on what you have learned already. This time we are going to use the RGB LED circuit you worked on in Lesson 13 and Lesson 14,  but this time you will set the color based on the color seen by a color sensor! That is right, we will incorporate a color sensor into the circuit. If the color sensor sees red, the LED will turn red. If it sees blue, the LED will turn blue. Our challenge in this project is to make the sensor match as many colors as well as possible.

We will use an arduino color sensor to set the color of the RGB LED

There are a couple of things you will need for this project in addition to the arduino, breadboard, and RGB LED we have been using so far. The good news is the components are very affordable and can be easily ordered from amazon. First up you will need the Virtuobotix Color Sensor which you can order HERE. To connect the color sensor to your arduino you will need some male/female connecting wires, which you can order HERE.  You probably have the rest of the things you need, but I will give a complete list at the end of this lesson.

For the LED side of things you will want to use the same circuit from Lesson 13 and Lesson 14.  As a refresher, here is the schematic;

Circuit used to control RGB LED from an arduino

Now for this project, instead of getting the desired color from the user via the serial port, we will set the LED color by having it match colored cards we place in front of the sensor. So, we will need to figure out how to operate the sensor. It is really pretty straighforward. First up, we have to hook it to the arduino. That is probably easiest done by following this table, rather than me trying to draw a picture:

Connecting the Color Sensor to the Arduino

Color Sensor Pin
Arduino Pin
S0 GND
S1 5V
S2 pin 7
S3 pin 8
OUT pin 4
VCC 5V
GND GND

Hopefully that is clear. Remember, you must use the male/female wires described above to connect the Color Sensor to the Arduino. Unfortunately, the sensor is too big to connect to a standard size breadboard. Use the table above to carefully make the connections, but after you are done your circuit should look like this:

Color Sensor and RGB LED connected to the Arduino

There are lots of wires, so double check your work against the table above.

Now,  this is the way the senor works. It will make three different readings indicating the relative “strength” of the three primary colors  . . . Red, Green and Blue.  Never fear, if you know the strength of the primary colors, you can figure out any color as they will just be different “mixes” of red,  green and blue.

Which color is read depends on the voltages you write to the S2 and S3 pins, according to this table:

S2
S3
Color Read
LOW LOW Red
LOW HIGH Blue
HIGH HIGH Green

To actually make a measurement, you need to select which color strength you want to read by doing digital writes to pins S2 and S3 according to the pins above. Then you read the color strength on the sensor OUT pin, which we have connected to Arduino pin 4. To make the measurement, you need to make a pulseIn measurement at pin 4 on the arduino. The pulseIn measurement is an arduino command that looks at the pin you specify, and looks for a pulse, and returns to you a number representing the length in microseconds of the pulse seen at the pin specified. For example, lets say we already declared a variable pulseWidth to hold the measured value. The following code would allow us to measure the pulseWidth at the outPin (make sure you have declared both variables, and you should set the pinMode of outPin to be an INPUT,  since you are reading from it;

 This measurement will return a value between 0 an 102,400. Because of this, you need to be sure to declare pulseWidth variable an unsigned int. Normal integers can only hold numbers up to +/- 32,768 an unsigned int allows only positive numbers but allows numbers up to 4,294,967,295. 

The number that is returned which we put in the variable pulseWidth above can be interpreted as such: The lower the number, the stronger the color being read. The larger the number, the weaker the color.

We need to somehow convert this rather odd number into something that means something in the real world. Well, when we write values to an RGB LED we want them to be between 0 and 255.  Also, that is a fairly standard scale to report RGB colors . . . by giving the relative strength of the compoents of R, G, and B on a scale from 0 to 255. First we need to convert 0 to 102,400 to this range.  102,400/400 = 256. Almost exactly what we want! But we need to subtract one. So, we could say that rColorStrength = (pulseWidth/400) – 1. That gets us a number between 0 and 255. Only problem is, remember that in the original pulseWidth, big numbers mean weak colors and small numbers mean strong colors, so we need to fix that. We could fix it by now saying:

rColorStrength = (255 – rColorStrength);

That simply adjusts things so that big numbers now mean strong colors. Also, you can see this example would be for reading red. You would need to repeat by setting S2 and S3 to also create gColorStrenght and bColorStrength for green and blue.

So, with this little bit of math we should have what we need to actually read R, G, and B values that fairly accurately represent the color the sensor is seeing. In the video I go through the code. I am not posting the code on this one because you need to think through it and if you get stuck, the video shows you each step.

LESSON 14: If Statements and Conditionals in Arduino

In our LED project in Lesson 13, we controlled the color of the LED by changing lines of code in the program. As you know, you really want to do that sort of thing by interacting with the user over the serial port. So, in this project, we are going to have the user set the color by indicating his preferred color in the serial monitor. Notice in our new picture below we have covered the LED with a ping pong ball. We did this so the LED will show better in the video, but after doing it, I really like it! It makes a cool little lamp. You can do this by creating a small hole the size of the LED in the ping pong ball, and then just mounting the ball on the LED. Cool stuff!

We have added a ping pong ball to the top of our RGB LED.

This project uses the same circuit we set up in Project 13. We will just be changing the code.

Circuit used to control RGB LED from an arduino

So, for this project, we will want the user to input his desired color for the LED. Then we will make the LED change to the color he requested. In order to do this, we need to learn a new programming command called the if statement. The if statement has a clause, or group of commands between a set of curly brackets. It executes those commands only if a condition is met. An if statement in arduino would look like this:

 

The commands between the curly brackets will be executed if the condition inside the parenthesis is true. Lets consider you had two variables, a and b. Lets say you only wanted to execute the commands in the clause if a is > or = to b. In that case you would put that condition in the parenthesis and your code would look like this:

The arduino would only execute the code if the condition was true. Otherwise it would jump to the first line of code after the closing curly bracket. There are a number of different condition tests that can be used in the parenthesis:

You can combine more than one condition by using the logical operators “and” or “or”. In arduino the symbol for “and” operation is && and the symbol for “or” operator is ||. (This is the symbol above the backslash on the keyboard). So you could have a condition where a is greater than b AND a is greater than c. This would look like:

 OK, so that is how if statements and conditional work. A key thing is that you have to remember than when you are testing for equality in an if statement, you use two equal signs. One of the common mistakes I see students make is to forget and just use one equal sign in a conditional.

What you will want to do now is write a program that will ask the user what color he would like the LED to be. In the prompt let him know that his choices are Red, Green, or Blue. Then turn the LED that color. You should also include a “test” . . . if he does not choose one of the allowed choices, he must choose again. Do your best to develop the code on your own, but if you get stuck, peak at my code below. You should not copy and paste my code, but just use it as a guide if you get stuck.

 OK, now your assignment is to move forward and have the program have more options for colors. Have it where you can turn the LED Red, Green, Blue, Cyan, Magenta, Yellow, Orange, Purple, Pink. Do some research on the internet to make sure you are really hitting these colors. Part of your grade will be how well you match the colors.

Making The World a Better Place One High Tech Project at a Time. Enjoy!

Exit mobile version