Tag Archives: Lessons

Arduino Lesson 6: Reading From the Serial Port

So far in our programming we have set the variables inside of the program, usually up at the top. In order to change the number of times the LED’s blink, we would change the lines of code that set those variables. This is OK for playing around, but you can see that if you want other people to use your programs you can not have them playing around with your code. You need to be able to get input from the user without modifying the code. We can do that using the Serial Port. Just like we can print information to the user using the Serial Port, we can also get information from the user using the serial port.

In these exercises we will continue to use the circuit created in Arduino Lesson 3. If you need help in putting the circuit together, go back and review that lesson. Here is a diagram of the circuit we are working with.

LED Schematic
This circuit will allow you to independently control two Light Emitting Diodes from the arduino microcontroller

Also, as a reminder, here is the code we have been working with that incorporates all the things we have learned so far. I am including this code so you can look at it if you get stuck, and to serve as an example for the work you do. To learn programming though, you need to be typing in your own code, making mistakes, and then finding an correcting your mistakes. You will not learn programming if you simply go through these lessons copying and pasting my code.

OK, look over this code and review what we have learned so far. At the top of the program we declare our variables, and we assign values to them. So far we have worked with variables of type int and type String.  Then in the void loop we start our serial port, and we set our two arduino pins to OUTPUT.  In the void loop we have built two for loops .  .  . one to blink the red LED and then one to blink the yellow LED. The parameters used in the for loop like how many times to blink and how long each blink should be are all defined at the top of the program.

As we mentioned at the beginning, it is OK to start out doing things this way, but at some point you need to be getting your parameter values from the user, and not hard coding them into the program. You would like the program to ask the user how many times he would like to blink the red LED, and then ask how many times he would like to blink the yellow LED. This is really pretty easy to do, and we do it over the serial port, very similar to how we learned to print in lesson 5.

In order to get input from the user, you need to make sure that you have turned your serial port on in your void setup. You do that with a Serial.begin(9600); command, as seen in the code above. You always need to have this command in your void setup() if you are going to print to the serial port or read from it. Now, in order to get input from the user, you need to do three things:

    • Prompt the User for the Input
    • Wait for the User to Enter the Input
    • Read the information from the serial port

In the program above,  lets say that in our void loop each time through the loop we want to prompt the user for how many times he wants the red LED to blink and then after that prompt him for how many times he wants the yellow LED to blink. In this scenario, we are now getting the parameters from the user instead of hard wiring them into the program. In this case, we still have to declare our varialbes, but we do not need to assign values to them. Hence in the example above the code:

Should be taken out and replaced with:

You see, now we are only declaring our variables. We are not assigning values to them, because we will be getting the values from the user. It is important, however, that any variables that we will use still need to be declared.

Now in our void loop() this would be the code to get from the user the number of times he would like to blink the LED.

There is a lot going on in these few lines of code, and lots of new things for you to learn, so lets unpack it pretty carefully. The first line should be familiar to you. You are just printing to the serial monitor a message to the user that you are waiting for input. In this case he will see a message asking him to put in a number. Now, we have to remember that the computer can work much faster than a person, so when a computer asks a person to do something, it is important for the computer to sit and wait for the person to complete it. This is done in the second and third lines of code above. This is an example of a while loop. You can see the while loop has a clause associated with it that starts and ends with the curly brackets. The program will continue to execute what is between these curly brackets as long as the condition that is in the parenthesis is true. So a while loop is sort of like a for loop, except the while loop can continue to loop forever as long as the condition in the parenthesis is true. So, we need to understand the ‘condition’ part of the code above, which is Serial.available()==0.  This is not as confusing as it looks. Serial.available() is a function that when you call it, it returns a ‘1’ if the user has input data, and a ‘0’ if the user has not input data. So, if the user has not input data, Seraial.available() will be 0, the condition will be true, and the program will stay in the while loop.

So the bottom line is that

 will sit and loop forever waiting for the user to input the data. When the user inputs the data, it will them move on to the next lines of code. Notice that we do not do anything in the while loop because there are no commands between the two curly brackets. The purpose of this line of code is simply to get the program to stay at that point until the user inputs his data.

Now at the point the user does input the data, Serial.avaialbe() will become ‘1’, and the program moves to the next line of code. The next line of code,

is the line that actually reads the data. Serial.parseInt() reads the number the user input, and then that number is assigned to the variable numRedBlinks. When you are reading an integer from the serial port, you use Serial.parseInt(). There are different commands for reading other variable types. You can imagine that if you were reading a floating number, you would user Serial.parseFloat(). To read a string you would user Serial.readString(). The important point is that you need to use the correctly precise command for the type of data you are trying to read.

OK, so put that code into your program at the start of the void loop() and also make a similar sequence of code to get from the user the numYellowBlinks. After you have that working also get other parameters from the user like the various blink time variables. You should play around with this and get comfortable getting input from the user. When you run the code, remember to click the icon in the upper right of the arduino IDE to get the serial monitor to pop up. You should see the prompt in the Serial Monitor, and you should enter your number in the small box, and then click send, or press the enter key.

Arduino Lesson 5: Working With Strings

In this lesson we will learn more about working with stings. A string is literally a string or sequence of characters. The word “Hello” is a string of characters. Stings allow your computer program to interact with the world in a way that the world understands, so it is important for us to learn a little more about strings.

In this lesson we will be using the same circuit we developed in Arduino Lesson 3.  If you need help setting the circuit up, please visit lesson 3. Hopefully you still have the circuit set up, as we have used it for the last two lessons. The circuit schematic and code we have been working with is presented below.

LED Schematic
This circuit will allow you to independently control two Light Emitting Diodes from the arduino microcontroller

This is the code that will run this circuit.

In the code above, notice that we are using stings in some of our print statements. For example the line of code above the for loop for blinking the red LED reads as:

The text in quotes is your string, and in this case is “The Red LED is Blinking”.  As you can see a string is just a string of characters. We can use strings to present meaningful words and thoughts to the user.  We are not limited to just using strings as we have above,  but we can actually create variables to hold strings. For example, in the code above one of the strings we print for the user to see is “The Red LED is Blinking”. It would be possible for us to create a variable called redMessage, and set redMessage to “The Red LED is Blinking”. In order to do this, we would need to declare the variable redMessage a string. We can do that up at the top of the program before the void setup, which would make it a global variable. The code would look like this:

With this code we declare two new variables of type String. In addition to declaring the variables we initialize them to their respective values. By doing this we can modify our print statements in the original code to print the Strings by printing the variables we have assigned them to.

can be replaced with

Notice when we print the variable, we do not use quotes around it. When we say to print redMessage, it will print the string that was assigned to redMessage.

By assigning strings to variables instead of using them directly it makes it much easier to modify and use your code. Try and get in the habit of assigning strings to variables.

When we have string variables, it is possible to concatenate, or combine stings together.

For example, lets say we declare and initialize two variables:

It is a good practice to try to assign strings to variables and then use the variables.

Arduino LESSON 4: Printing Over the Serial Port

In Lesson 3 you learned about for loops, and how for loops can make your life as a programmer much simpler.  You wrote a program that would blink a red LED and then a yellow LED the number of times indicated by the program. In this lesson, we will be using the same 2-LED circuit. If you don’s already have it put together, you should go ahead and do it now. This is a schematic of the circuit:

LED Schematic
This circuit will allow you to independently control two Light Emitting Diodes from the arduino microcontroller

In order to independently blink the two LED’s you were probably using code similar to this:

As you learned in Lesson 3 for loops make your program much simpler to write and much simpler to modify. In the code above, to change how many times the LED’s blink, you just have to simply change two lines of code:

By changing either of these variables at the top of your program, you effectively adjust how many times each LED will blink in each cycle.

Now besides just blinking the LED, it would be nice to provide some information directly to the user. It would be nice to be able to have the arduino ‘print’ information to your computer screen. You can do this by working with the Serial Port and the Serial Monitor.

In order to use the Serial Port, the first thing you have to do is turn it on inside your program. Since this is something you would only need to do once, you do it in the void setup(). The code below, when placed inside the void setup() will turn your serial port on:

You will want to keep whatever else you already have going on in your void setup(), and just add the line of code above to it. Note that this line of code tells the arduino to turn the serial port on. The ‘9600’ tells the arduino to communicate at 9600 baud, which basically is just the speed you will be working at. The higher the number the faster data will be sent and received over the serial port. This can be set to different numbers, but the important thing is that everyone is talking and listening at the same speed. So, if you tell the arduino to run at 9600 baud, when you open your serial monitor later, you need to make sure it is set to the same speed.

OK, now that you have started your serial monitor you can start sending and receiving data over it. The first and easiest thing is to send data to it. We do this using Serial.print and Serial.println commands. These commands send data to the arduino serial monitor. We will show you how to open the serial monitor in a minute, but for now, lets add some print statements to our program.

Notice that the loop above is our loop for blinking the red LED. We have added a new line to the start of the loop . . . Serial.println(j). After you add the line of code, download the code to the arduino, and then pop open your serial monitor. You do this by clicking on the magnifier icon at the upper right corner of the arduino IDE.

Arduino Serial Monitor
Click on Magnifier to Open the Arduino Serial Monitor

When you click on the icon you should see the serial monitor pop open, and you should see the values of j being printed out. It should look like this:

Arduino Serial Monitor
Serial Monitor shows what you are printing

You should see the numbers printing out as your program goes through the for loop. Make sure that you have the baud rate set in the lower right corner of the serial monitor to the same value you specified in the program. 9600 baud is usually a good choice.

In the example above, we are printing the variable j each time the program loops through the for loop for the red LED. We can also print out a string of text. To print out a string of text, you put the string in quotes.  To print a string you would do something like Serial.println(“Blinking Red LED”). It will print the words between the quotes. Lets add this to our code, but lets add it before the for loop, so it just prints it once each cycle. Your code for the red LED should look like this:

Now download and run the code and look at your serial monitor. You should see those words printing each time before the Red LED blinks. Now go ahead and add similar code to your Yellow LED loop so that it will announce which LED is blinking and then the blink counter. Your code should look like this for the two for loops:

 So this code will announce which LED is blinking, and will then give a count of which blink you are on. Pretty cool! Your Serial Monitor should now be looking something like this as it tells the user which LED is blinking and which blink you are on:

Arduino Serial Port
Serial Monitor shows what values the arduino is printing

So we can see that we can print both variables, like j, and strings. When printing strings, it is important to include the text in quotes, so that the arduino knows you are printing the string of text, and not a variable.

Notice that each time you use Serial.println it goes to the next line. If you want to print to the same line, without advancing to the next line, you should use the command Serial.print. In the example above, lets say instead of just printing the number j, you want text in front of the number that says ‘you are on blink number ‘ and then the number. You can modify your code and add another Serial.print command to the for loops. I will do it for you on the red loop, but you need to figure out the yellow for yourself:

You should get something that looks like this:

Arduino Serial Port Example
Nicely formatted Arduino Serial Monitor

Make sure to play around with blank spaces when you print strings so that your output is neat and readable.  Notice on mine that by using blank spaces I get an indent which makes the scrolling text more readable.

So, we need to carefully consider when it suitable to use Serial.print vs. when we should use Serial.println.

Arduino Lesson 3: For Loops for Simple LED Circuit

In this lesson we will create a circuit and write arduino code to control two LED’s.

Two Diode Circuit

You can jump right to the video, or read through the tutorial.

In the earlier lessons we wrote our first programs and built our first circuit. At this time you should be getting comfortable with how the breadboard works and how to work with variables and digitalWrite commands in the arduino IDE (Integrated Development Environment). Now we are going to build a slightly more complicated circuit for controlling two LEDs. Since we want to control each one individually, you will need to have a separate arduino pin control each LED and each LED should have its own current limiting resistor (330 ohms). You should be able to sketch out your own circuit at this point. This is a diagram of the circuit we will be using. Yours does not have to be exactly like this, but it should have the same function.

LED Schematic
This circuit will allow you to independently control two Light Emitting Diodes from the arduino microcontroller

Notice that in this circuit, the shorter leg of both LED’s needs to be connected to ground. In order to accomplish this we run a wire from the ground pin on the arduino to the top row of the breadboard. This makes the top row “ground”. Now any device that needs to be grounded can just be connected to the top row, since that row of the breadboard is connected all the way across (See LESSON 1). Also note that both LED’s have their own 330 ohm current limiting resistor, and remember that the direction matters on diodes . . . be sure to put them in with the longer leg connected to the more positive part of the circuit . . . in this case, the longer leg should be connected to the resistor (since the resistor connects to the + voltage coming from the arduino pin).

When you get the circuit built, it should look something like this:

Arduino LED Circuit
Photograph of our Arduino Circuit for Controlling Two Diodes.

Now that your circuit is built, we are ready to do some programming.

Our objective in this exercise is to be able to independently control the LED’s.  We will want to blink the red one ten times in a row, and then blink the yellow one once.  A “blink” should be turning LED on, leaving it on for a quarter second, turning it off, and leaving it off for a quarter second. Then that sequence will be repeated. So, we will need to think about the variables we will need. We have two LED’s so we will need to declare two variables to indicate the pins that the LED’s are connected to. In the schematic we connected the red LED to pin 9 and the yellow LED to pin 10. Also, since we will be blinking two LED’s, we will need onTime and offTime variables for each LED.  You should go ahead and open your arduino IDE and set declare your variables. Think about what you are going to name your variables . . . you do not have to use the same names I use. My code looks like this:

Now that your variables are declared, what should you do next? That’s right! You need to work on your void setup(). In your void setup you will need to set your pinModes. Since you are using 2 arduino pins this time, you need to issue two pinMode commads as follows.

Things are moving along and we are now ready to do our main business in the void loop(). Remember our goal is to blink the Red LED ten times, and then blink the yellow LED one time.

 OK, now you are ready to run your code. If you did it correctly,  it should run, and blink the red LED ten times, and then blink the yellow LED one time. If it does not run correctly, you need to debug your code. If it does not work, it is because you made a mistake. Most of the time it is silly typos or forgetting to end lines with a semicolon. Check your work, and you will find your error. Sometimes it helps to have someone else look it over with you.

OK, hopefully you have your code and circuit working now. You can play around with the parameters, and you can see that you can make the LED’s do whatever you want them to.

Now imagine I asked you to make the red LED blink 25 times and then the yellow blink ten times. The problem becomes that it gets very tedious to continue to copy and paste the code, and it eventually becomes impossible to keep track of how many times you have pasted the code in. We need a better way of doing repetitive tasks, like blinking. Luckily there is what is called a “for loop” a for loop will repeat a clause, or a group of commands, or lines of code a specified number of times. The for loop looks like this:

 OK, there is lots going on with this new code, so lets break it down. First,  notice the open and close curly brackets. All of the code or command lines you put between the curly brackets will be the code that is executed in the for loop. You can put as much or as little code as you want in the for loop. Now lets look at the first line that actually initiates the for loop. Inside the parenthesis are the parameters or arguments that define the behavior of the loop. Notice first that we have introduced a new variable, j. Since we do not need this variable in other parts of the program, we make it a “local” variable. That is, we do not declare it at the top of the program, but declare it just when we use it. That is why we have “int j=1”. The int is declaring that we are going to use a new variable called j. Now j=1 is telling the loop to start with a value of j of 1. Then the j<=10 says to continue to loop as long as j is less than or equal to 10. Then after the next semicolon we have j=j+1. This tells the arduino that each time through the loop, increment j by 1. So, inside the parenthesis we are telling the arduino to start looping with j set equal to one, to continue to loop as long as j is less than or equal to 10,  and each time through the loop to add 1 to the value of j.

So, if we want to blink the red LED ten times, it becomes very easy using the following code:

Remember that our goal was to blink the red LED ten times and blink the yelow LED one time.  We need to add a little code so that the LED will blink yellow. This should be done AFTER the for loop.

 WOW, that is a huge improvement over our original code. The for loop makes it much easier to manage things. The one thing that I don’t like about what we did in the code above is that we looped to the constant value of ten. It would be better and smarter to declare a new variable at the top of the program, The new variable could be numRedBlinks. Then in the for loop we would loop until j<=numRedBlinks. Then at the top of the program we could set numRedBlinks to however many times we want the red led to blink.

OK, I have done lots of the work for you in the above example. Now, I want you to write a program where the yellow LED is also controlled inside a for loop. So, you would declare at the top of the program two new variables . . . numRedBlink and numYellowBlink. The program would have a for loop to blink the red LED numRedBlink times, and then blink the yellow LED numYellowBlink times.  Good Luck!

RESOURCES USED IN THIS LESSON:

Arduino Microcontroller: You can get a good deal on the arduino on Amazon. Arduinos are open source and many are cheap chinese knockoffs, so you want to make sure you get an “official” version, which you can at the link above.

Sparkfun Inventor’s Kit: While the bare arduino will get you started, I really suggest getting the Sparkfun Inventor Kit. The projects I will feature in this tutorial set will use the components in this kit, and it is probably cheaper to go ahead and get the kit than to buy the individual components as you go along. The kit is under $100 on Amazon.

Arduino Lesson 2: Using a Breadboard

Breadboard
Breadboard for prototyping your Arduino Circuits

In this lesson we will begin to build our first circuits that will be controlled by the Arduino. We will start out with simple circuits and build from there. It is important for you to learn the basics before moving on, and one of the most important basics is how to use a Breadboard.  In this lesson we will learn the ins and outs of breadboards, and by the end of the lesson you will have your first circuit built, and it will be controlled by the arduino.  Watch the video below for in depth description of how the breadboard works.

In order to build a circuit, you have to connect circuit elements together. You could run a bunch of wires to connect components, but you find that very quickly you end up with a rats nest of wires, and it becomes impossible to debug. In order to keep your circuit organized you need to use a breadboard, pictured above. The breadboard allows you to connect components together by plugging them into the little holes. The key is to understand how the holes are connected. As you can see in the diagram, the holes in a column (when oriented as shown in the picture) are connected together.  So to connect components together you need to plug the leads you want connected into the same column. Note that the columns are not connected across the “trench” in the center of the board. Also notice that as the long rows at the top and bottom are connected together. These are typically used to create “rails”.  These are typically used for grounds and supply voltages you might need to connect many components to. Notice some rows are marked (+) and some(-). These are just markings. The row will be set at whatever voltage YOU connect to it.

LED Circuit
Simple LED Circuit for blinking an LED

So, lets look at a real example. In this circuit we have a voltage supply connected to an LED through a resistor. We will need to take this circuit schematic and figure out how to connect it up in the real world. As mentioned above this should be done using a breadboard. You can see that you need to connect the voltage supply to one leg of the resistor. The other leg of the resistor is connected to the LED. Note that the LED is directional, meaning it has to be connected in a certain orientation. You must connect the Cathode to the positive voltage. The Cathode is typically the longer of the two leads on the LED. If you put the LED in upside down, it will not light up. The other leg of the LED needs to be connected to the negative terminal of the voltage supply. For this project we will supply the voltage from the Arduino microcontroller. That way, we can turn the LED on and off from our program.

Look at the diagram at the top of this post to see how the holes are connected in the breadboard, and figure out a way you could connect the circuit up using the PC board. There are many ways to hook it up, but one that will work is shown here.

Arduino LED Circuit
This shows how you can hook an LED to the arduino through a current limiting resistor

When you hook your circuit up in real life, it should look something like this:

LED Arduino Circuit
Photograph of the circuit. Your LED will not come on until you write your program

Remember that it is the long leg of the LED that is connected to the resistor and the short leg to the black wire going to ground.

Now, if you follow along and develop the code as outlined in the video you should be able to do amazing things with the LED.

RESOURCES: On all these lessons I will include resources on where you can purchase the items mentioned in the lecture.

Arduino Microcontroller: You can get a good deal on the arduino on Amazon. Arduinos are open source and many are cheap chinese knockoffs, so you want to make sure you get an “official” version, which you can at the link above.

Arduino Beginner’s Kit: While the bare arduino will get you started, I really suggest getting the complete Beginner’s Kit. The projects I will feature in this tutorial set will use the components in this kit, and it is probably cheaper to go ahead and get the kit than to buy the individual components as you go along. The kit is under $100 on Amazon.