Learn Programming and Electronics with Arduino

Learn Programming and Electronics with Arduino

By Programming Electronics AcademyTechnologyEducationCourses
Download on the App Store

Learn Programming and Electronics with Arduino episodes

  • Understanding the Arduino uber functions loop() and setup()
    Discussion:

    In this lesson, we're going to discuss two very special functions that you will use in every single Arduino sketch that you write. They're called Setup and Loop.

    Specifically, we'll cover:

    • How Setup Operates and the type of code that it executes
    • How Loop Operates and the type of code that it executes
    • Loop Function's Responsive Outputs
    • How to get those little ships inside the glass bottles

    I want you to pretend for a moment that you own a specialty Italian sub shop. Business is great, and you have wonderful customers.

    However, you have one major problem. Employee turnover is very high. This is mostly because the majority of your employees are teenagers who, by nature, tend to move on to different things.

    It feels like as soon as you get an employee trained, they move on to Harvard Business School or get a scholarship to MIT - or they just decide that bungee jumping all day long is better than making subs.

    In order to help train new employees, you create two binders of procedure lists. One binder is called "The Morning Setup Binder", and it lists all the stuff that you have to do when you open the store.

    This binder contains things like unlock the front and back doors, turn on the "Open" sign, put the delivered sausage in the fridge, and get the broccoli out of the fridge. It's stuff that only has to be done once.

    Once all of that stuff has been done, a new employee can take that binder and stick it on the shelf. Then, they can pull out "The Sub Making Binder". This is the binder that lists step-by-step everything an employee has to do to make a sub and deliver quality customer service.

    It might go something like this: When a customer walks in, welcome them with a warm, "Hello!" Ask them what type of sub they want. Ask them what type of bread they want. Ask them what type of condiments they want. Ask them if it will be for here or to go. See if they want to add one of Mama's homemade cookies to their order. I think you get the gist.

    The binder lists these steps in detail and talks about the quantities of toppings for different subs. "The Sub Making Binder" is really the procedure list that drives the task of the employee and will be the binder that the new employee will keep open all day long when they're starting out. They're going to go back to it over and over again for every sub.

    So, what does this have to do with programming? Well, a program in Arduino has to do similar things like the sub shop.

    The Setup Function

    There are certain tasks that need to be done just once when the program first starts. These are things like: setting up a serial communication to talk with the computer over a USB port, setting the modes of microcontroller pins as either inputs or outputs, displaying a welcome message on an attached LCD screen, or possibly turning a servo to a default location.

    All of these things might only need to happen once when the sketch first starts and never need to be bothered with again until the program is restarted or the Arduino is reset. These are the type of tasks that are put into a special function called Setup.

    Let's take a look at Setup. First, notice that the color of Setup is different. Unfortunately, the color is reminiscent of baby poop.

    This automatic coloring, though, is letting you know that the Arduino IDE recognizes the function Setup as a special type of function that's used for controlling the structure of the code.

    You'll also notice that right after the word Setup there is an opening and closing parenthesis. The Setup function doesn't need any arguments to operate, but you still have to include the opening and closing parentheses just as you would in any other function.

    To the left is the word void. Void means that the Setup function will not return any data.

    So this is a function that doesn't need any arguments from us in order to operate and doesn't return any values to us, but it does do something. Its job is to execute all the code inside its opening and closing curly braces precisely one time.

    Let me say this again - and with a dramatic pause - because it's that important! Setup only runs once. When the program starts up, Setup will run just once. All of the code inside the curly brackets will get executed one time.

    If you pretend the program is like the high schooler at the sub shop, the first thing she does when she comes to work is open "The Setup Binder" and go line-by-line until everything is done. Once everything in Setup is finished, she closes the binder, and then she goes on to the next binder.

    The Loop Function

    For the Arduino sketch, the next binder is the Loop function. The Loop function looks just like the Setup function.

    It doesn't take any arguments. It has the opening and closing parentheses. It doesn't return any values, so it has that void to the left. Then, it has the opening and closing curly brackets. Just like Setup, when Loop gets executed, the program will work line-by-line down the sketch.

    However, here's how Loop is different. When the code between the curly brackets has been executed, the program starts back at the top of the loop and does it all over again.

    Back to our sub shop example, imagine the teenage employee during the lunch hour rush. He has customer after customer lined up, and he's going through each line in the procedure guide step-by-step.

    He asks what kind of sub they want. He asks what kind of bread they want. He asks if they want it for here or to go, and so on and so forth. He keeps working down that list until he gets to the end of the procedure list.

    Then, he starts back at the top of the list with the next customer. He does this over and over and over, all through the lunch rush and all day long.

    This is how the Loop works. It executes all of the code inside the curly brackets, step-by-step. When it gets to the closing curly bracket, it starts all over at the top, working through all of the code again, line-by-line. It does this over and over and over.

    How fast can it go through the loop? How fast can it actually execute this code? Well, that's a really good question. The answer is that it depends, but the microcontroller that the Arduino uses can run at 20 megahertz.

    Each line of code you write might end up being multiple instructions when it actually gets translated into machine code, but needless to say, even a sketch with several thousand instructions will be looping pretty fast.

    Even though I really do like this sub shop analogy, there's one key place that it breaks down. I want to point it out so that you're not misled.

    In the sub shop example, the teenager waits to start the instructions again when a new customer shows up. In reality, the code in the Loop automatically starts over. Once it gets to the bottom, it jumps back to the top. It doesn't wait for any outside input to do so.

    Responsive Outputs for Loop Functions

    You might be wondering how the same code running over and over again can produce any coherent result. How does it add any variation?

    Well, think about that teenage sub maker. Do you remember the steps that she had to follow? Many of the steps could have different results depending on the response of the customer. So she may have had one procedure guide, but she could make a giant variety of tasty subs as a result.

    It's the same way with the programming code. You're going to write instructions that will do different things based on different new inputs.

    For example, if the water level is above some threshold, then beep an alarm. Otherwise, don't do anything. As the code loops over and over again, it's probably doing nothing until it sees that the threshold was too high. Then it executes what you've asked it to do.

    Or maybe something like... while the light is shining, keep the servo arm at 60 degrees. There's all types of amazing things that you can do and all types of possibilities of how you can control things.

    There's one last thing to keep in mind. The Setup and Loop functions are required in your sketches. Your sketches will not compile without them being present.

    In fact, these two functions are so integral that when you open up a new sketch in the Arduino IDE, you'll find them already there for you pre-populated.

    Review

    This was a lot of information, so let's review. Setup and Loop are special functions that help define the structure of the program.

    Setup is written before the loop and only executes once. All of the code in the Setup function only runs once.

    The code in the Setup function does things like set pin modes, start serial communication with the computer, display default messages to an LCD screen, or just about anything that needs to happen only once at the beginning of a program.

    The Loop function comes after the Setup function. All of the code in the Loop function runs over and over forever really fast.

    Both the Loop and the Setup function are required in your sketch. The program will not compile without them.

    If you ever forget what the Loop and the Setup do, just say their names. Setup sets up the sketch. Loop loops over and over again. I hope you have a wonderful day, and I can't wait to see you in the next video lesson.

    11 min
  • Functions: Let's make programming Arduino as easy as possible
    Discussion:

    In this lesson, we're going to do an overview of functions. This will be just a general discussion to lay out a framework for understanding how functions work and how we can use them.

    More specifically, we'll be talking about:

    • Function Calls
    • Function Parameters
    • Passing Arguments
    • Different Ways Functions Work

    In an earlier lesson, we said functions are like the verbs of a programming language. If you want to get something done, it's probably going to involve a function.

    Function Calls

    The Arduino programming language is essentially the same as C++ and a lot like C. So, it's chock-full of different types of functions that do all kinds of things for us. If you can think of something, there's probably a function that does it.

    To use this grand variety of functions, all we have to do is type the name of the specific function that we want to use. That's it. You just type its name.

    Then you follow its name by an opening and closing parenthesis. Sometimes, you have to put values in between those parentheses.

    Let's take this function called digitalWrite, for example. The digitalWrite function wants to know a pin number on your Arduino, and then it wants to know a state, either HIGH or LOW.

    Once you give it that information, it will apply either five volts, which would be a HIGH state, or zero volts, which would be a LOW state.

    When we type digitalWrite in our program, that is called a function call. I want to make sure that you've heard that terminology, function call, because you'll be hearing it quite a bit. We'll actually be going over a lot of terminology in this lesson.

    Function Parameters

    Some functions require information from us in order to work properly. The function digitalWrite needed to know two things. It needed to know pin number and high or low voltage.

    The pieces of information that the function needs to operate are called the function's parameters.

    You might be wondering, "How am I supposed to know what the parameters of a function are?" That's actually a really good question because when you look at the word digitalWrite, there's nothing in the name that alludes to what parameters it needs.

    In order to know what the parameters are, you have to look it up in a resource called the reference. The reference is like a user manual for programming languages.

    For functions that you use all the time, you'll become very familiar with what the parameters are. You won't have to look it up all the time.

    However, for functions that are unfamiliar, you'll probably have to refer to the reference frequently. It's really easy to use, and you'll learn a lot more about it throughout the course.

    Passing Arguments

    Back to our discussion on parameters. As said before, parameters are what a function wants or expects.

    The actual values that you give to the function, though, are called the arguments. In our digiWrite example, we have the number three and the state as HIGH.

    Those specific values are the arguments. This might sound like a case of semantics to you, but it's actually quite different.

    Parameters are just the general definition of what the function expects, like pin number or state. The argument is the specific value that you pass to a function, like 3 or HIGH.

    One more term to learn is "passing". When I give a function arguments, it's called passing. I pass the arguments to a function.

    Okay, so let's do a quick recap. When we use a function, it's called a function call because we're calling a function. Seems straightforward, right?

    The information a function needs to operate are called its parameters. The actual values we send into the function are called arguments. Lastly, when we send those arguments, we say we're passing the arguments to a function.

    Phew, that's a lot of terminology! Keep in mind that that's all it really is. It's just fancy computer programming words.

    The reason I want to talk about it here is because we're going to be using these terms throughout the course, and I'm sure you'll hear them elsewhere. Therefore, I think if you understand these terms, it will help us communicate better since we'll all be speaking the same language.

    Different Ways Functions Work

    Now let's move on to the different ways that functions work. For some functions, like our example digitalWrite, do something for us. We might pass the number 13 and HIGH to digitalWrite, and digitalWrite then applies five volts at pin 13. The function actually does something physical for us.

    Other functions just return values. For example, the function digitalRead monitors a pin on the Arduino and lets you know the state of the pin, either HIGH or LOW. It only has one parameter, which is the number of the pin that you want to check.

    To make sense of this, let's look at this line of code as an example. We have pinState = digitalRead(3). This line of code assigns the output of the digitalRead function to the variable pinState.

    So when this gets executed, the function digitalRead gets called, and we pass it the value three. Therefore, three is our argument.

    Now, digitalRead goes and checks the state of pin three. It's either going to be HIGH or LOW. Then, it sends that value back to our program.

    When it sends that value back, it's called returning the value. In other words, the function digitalRead returns the state of that pin. The value that gets returned will then be assigned to the variable pinState.

    Another example would be a Celsius to Fahrenheit converter function. It takes a number in Celsius and then returns the different, converted value in Fahrenheit. If you want that new Fahrenheit value, you need to assign it to a variable.

    Alright, so far we've been talking about functions that take parameters. In order for them to work, you have to give them some information. However, there are other functions that don't need any information to work.

    One common example is the millis function. When you call the millis function, it pulls the number of milliseconds that the current Arduino sketch has been running. Millis uses hardware that's integral to the integrated circuit the Arduino uses. It's going to pull information behind-the-scenes and return this value to you. You don't have to do anything.

    There are other functions that do this, as well. You don't have to give it any information. It goes out, it does stuff, and it gives that information back to you. So in this line of code, the variable timing will be assigned the number of milliseconds that the millis function returns.

    Finally, there are some functions that don't take parameters and don't return values. They just do something when they're called.

    Maybe you're working on a project that waters plants at different time intervals. You might need a function that simply opens a valve. In this line of code, we have OpenValve. The OpenValve function doesn't take any parameters. It simply opens a valve that we specify elsewhere.

    When we use a function, it's important to realize that there's more than meets the eye. For example, do you know what DNA stands for? It stands for deoxyribonucleic acid. It's quite a mouthful to say.

    So instead of saying deoxyribonucleic acid, people just shorten it and use the acronym DNA. It's a quick and easy way to communicate deoxyribonucleic acid without actually having to say deoxyribonucleic acid.

    Functions are similar to this in that they allow quick and easy access to a mouthful of useful code - the function definition. For every function name that you use, like digitalWrite or digitalRead, there's a function definition that gets executed for you behind the scenes.

    The function definition spells out exactly how that function is going to behave, what parameters it will use, whether or not it will return any values, and the like.

    In most cases, you're going to care very little about the function definition. You're going to be more interested in how to use the function. After all, the power of a function is its ability to reduce your workload.

    Programming languages are filled with tons of useful functions. Some are used far more frequently than others. You'll find that you'll get quite familiar with a couple dozen or so of your most frequently used, most effective functions.

    Other functions you'll slowly integrate into your knowledge. Later in the course, you're even going to learn how to write your own function definitions so that you can make your own handy user-defined functions, but that's going to be for a later time.

    Review

    Alright, let's review this lesson. We discussed what it means to make a function call. We also discussed that parameters are the general values that a function expects in order to work.

    The specific values we give a function are the arguments. Giving the function these arguments is called passing the arguments to the function.

    Finally, we talked about different ways that functions work. Some take arguments and then physically do something. Some take arguments and then return a value. Some don't take any arguments and but still return a value. Some don't take any arguments and don't return a value, but they still do something.

    We also touched on a lot about terminology in this lesson. Again, the goal of this lesson was just to layout a framework. I wanted to give you an overview of how we're going to be interacting with all different types of functions throughout the course. I look forward to seeing you in the next lesson.

    11 min
  • Data Types: One size does not fit all
    Discussion:

    We're going to explore some of the specific data types you'll encounter as you begin to program with Arduino. We'll tackle data types in more detail, to include:

    • Integer and Integer Qualifier
    • Long
    • Float
    • Byte
    • Boolean
    • Character
    Data Types Recap

    Let's review what we've learned in previous units. We know that when we create a variable, we need to declare its data type. We also know that a data type is simply a way to classify the types of information that you're going to put in a variable.

    Data type determines several things:

    • what range of values can be stored in the variable
    • how much space and memory that variable needs
    • what types of operations can be performed on that variable
    Integer

    We'll begin our discussion of data types with the most common one that you'll see in this course - the integer. This is abbreviated "int" when you type it into the Arduino IDE.

    The integer is really the go-to data type if you need to store a number. It can hold a value from -32,768 all the way up to 32,767.

    Keep in mind that it only holds a whole number. You can't store a decimal, such as 3.14, in a variable whose data type is integer.

    Also, an integer is a 16-bit value. In other words, it takes 16 bits (or two bytes) of memory to store an integer.

    It doesn't matter if you put a small number in that integer variable like 10, or a big number like 30,000. The compiler will always set aside two bytes for any integer, regardless of number size.

    In the grand scheme of things, that's pretty small and is why integers are our friends. They don't take up that much space, even if you need to hold a very large value.

    Now, what happens if you try to put a number bigger than 32,767 inside an integer variable? Well, it actually rolls over. I'm sure most of you are familiar with Pac-Man. You know how if he goes off the screen, he comes right back on the other side? The same thing happens with variables.

    Let's say we had an integer variable storing 32,767. Then, we add one to it. The result will actually be -32,768, which is called rolling over. Likewise, if you subtract one from -32,768, the result will be 32,767.

    This leads us to a really important point. When you create a variable, you should have some idea about how big you expect the stored value will be. That expected value will help you determine what data type you should use for a given variable.

    Remember, the key aspect of variables is that they change - they can vary. At some point, you'll probably do calculations with those variables and change what is stored there based on your results.

    You can only put so much water in a bucket before it spills over. Therefore, if the value in that variable at any time exceeds the size allow by its data type, it's going to roll over. You can imagine that might return some really weird results.

    With this in mind, what happens if you need to store a number bigger than 32,767? Well, you have a couple of options.

    However, before we abandon the integer for a data type that takes up more of our precious memory storage, let's talk about what signed and unsigned means.

    Integer Qualifier

    By default, an integer is signed. This means that it accepts both positive and negative signs. So when we say signed, we're talking about the fact that the value could be negative or positive.

    What if we know we won't be working with negative numbers? Our variable will never need to store negative values.

    For example, if I'm using a variable to store the number of days that have passed, there's never going to be a negative number of days. The number is only going to increase from its starting point - unless, for all of you 80's kids out there, I jump in a Delorean or something like that.

    If this is the case, we can use what is called a qualifier to make an unsigned integer. This gets rid of all the negative values and shifts them into the positive range.

    To use the unsigned qualifier, all you have to do is write unsigned before the "int" data type and voila... now you can store a value in the range from zero to 65,535 AND you're still only using two bytes of storage. Totally awesome!

    Rolling over still works the same way, though. If you add one to 65,535, you will roll back to zero.

    Long

    That's great, but what if you need a number bigger than 65,535? This brings us to a long. Long is a data type that stores four bytes of data and can hold a value from -2,147,483,648 to 2,147,483,647.

    You can think of a long as a really big integer. It acts the same way in that it can only hold whole numbers and can be made to qualify as unsigned if needed. This reaps you a whopping range of zero all the way up to four million and some change.

    Float

    We still keep running into this whole number wall, though. What if I want to store a decimal value?

    In programming, a number with a decimal point is called a floating point number. The point can float around the number.

    The data type for a floating point number is simply the float, and it can hold a value in the range from 340 undecillion 282 decillion, 315 nonillion (or 3.4028235E38 for you math whizzes).

    That's pretty big, so you might be thinking, "Geez, how much memory does it take to store a floating point number?" It's actually only a cool four bytes. That's right. It's no bigger than the long.

    How is this possible? It comes down to precision. In reality, a floating point number is only good up to six or seven actual numbers that mean anything. That's the total number - not just how many numbers after the decimal point.

    A number like 4,056.897 would be within the precision of a floating point number. You can see we only have seven digits there. The same would go for something like 40.1234.

    The less significant numbers after that, though, are going to be rounded off, chopped off, and battered. You really don't know exactly how the compiler's going to handle them.

    Large floating point numbers can be made using a capital "E" following the number. This means the same as it did in math class. For example, 42E2 means 42 times 10 to the second, or 4,200.

    You can think of the number that follows the E as the number of zeroes you want to add to the number before the E. To be honest, I hardly ever use the E. I just want to throw it out there just in case you run into it.

    Byte

    Another data type is the byte. A byte can store a number from zero to 255. As the name implies, it only takes up one byte of storage. That's extremely small.

    You could also run into a number like B10010 being set equal to a byte. This is a number represented in the binary numeral system.

    B is the binary formatter. It lets the computer know to interpret the number following the B as a binary number.

    We aren't going to delve into the binary numeral system because we really don't need to right now. You can check out the further reading section if you want to learn more about that, though.

    Boolean

    There is a data type that goes even smaller than a byte. The Boolean data type only takes up one bit of data. It can only hold one of two values: either true or false.

    Boolean is quite interesting. What happens if you try to put the number 2 in a Boolean data type? Does it roll over?

    No, it doesn't. With Boolean, any value other than zero is true. Numbers like 2, 5, -2, and 47 put in as a Boolean variable would be represented as true.

    False can be represented by several things. It can be represented by the keyword FALSE, the number zero, or the keyword LOW. We'll talk more about LOW later on.

    The true state can be represented by the keyword TRUE, any non-zero number as illustrated previously, and the keyword HIGH.

    If a variable only needs to represent two states, then a Boolean data type is a good option.

    Character

    This brings us to the final data type, the character. A character data type takes one byte of storage, and it holds a character symbol, such as a letter.

    The letter is actually stored as a number, and that number represents a specific text character in a system called ASCII. ASCII stands for the American Standard Code for Information Interchange. It's the way text is encoded numerically in programming.

    You can assign values to the character data type two different ways. It can be set equal to the actual character you want, as in an actual a, n, asterisk, or dollar sign, but you have to put single quotes around that character.

    The other way is to assign it as a number value since characters can be represented by numbers. For example, the following two lines of code would be equivalent because 97 is a lowercase a in ASCII code.

    This also means that you can perform math on characters. We won't get into that now, but it's kind of neat.

    Review

    Let's review what we've covered in this lesson. We talked a little bit more about data types and what they do for us.

    We talked about integers and the fact that they only hold whole numbers. Roll over and integer qualifiers were also explained, with special attention given to unsigned qualifiers.

    Long data types were next and how it's a really big number. Then, we moved on to the float for floating point numbers and the byte for simple numbers from zero to 255. The last two data types were Boolean, which is either true or false, and character.

    I hope you don't feel overwhelmed with all of this information. You don't have to memorize everything. I just wanted at the very least to give you a feel for what they represent because I guarantee you're going to see them as you open up different programs. Take a deep breath, soak it all in, and I'll see you in the next lesson.

    12 min
  • Understanding Variables
    Discussion:

    This lesson covers one of the most fundamental of all programming concepts: Variables.

    This is a really exciting topic because once you have a handle on how variables work, you have one of the biggest keys to understanding how programming works.

    Specifically, we'll be discussing:

    • Memory
    • Data Types
    • Declaring a Variable
    • Naming Conventions
    • Initializing a Variable

    What is a variable? Variables are a programming tool that help us store and recall information in our programs.

    Memory

    A microcontroller, like the one the Arduino uses, as well as computers in general, have something called memory. Memory is really handy because it allows us to store information for use at a later time.

    Let's say I'm working on a project that will monitor temperature during the day. I have a temperature sensor that reads the current temperature every 60 minutes from 1 am until midnight. I want the program to record the highest temperature and then display it at the end of the day on an LCD screen.

    In order for the program to accomplish this, it needs to store two key pieces of information. It needs to store the value of the current temperature, and then it also needs to store the value of the highest temperature that it has encountered thus far.

    But how do we actually save this information in a sketch? Furthermore, how do we recall it when we need to remember it? In order to do this, we need to use the memory.

    For now, think of memory as a big wall of lockers, and you can use the lockers to store something. When you need that something again, you just go back to locker and grab it.

    But how do you remember what locker you put it in? In order for us to do that, we first have to give the locker a name. That name you gave to the "locker", the place where you're storing your stuff, is called a variable.

    Now technically speaking, a variable is the named address of a specific location of memory. However, I don't want to get caught up in all of the technical stuff. I want to dive into the practical use of variables. Therefore, let's go back to this temperature project.

    As previously stated, we want to record the highest temperature during a 24 hour period. For our program, I need to store those two key pieces of information: the current temperature and the highest temperature.

    That means I'll have to name two lockers. I'll call one locker "Current Temperature", and I'll name another locker "Highest Temperature".

    Let's say my Arduino begins taking the first reading of the day. Maybe the temperature is 50 degrees. So I'll open the "Current Temperature" locker, and I'll put in the number 50.

    At the same time, I'll also open up the "Highest Temperature" locker. Right now there's nothing in it, but 50 is larger than nothing. Therefore, I'll put the number 50 in the "Highest Temperature" locker, as well. So now both of our lockers have the number 50 in them.

    After 60 minutes pass, I read the temperature again. Let's say it has raised two degrees to read 52 degrees Fahrenheit outside.

    I open up my "Current Temperature" locker, and I put in 52. This means that 52 overwrites the number 50 so that now the "Current Temperature" locker has the number 52 in it.

    I also peek inside the "Highest Temperature" locker. I see that 52 is hotter than 50. I go ahead and replace that also. I'm just going to repeat that process every hour.

    I open up the "Current Temperature" locker, replace the old value with the new value, and then check to see if I need to replace the temperature in the "Highest Temperature" locker.

    This reveals the first really important thing about variables and the most powerful thing about variables. The contents of a variable change. The name of the variable stays the same because the variable is just the container for the information.

    We don't want to confuse it with the actual information itself. The variable is the locker. It's not the actual stuff inside the locker.

    Let's recap what we've learned thus far. We need to store information, and we use memory to store it. We can think of memory like a wall of lockers. To use one of these lockers, we have to name it, and the name of the locker is called a variable.

    Once we have it named, we can put stuff in it and refer back to that stuff at a later time whenever we need it again. Again, the name refers to the location of the locker, not the actual content of the locker.

    Data Types

    There is another thing we have to do when we make a variable. We also have to say what type of thing we're going to put in it. This is called the Data Type.

    A good analogy here is to imagine that you have to build a zoo. You have to figure out where each animal is going to go in your zoo, and you have to make sure that each animal is given enough space so it can do its thing.

    For example, you'll need a bigger cage for a tiger than you will for an African frog display. If you're going to have an aquatic display, you'll need a bigger tank for a shark than you will for a goldfish.

    Where am I going with this zoo analogy? Here's the deal. You can't take a monkey and put him in a cage designed for fish. Likewise, you can't take a fish and put it in a cage designed for a tiger. It just won't work.

    Variables are similar to this because you have to specify a data type for the variable. Maybe an example will clarify what I mean.

    Let's assume I have a variable, and I say, "This variable can only hold whole numbers." I can put whole numbers in that variable all day long. However, if I try to put a number like a fraction into that variable, I'm going to get an error.

    The reason is that I specified the data type for that variable to be whole numbers. I can't put a fraction into a variable that I've designated as a whole number variable.

    Declaring a Variable

    Creating a variable is called "declaring" it. To declare a variable, you need two things: a name and a data type. The data type comes first, followed by its name.

    One example of a common data type is an integer. An integer is a data type that can store a whole number from -32,768 to 32,766.

    Of course, you don't need to memorize that. Just understand that a whole number is like 1, -5, or 18. It doesn't have a decimal point after it, such as the number 1.0567.

    In order to specify a variable as an integer data type, we use the abbreviation "int". The Arduino IDE recognizes all possible data types. Therefore, when you type "int", it will conveniently change the color of the text for you automatically.

    Following the data type, we need to key in the name. There has to be a space between the data type and the name.

    You can name a variable almost anything you want, but there are some basic rules to follow. A variable name cannot contain any spaces or special characters, such as a pound sign, dollar sign, or percent.

    You may use numbers in a variable name, as long as the name doesn't start with a number. Also, you can't use a keyword as the name of a variable.

    Keywords are special words that you will learn about later in the course. They're words that the Arduino IDE restricts for certain uses. Just like data types, the Arduino IDE will change the color of the text when you type a keyword.

    Thankfully, this means you don't have to know all the keywords right now. If you happen to type one, it'll change color and will help you realize that you can't use that as a variable name.

    Naming Conventions

    Using these rules, how should we name variables? Even though you can name them whatever you want, there are still some naming conventions that are best to follow.

    The bottom line is that your variable names should be descriptive of what information they will hold.

    For example, if we wanted to save the current temperature in a variable called "mom", we could. However, it really wouldn't make that much sense.

    It'd be more logical to name that variable "currentTemperature". That way, if somebody else reads our sketch, they will have a basic idea of what information is actually in that variable.

    Notice how I wrote the word "currentTemperature". I capitalized the T in the second word temperature. This is called camelCase. It's simply a way to help distinguish the words in a variable name.

    You could also type "current_temperature" with an underscore between the two words. How you write the name of the variable is up to you.

    The important concept here is that this is called the "naming convention". It is a way to keep things standardized to make the code easier to read and easier to understand.

    Throughout the course you'll see me use a mix of camelCase and underscoring, depending on the context of the variable I create. Again, you're free to use whatever name you want, as long as you follow the rules we discussed.

    Initializing a Variable

    As mentioned before, when we are declaring a variable, we need the data type followed by the name. Then, at the end of that statement, we want a semicolon.

    Once we've declared a variable, it can now hold information. To put a value inside a variable, we use what is called the "assignment operator", which is simply just an equals sign.

    The first (or initial) time we assign a value to a variable, it's called "initializing the variable". We can actually declare and initialize a variable on the same line of code. Here's an example:

    We have "int" for the data type and "currentTemperature"as the name of the variable. Next, there is the assignment operator, the equals sign.

    After that is the value to which we are initializing that variable. In this case, the initial value we are putting in the variable is 40. Lastly, we finish the statement with the all-important semicolon.

    If we want to change that value at some point later in the program, we just use the assignment operator again.

    In other words, we would type the variable name "currentTemperature", use the equals sign as our assignment operator, type the new value, and then end it with a semicolon.

    Review

    Let's recap this lesson. A variable is simply the name of a memory location. It's how we're able to store and recall information in our sketch.

    In order to use a variable, we have to give it both a data type and a name. The data type determines what we can put in a variable. Although you can use almost anything for a variable name, we did go over a few helpful rules and naming conventions.

    When we want to assign a value to a variable, we use an equals sign called the assignment operator. The first time we do this, it's called initializing that variable.

    Throughout the program, if we want to change the value of a variable, we simply type its name, assignment operator, and new value.

    That concludes this lesson. I know it's all kind of abstract right now, but these concepts will become more concrete as we move forward in the course. I look forward to next time where we'll dive more into data types and the like.

    12 min
  • Syntax; the spelling and grammar of programming
    You Will Need:
    • The Arduino IDE installed and an Arduino connected to your computer.
    Discussion:

    In this lesson, we're going to be talking about programming syntax. We'll be introducing some of the basic programming syntax that you'll be using every time you write a sketch.

    Specifically, we'll be talking about:

    • what programming syntax is
    • comments
    • the semicolon
    • keywords
    • function syntax
    • layout & indentation
    Programming Syntax

    What is programming syntax? I like to use this analogy. You can think of programming syntax like the punctuation and grammar of computer programming.

    If you've ever read a book, then you're probably really familiar with written punctuation and grammar. For example, in the written word, we use things such as periods, commas, dashes, or semicolons.

    Languages also have verbs, nouns, diphthongs, and all types of crazy grammar that goes with them. The punctuation and grammar that you're familiar with are tools that help us communicate effectively with one another in the written word.

    Commas convey a pause. Periods let us know a sentence has ended. Italics and bold text let us know if a word is emphasized. When we're communicating to another person, these are tools that help us do so.

    Just as written sentences require correct grammar and punctuation to be correct, the same is true for programming languages.

    However, with programming, in most cases we're communicating with the compiler - the compiler being the program that looks at our code and creates machine language for us.

    The programming syntax that we use is meant to communicate our intent to the compiler program. For this reason, the programming syntax MUST be correct.

    You can get away with messing up some grammar and punctuation when you're writing to a friend or an audience. They'll probably understand what your intent is.

    On the other hand, if you make an error in your programming syntax, there's almost assuredly going to be an issue. You'll have either a compiler error when you go to compile the code or a subtle and hard to find bug in the actual operation of your sketch.

    When you start out, you'll likely find that getting all the program syntax correct is a major hassle. It just doesn't feel natural, and the compiler is far more exacting than most "red pen crazy" elementary school teachers.

    The good news is that as you get more comfortable in the programming language, the syntax will come more naturally to you. It will become second nature as you write your code.

    Comments

    Let's start with one of the most important tools in programming - the comment. Comments are descriptive statements that a programmer writes to help explain the code.

    They are syntax and punctuation that really have nothing to do with the compiler. In fact, the whole purpose of a comment is so that you can hide these words from the compiler.

    There are two ways to create a comment. The first is the single line comment, which uses a double forward slash. It looks like this:

    Notice that all the text after the double forward slash is grayed out.

    If you have a lot to say, then you can use a multi-line comment. To start a multi-line comment, you type a forward slash followed by an asterisk. Now you can type multiple lines of comments.

    You'll notice that they're all grayed out. Also, when you press the enter key after that first line, the Arduino IDE actually auto closes the comment for you. It is closed with an asterisk and another forward slash.

    These additional asterisks on the lines in between are not required, but they are added by the Arduino IDE. These help the multi-line comment stand out from the rest of the code.

    As I said, comments are hidden from the compiler. They are words specifically for any other person reading your code - not the computer.

    I won't go into the substance of comments right now. You'll learn more about what comments should say as you work through the course, but I will say that comments should be descriptive statements explaining what that part of the code will do.

    Semicolons

    The next thing I want to talk about is the semicolon. The semicolon is to the C++ programming language as the period is to the English language.

    A semicolon lets the compiler know that a specific statement of computer code is complete. Let's take this line of code:

    .

    I know right now this code means nothing to you, but what I want you to see is the semicolon at the end. This semicolon lets the compiler know that your next line of code is independent from the previous one.

    If you wanted, you could move the semicolon to the next line of code or even insert spaces. It wouldn't make a difference. However, this is horrible form.

    You really should keep your semicolon on the same line of code that it ends. I just wanted to point this out to demonstrate that the compiler will ignore the spaces before and after a semicolon.

    If you forget to type a semicolon and then compile your sketch, you may get several different types of errors. I took out the semicolon from the previous line of code and compiled the code using the verify button. I then get an error.

    The message bar says, "expected unqualified id before numeric constant". What does that mean? Well, let's look down into the error and see what it actually says.

    If we look through these error messages, we can see that it's referring to the name of the program and the line of code - line 12. Then it says, "expected comma or semicolon before void".

    If we look back up to line 12, it says, "void". It's saying that it expected a comma or a semicolon. Now we can trace back our steps to that particular line of code and put in a semicolon.

    If I compile it now, it will be successful.

    In many cases, error codes are not very informative. Luckily, these are pretty descriptive. They tell you what line of code to look at, and they even tell you what you forgot. So it's pretty handy.

    Keywords

    You may have noticed that some of the words typed into the Arduino IDE automatically change color. These are called keywords.

    Keywords are specially designated terms in a programming language. They perform specific functions for us and are reserved to be used only for those functions.

    You'll get very familiar with different keywords as you work through the course. Therefore, we won't give an in-depth description of every keyword in this module.

    Remember, you'll know when you've typed a keyword because it will automatically change color.

    Function Syntax

    The next thing I want to talk about are functions. Keep in mind that this is a very cursory overview of functions. I want to give you just the gist of what a function does.

    Functions are programming tools that package up frequently used pieces of code to make them easy to use.

    Let's say, for example, that you had some code that did a calculation to convert degrees Celsius to degrees Fahrenheit. Maybe it was just a couple lines of code, but you found yourself using that code pretty frequently.

    Instead of having to type that code into the program every time you wanted to do the calculation, you could turn it into a function.

    To use a function, all you have to do is write the name of the function. Then, give it some pieces of information so that it can do the job. For example, if it was a Celsius to Fahrenheit converter, you'd have to give it the temperature in Celsius, and it would give you back the value in Fahrenheit.

    The Arduino language has tons of built-in functions, and, just like keywords, they also change color automatically when you type them.

    Functions are kind of like the verbs of a programming language. They make things happen, and they do stuff for us.

    The real reason I brought up functions isn't because I want to explain how they work. We'll be learning, in detail, about all different types of functions throughout the course. What I really want to talk about is function syntax.

    All functions are followed by an opening and closing parenthesis. Inside these parentheses is where you give the function what it needs to perform its task. If the function needs multiple pieces of information, those items are separated by commas.

    Some functions don't take any data, but they still must have a pair of parentheses. Also, every open parenthesis MUST have a closing parenthesis.

    Notice when I put my cursor on an opening parenthesis that the closing parenthesis is highlighted.

    Likewise, if I put my cursor by the closing parenthesis, the opening parenthesis is highlighted. This can be a handy tool to determine if you've actually closed the parenthesis after you opened it, or vice versa.

    Some functions, called control structures, have opening and closing curly brackets following the parentheses. The code that goes between these opening and closing curly brackets will get executed under different circumstances.

    Just as with parentheses, every open curly bracket must have a closing curly bracket. Furthermore, just like parentheses, if you put your cursor by one of the curly brackets, it will highlight the partner of that curly bracket.

    Layout & Indentation

    You may have also noticed that there is indentation in these lines of code. Indentation doesn't communicate anything at all to the compiler, but it helps the author of the code - as well as anyone else reading it- navigate through what's been written.

    As a general rule of thumb, when you're writing code inside opening and closing curly brackets of a control structure, the code is indented two spaces from the rest of that code. Then, that indentation continues if a new set of curly brackets is opened up.

    Another tool for indenting is the "Auto Format" tool in the Arduino IDE. Simply go up to "Tools" at the top of the screen, and then choose "Auto Format". You could also just press command T.

    This will automatically create the correct layout for you. It's much easier to use than manually indenting, and it keeps your code from looking sloppy.

    Review

    We talked about what programming syntax is. It's like punctuation and grammar for computer programming languages. We talked about comments, both single line and multi-line.

    We also talked about the semicolon and how it's like the period of a sentence for the C++ programming language.

    Next, we discussed the automatic coloring of keywords and about function syntax. Finally, we talked about layout indenting.

    That's it for this lesson. Again, this was just a cursory overview. Don't worry about memorizing every little thing and about whether or not you understood the coding shown. That's not the expectation right now.

    Really we just want to get our eyes inside the Arduino IDE and start understanding some of the basics - symbols being used and what some of the coloring and layout mean. I look forward to seeing you in the next lesson.

    Try On Your Own Challenge:
    1. Type the following code (exactly how it is typed), into the Arduino IDE. Remember - the compiler program will not accept errors - so don't get angry if you see a couple spur up the first time around - it is just part of the learning experience. When you are done, Verify the code by pressing "Control + r", you should not get any errors.
    2. //Type this into your Arduino IDE *EXACTLY* how it is typed here. //Don't worry about what the program does - this is about practicing the syntax. //This is a single line commment - What color is the text here? //Will the complier *see* these comments? /* This is a mutli-line comment. Will the compiler see these words? Are these multi-line comments colored different than single line comments? */ String dog; //Which of these words is a keyword? How do you know? //Setup only runs once. void setup() { //notice that setup() has a different color. // Comments are meant to explain your code to you and other people. //Set up Serial Communication. Serial.begin(9600); //This is the color of a library function }//This curly bracket "closes" the setup function. // Put your main code here, to run repeatedly: void loop() { //This curly bracket opens the loop() function. //Assign a bark to the dog. dog = "bark"; //Send the dog bark to the computer. Serial.println(dog); //Upload this code to the Arduino (CONTROL + U) and open the Serial Monitor Window (SHIFT + CONTROL + M) } //This curly bracket closes the loop() function.
    Further Reading:
    • ; Semicolon
    • {} Curly Braces
    • Comments
    12 min
  • Progress vs Perfection: Chicken Analogy
    Discussion: Will the Chicken Cross the Road?

    So there's this chicken, and he's on the side of the road. He wants to cross the road. He wants to get to the other side.

    Before he steps out and crosses the road, he looks both ways. That is a rational thing to do. If he doesn't look both ways, and he just steps out, he's going to get smashed by a car, and he won't get to the other side of the road.

    This chicken is a little bit of a nervous chicken. He is just sitting there and watching. A car passes by, another car passes by, and he's looking at each one. He is analyzing the traffic, but he never steps out in the street and actually makes any progress because he's always afraid a car is going to come and nail him.

    Now, in some regards, you and I are a little bit like that chicken. No, I'm not calling you yellow, or anything like that. That's not where I'm going with this.

    What I'm saying is that, many times, when we're learning something, especially a step-by-step process, we can get a little caught up on learning it and trying to learn that something to perfection.

    Instead of actually stepping out into the street and crossing the road, and actually making progress, we're sitting back and kind of studying, and studying, and studying. We're studying that traffic. We're actually not getting anywhere.

    Stepping out into Uncertainty- At Some Point You Have to Cross the Road

    In programming electronics, there is a lot to learn. Anytime you start to learn one thing, another thing is going to pop up. It's like this endless amount of rabbit holes.

    In order for us to actually make progress to our goal, we have to be willing to accept a certain level of uncertainty. We have to be willing to say, okay, you know what, maybe I don't get all of this. But, I am going to take a step forward, and I am to keep moving forward.

    That is really what I want you to try to think about as you learn all this new information. Some of it might (will) feel a little fuzzy as you move forward, and that is okay!

    As we go through the course, I'll give you some really good rules of thumb for when I think it's okay for you to take a step forward and say, "You know what? I think that I know this enough."

    Alright, let's go ahead and get cracking!

    3 min
  • The Arduino Development Toolchain - How it all gets done...
    Discussion:

    In this lesson, we're going to do an overview of the Arduino toolchain. The toolchain includes all of the software tools that are between us pressing the Verify/Upload buttons and that code actually getting loaded onto the integrated circuit on the Arduino board.

    I definitely want to stress the keyword overview because there is a lot going on behind the scenes that actually makes it happen. In practice for us, though, the entire process is just a matter of pressing a button.

    As we start to dig in, it's tempting to want to know every detail. However, remember that our goal in this course is to learn programming and electronics.

    If we're not careful, we can get pulled down this huge rabbit hole. That being said, I do think it's important to be familiar with the process.

    We don't need to understand it in depth. I just want you to be able to understand and recognize some of the terms and basic concepts associated with this toolchain.

    Specifically, we'll discuss:

    • What Is a Toolchain
    • A Toolchain Analogy
    • Toolchain Basics
    What in the World Is a Toolchain?

    So, what is a toolchain in the first place? In programming, a toolchain is just a series of programming tools that work together in order to complete a task.

    If we were cooking something, like carrot soup, the toolchain might include a carrot peeler, a produce knife, a pot, some water, and a stove.

    Together, these tools help you create the desired output, carrot soup.

    When we're developing programs for Arduino, we'll also be using a toolchain. This all happens behind the scenes. On our end, we literally only have to press a button for the code to get to the board, but it wouldn't happen without the toolchain.

    A Helpful Analogy

    So, I want to start peeling back the curtain on this Arduino toolchain. Imagine for a moment that you're an author. In fact, you're a New York Times bestselling author... just like me.

    What type of toolchain might you use? Maybe you start off with text editing software, just like Microsoft Word, to type your awesome story.

    Once you're done with that manuscript, you send it off to a professional editor at a publishing company. That professional editor is part of this toolchain. He will look over your manuscript and point out any errors. He might do some rearranging and other things, as well.

    After he sends the suggested edits back to you, you make any necessary corrections. Then, you give the manuscript back to that professional editor to do one last check for errors.

    He then hands it off to the office next door at that publishing company. The publishing company can't just take that Microsoft Word file and send it off to a printer. They need a special file type to format the book for how it should look on a physical page when it actually gets printed.

    Therefore, they take the manuscript in a Microsoft Word file format, and they turn it into a new file format. Once this is done, the publisher can send it off to be printed.

    Luckily, to make the process of printing a whole lot easier, this publisher has an in-house printer. So, he simply needs to just go right down the hall, so to speak. The printer takes that file and prints it onto an actual physical page.

    So, let's review this author's toolchain. The author writes with a text editor program. Then, he sends the manuscript to an editor at a publishing company.

    That editor reviews the manuscript until it is perfect. He then sends it next door to be formatted.

    The manuscript is converted into the proper file format, and it is sent off to the printer to create the physical book. Finally, voilร , somebody buys your book from Amazon to read all about zombies over a warm cup of latte.

    Arduino Toolchain Basics

    Why did I go through that long scenario? Well, the Arduino has a similar toolchain. When we start writing our code, and we become the author.

    We do this in the Arduino IDE, which is akin to a text editor. We also write the code in a programming language called C++, with a file type extension of .ino.

    The code that we write is called human readable code since it's meant for us to read and, hopefully, understand. However, the Arduino hardware doesn't understand C++ code.

    It needs what's called machine code. In order to generate that machine code, we use a software tool called a compiler.

    Remember that Verify button in the Arduino IDE that looks like the checkmark?

    When you press this button, it compiles the code using compiler software called AVR-GCC. This compiler software does a bunch of stuff.

    The main thing it does it rearrange some code and check for errors. This is like the professional editor at the publishing company.

    The compiler also translates the human readable code into machine code. There are some in-between file types and other fuzzy things that go on, but the final output of the compiler is a machine language saved as a .hex file.

    In order to get this .hex file loaded onto our Arduino's integrated circuit, we need to press the Upload button.

    This begins another piece of software called AVRDUDE, which sends the file to the integrated circuit.

    Normally, we would have to use some external hardware to load that circuit. However, in Arduino's infinite wisdom, they loaded a small piece of software onto the integrated circuit that automatically comes with an Arduino board.

    That piece of software is called a bootloader. It works with ARVDUDE to take the outputted .hex file and put it onto the flash memory of that Arduino's integrated circuit using only the USB cable.

    Again, all we had to do was press the Upload button. This whole process happens behind the scenes.

    Now the process is complete. So, what was our toolchain?

    We have the Arduino IDE Editor. Then, we have the compiler, which is AVR-GCC. The result is a .hex file.

    Next, we have AVRDUDE and the bootloader on the integrated circuit of the Arduino board. These work together to upload the .hex file to the board.

    REVIEW

    That was a lot of information to absorb. Let's summarize what we learned in this lesson.

    First, we learned that in programming, a toolchain is simply a group of software tools used to complete a task. Then we discussed the book publishing analogy to help illustrate that point.

    Lastly, we walked through the Arduino toolchain. As an encore, we'll go over that toolchain one more time.

    We start by writing human-readable C++ code in the Arduino IDE Editor. Then, we click Verify.

    The compiler program, called AVR-GCC, checks the code for error and adjusts some of the code for us. The result is machine code in a .hex file.

    When we press the Upload button, AVRDUDE takes that .hex file and works with the bootloader. The bootloader is pre-installed on the Arduino's integrated circuit, and it helps get the machine code loaded onto the Arduino's integrated circuit.

    Wow, I'm so glad that all happens behind the scenes! Again, this was meant only to be a cursory overview.

    I wanted to make sure that if you see AVR-GCC in error message or hear the word compiler or any of the other jargon we discussed here, at least you now have an idea of their significance. You now know where they are in the Arduino toolchain.

    9 min
  • Arduino Board Hardware overview for people like me
    Discussion:

    This lesson continues our quest of learning more about programming and electronics. In previous lessons, we already discussed several reasons why we have chosen to use an Arduino board as the tool to help us learn.

    Specifically, we chose the Arduino Uno board. The Uno is the baseline Arduino board, being the one around which other Arduino boards are designed .

    Therefore, the Uno is a great place for us to start digging in. It's also a fantastic launchpad if you decide to move on to other platforms in the future.

    In this lesson, we'll do a high-level overview of the Arduino Uno hardware. Specifically, we'll cover:

    • The Concept of an Arduino Board
    • The Three Types of Pin Header Rows: Digital, Analog, and Power
    • Other Miscellaneous Valuable Tidbits
    The Concept of an Arduino Board

    As we discuss the hardware, I recommend holding your Arduino board in your hand. Pause the video as needed to take a closer look at the board as we discuss the different components.

    First, I want to point out that the integrated circuit is the brains behind the Arduino board. It's very likely that the circuit is the Atmel ATmega 328, which is an 8-bit microcontroller.

    Don't worry about that fancy name. The only thing I want you to understand is that everything on the Arduino board is meant to support that integrated circuit. So, the Arduino exists to make it easy to use this microcontroller.

    If you look closely at the microcontroller, it may look slightly different from mine, depending on which model you have. It might be really small, called a surface mount component, or it could be a big one like mine, which is called a DIP.

    Either way, there will be little metal prongs that stick out of the side. These are called pins.

    These pins are how the microcontroller is able to do stuff. These are used to interface with other hardware and circuitry, such as LEDs, sensors, or even your computer.

    Therefore, we need to know how to actually connect them to other things. That's where the pin headers come into play.

    Pin headers, sometimes referred to as just headers, are the plastic rows of holes that stick up from the Arduino board. They are all along the border.

    Inside of the holes are little metal clips. When you stick a wire down into the hole, that wire will stick and stay there.

    For example, you can stick the wire that comes out of an LED or a resistor into those holes. The wires are called leads, by the way. The wire makes an electrical contact in that hole.

    In other words, the wire sticks in the pin header. The metal clamp inside the header clamps onto the wire, and an electrical connection between that wire and a specific pin on the microcontroller is then created.

    Digital Pin Headers

    There are three categories of headers: digital, power, and analog. The first one we'll discuss is the digital category.

    Digital pin headers make up the longest row on the Arduino board.

    They are numbered from zero to 13. That means there are a total of 14 digital pins that we can use.

    To make this lesson as practical and easy as possible, for our purposes when I say digital, I mean something that is a discrete state.

    Let's use color as an analogy. Something that is digital can only be either black or white. Digital does not care about any point of gray in-between.

    Therefore, digital pins are used in one of two ways. They can be used as inputs to do things like read a voltage. Otherwise, they are used as outputs, such as applying a voltage.

    When they operate as an input, they can only read two different voltage states - high or low. The same is true when they act as outputs. They can only output two voltage states - five volts (high) or zero volts (low).

    Just as in anything else in life, there is an exception to this. You'll notice that some of these pins have a little squiggly mark next to them.

    There should be six of them, located at pins three, five, six, nine, 10, and 11. These specific pins allow you to use a technique called pulse width modulation, or PWM.

    PWM is a technique that we'll dive into later in the course. It enables us to use digital pins in such a way that they appear as though they are outputting a varying amount of voltage.

    Again, we'll get into PWM in much greater depth later. Right now I just want to point out those pins, and why they are special.

    I also want to point out two other pins. Notice that pins zero and one have a "TX" and "RX" next to them with little arrows. That stands for transmit and receive.

    The Arduino uses these two pins to communicate between the board and the computer. For example, maybe you need to upload your code.

    Maybe executing your sketch performs serial communication between the Arduino and the computer. Serial communication is another concept we'll be learning later in the course.

    It's only important that you understand these pins used to transmit and receive. Therefore, it's best to only use pins zero and one as a last resort if you've run out of available pins.

    The reason for this is that sometimes adding additional circuitry to these pins can interfere with serial communication. This will make a lot more sense when we get to that section of the course. For now, just know it's a good rule of thumb to leave pins one and zero alone.

    There are also two on-board LEDs labeled "TX" and "RX". These blink every time you send information back and forth between the Arduino Uno and the computer.

    If you have the Arduino hooked up, and it's supposed to be communicating with the computer, you should see these blinking. If not, it's a good indication that you probably don't have the Arduino set up correctly in the IDE, and communication is unsuccessful.

    Lastly, pin 13 is also worth noting.

    That is where an on-board LED is attached. You can use that LED as though it were externally connected through a resistor to the Arduino.

    Analog Pin Headers

    The next category of headers are analog pin headers. These are labeled A0 through A5, giving us six analog pins.

    As you might have guessed, "A" stands for analog.

    Before we said that digital means discrete states - either high or low, one or zero, black or white. However, analog is a lot more colorful.

    When we say something is analog, it means that it can be in any number of states. Analog embraces all of the various shades of gray between black and white.

    Many sensors create analog signals. They're not just on or off. They can be all of the states in-between.

    However, our integrated circuit really only knows discrete digital states. Therefore, the microcontroller handles analog inputs by using a tool called an analog-to-digital converter, or simply an ADC.

    The ADC is part of the integrated circuit, built right into the chip. The analog pins have access to it.

    The ADC takes all of the variation in an analog signal and cuts it up into discrete steps. In other words, instead of having an endless list of possibilities from your low to high limit, the ADC would cut that expanse from the low value to the high into a certain number of "chunks".

    In addition to being able to use the ADC, analog pins can also act just like digital inputs or outputs. So, they are very versatile. We'll do a deeper dive on this later in the course, as well.

    Power Headers

    The last row of pin headers is the power header row. They are next to the analog headers.

    There are only a handful of pins I want to point out right now. The first one is labeled "5V".

    That stands for five volts. If you have the Arduino hooked up to the computer via USB, or if you have external battery power applied, this pin can provide five volts to a circuit. We'll be using this pin extensively throughout the course when we're setting up our circuits.

    The pin next to it is labeled "3.3V", which stands for 3.3 volts.

    Obviously, it provides 3.3 volts to the circuit.

    Next to these pins are two pins labeled "GND", which stands for ground.

    These two pins give us access to the lowest voltage on the Arduino board, which is zero volts.

    Miscellaneous Goodies to Know

    There is yet another ground pin located up next to the digital header row.

    It's important to keep in mind that all of these ground pins are one in the same. They are all connected to each other. Therefore, throughout the course when we set up our circuits, it doesn't matter which one you decide to use.

    Let me make one final note about the pin headers. You may hear a term thrown around called the "Arduino Footprint". That's simply how the Arduino headers are aligned.

    If something is said to match the "Arduino Footprint", it means that it has that same header layout as the Arduino board. The most common example of this would be an Arduino shield because, by default, the headers on a shield are almost always going to match the board.

    That term is not really all that important to know, but I wanted to make sure you had heard the term if you ran into it.

    Another item that is helpful is the reset button.

    Just as the name implies, when you press that button, the program currently running on your Arduino board will start back at the beginning. It doesn't erase the program. It just starts the program over.

    There is also a reset pin on the Arduino.

    If you apply a low voltage to that pin, it does the same thing as the reset button. It will reset the current program running on the Arduino.

    Next, the Arduino Uno has a power on LED.

    It is illuminated anytime power is being applied to the Arduino. This is true no matter if the Arduino is powered through a USB cable or through an external power jack.

    Review

    Wow! Lots of components! How about we go back over the highlights?

    We talked about kind of the overall concept of the Arduino board. It is built to support the integrated circuit.

    We also discussed the three different pin header rows. We went into detail about the digital, analog, and power headers.

    Finally, we covered a few miscellaneous components. The Arduino Uno has a reset button, a reset pin, and a power on LED.

    Hey, don't worry if you still have a lot of questions! That's to be expected this early in the course. A lot of terminology and some new concepts were thrown around.

    Remember, though, this was only meant to be an overview of the Arduino hardware. As we move further into the course and delve deeper into the specifics of these concepts, it will all begin to come together. Patience, young grasshopper.

    11 min
  • Everything you need to know about the Arduino IDE (for now)
    Discussion:

    Now that you have downloaded and set preferences, you need to become familiar with the Arduino Integrated Development Environment, or IDE for short. It works just like a text editor program.

    I'm only going to cover what I think is important for us to know right now. We do a deeper dive on an as needed basis as we progress through the course. Specifically, in this lesson we'll cover:

    • Selecting an Arduino Board and Serial Port
    • Saving an Arduino File
    • The Editor, Message Area, and Console
    • A Few Other "Good to Know" Items

    So let's open the Arduino Integrated Development Environment (IDE) and get started. Do this by clicking the Arduino icon.

    Which Board and Serial Port Should I Use?

    The first thing we're going to discuss is selecting the correct board. We have to let the Integrated Development Environment know what Arduino board you're using.

    Go to the "Tools" tab, and then go down to where it says "Board". You'll notice I selected the Arduino Uno since that is what I will use throughout the course.

    I recommend that you use an Uno or an Uno derivative throughout the course, as well. This will standardize our work in these lessons.

    Once you've selected the board, next you need to select your serial port. People can sometimes be intimidated by this technical term, but you don't have to be.

    Serial ports are just the different things connected to your computer. The easiest way to find out which of the ports listed is your Arduino is to first unplug the Arduino from the computer.

    Go to the ports list under the "Tools" tab, and write down the names of these ports.

    You only need to write enough to differentiate one from the next - maybe the last word or last few letters.

    Then, close your Arduino IDE. Plug your Arduino board back in via the USB cable to your computer. Open the Arduino IDE.

    You should now be able to see an additional serial port not on the list you originally wrote down. That will be the serial port to which your Arduino is connected.

    For Mac, you'll usually see cu or tty after the "dev/". Those are the common ways Arduino will show up on the serial port for a Mac.

    For a PC, it shows up as a COM port, but it's hard to know which one it will be. It could be one, two, four, etc.

    That's why the best method, although primitive, is just to unplug and plug the Arduino back into that port.

    Once you've chosen the board and port the first time, these settings will stay the same for any subsequent times you reopen the Arduino IDE.

    The reason I point this out is that if you happen to get a different board at some point, you will have to remember to change the board that is selected.

    The Arduino File

    When you open the Arduino IDE for the first time, it will open up a file for you, giving it a default name. That default is sketch, underscore, and the current date.

    That name also appears at the top of the IDE, along with the version of Arduino you're using.

    To save this, go to the "File" tab and then to "Save". It's just like saving any other file. Notice it asks you to save the file in "Documents".

    Remember that in Arduino, files are referred to as sketches. So, the collection of our sketches is known as the sketchbook. The sketchbook folder is where all of the sketches we write will be saved.

    Of course, you can also nest your files in that folder just like you could in any other program where you're saving files. It's really no different.

    Take a look at the name I chose for my file. There are certain rules you must follow when choosing a name for your sketch.

    When you're naming a file, you can't use any spaces between the words. One common method is to use an underscore where you would have normally preferred a space.

    You can't use special characters, either. You can use numbers in the name, but you can't have a number as the first character. Lastly, the names are limited to 64 characters.

    So, using these rules, name your sketch and save it.

    You'll see that the name on the tab and at the top of the screen now displays the name of your newly saved sketch.

    So, saving is really easy. The shortcut command is Ctrl S. There is also a down arrow that you can click.

    The Editor, Message Area, and Console

    There are three main areas of the Integrated Development Environment: the editor, the message bar, and the console.

    The editor is the big white space. It's where you type the Arduino code.

    It has number lines down the side - as long as that was one of the preferences you checked from our last lesson on choosing your settings.

    Right now it shows one through nine. If we were to add more code or move our cursor down further, it would adds numbers as lines are added.

    I want to point out one thing in this name here. Do you see the little funky looking "s"?

    Every time you make a change to the sketch that has not been saved, that s will be displayed. If I save the file, it goes away.

    If I were to type something in the sketch again, the funky little s would come back. It's just a visual reminder to save your changes.

    Personally, I am a save fanatic. For just about every single line of code I write, I use the shortcut key Control S to save before I go on to the next line.

    I want to make sure I don't lose anything in the event that I have an issue with either the Arduino IDE, my computer, unexpected interruptions, or whatever might happen.

    There is something interesting you might have noticed when you open a new sketch in Arduino. It auto-populates two of the mandatory functions for coding in Arduino.

    This is why you see void setup an void loop. We'll talk about these in depth later, but it's perfectly normal for these to show up. It's just a way of helping you save time when you code.

    On top of the editor area are two very important buttons.

    The first one is a check mark. It is the Verify button. When you click this, the code gets compiled.

    Compiling, as discussed before, is taking the human readable code that we've written and translating it into machine code. As it compiles, the program will point out any errors found in that code.

    It also does some optimization. This is a way behind the scenes concept that you don't have to worry about right now, though.

    You constantly want to check for errors in your code. I like to verify my code at almost every line of code I write along the way.

    The more you verify, the more quickly you can identify where you might have introduced an error into the code, i.e. find and fix a bug. We'll be using this verify button all the time.

    The shortcut key for verify is Command R or Control R. You can also verify by going to the "Sketch" tab.

    That other button is the Upload button. That takes all of the code that we've written and uploads it to the Arduino board.

    When you click that button and look at your Arduino board (assuming that it's hooked up to your computer via the USB cable), you'll see two lights blinking rapidly. That is the TX and RX buttons.

    This is a good visual indicator that you have a good connection between the Arduino board and the computer. The IDE is recognizing that you have a board hooked up. In other words, the lights tell you that the code is successfully being uploaded to the board.

    The shortcut key to upload is Control U or Command U. It is available in the dropdown under the "Sketch" tab, as well.

    The second main area of the IDE is this blue bar. It is the message bar.

    It will display information about what you've done recently in the program. For example, I just uploaded. You can see that it says, "Done Uploading."

    If I press Control S to save, it would say, "Done Saving." There are other pertinent messages that display while you are using the program.

    The third main area of the IDE is the black space below the message bar. It is called the Console.

    Now, you probably won't hear it referred to as the console very often. Many people just call it the error section, or some other generic term.

    If you want to increase the console's space, there is a bar you can drag up. It may be hard to see, so I put a box around it.

    The console displays the error messages. It will tell you information about the current operation that you did.

    For illustration purposes, let me introduce an error into the code and verify it. I'll just type a crude, uncoded line somewhere in the editor area.

    You can see that we get definitely get a reaction out of the Arduino IDE. First, the message bar gives us a quick note saying that you wasn't declared.

    Again, don't worry about understanding the error itself or any of the terminology displayed. I just want you to see where different types of information shows up.

    Then, in the console much more detailed information about the error is displayed. It tells you what file it was in, what function it was in, and even the line of code. Here it says the error was in line three.

    If we look back up at line three in the editor, we can see that it gets highlighted. That's where we can start looking for our error.

    Unfortunately, it will not always point out the correct line of code for the error. You might have to do a little searching around, but that is a discussion for another time and another lesson.

    You now know the three big pieces of the Arduino IDE. We walked through the editor, the message bar, and the console.

    Miscellaneous Tidbits

    There are a few final items we should discuss that are good to know. At the very bottom of the IDE is a number. Currently ours shows the number three.

    That simply refers to the line of code where your cursor is located. It seems like such a small detail, but it is very handy.

    Once you begin to work with larger and larger sketches, it may be harder to keep track of your cursor. This is especially true if you decide not to display line numbers down the side.

    Also, in the far right corner you'll see some additional information.

    It is the name of the Arduino board and which serial port that you identified earlier that you're using.

    In the top right, there is a little magnifying glass. This is for the Serial Monitor.

    If you click it, a window like this opens:

    The Serial Monitor window allows us to see communication occurring between the Arduino and the computer, and vice versa. We'll have an entire lesson later down the road about the Serial Monitor and communications.

    For now, just know that the button is there. The shortcut key for the Serial Monitor is Shift-Control(or Command)-M.

    Now Get Going!

    You now know enough information to start using the Arduino IDE. You can see it's not too complex. The IDE is very simple and streamlined.

    Arduino was designed for ease of use. There's not a bunch of bells and whistles that can sometimes get in your way. I have no doubt you'll be an Arduino pro in no time.

    12 min
  • Mac - Download and Install the Arduino IDE
    Discussion:

    Before you begin using the Arduino IDE, you must first learn how to download, install, and set your preferences. This lesson is specifically tailored for those who use a Mac. (The last lesson covered this same topic, but for PC users.)

    I'm currently running Mac OS X Yosemite. You are probably running a newer version of Windows. However, the following instructions will be almost identical from one version to the next. If this should ever change, I'll update this lesson to reflect those changes.

    Find the Arduino IDE Download

    First, jump on the internet with your favorite browser, and navigate to www.arduino.cc. Look for the tab labeled "Download".

    The page on which you land might look a little different than this. It does change from time to time, but there will always be an obvious tab for Download.

    Go ahead and click Download. We're currently working on version 1.6.5, and what you'll do is select your operating system.

    Click on that "Downloads tab". That will bring you to the "Download the Arduino Software" page.

    Once on this page, choose your operating system. For Mac users, you have two options.

    You can download from the green panel:

    Or you can get the absolute latest, razor-sharp release of the Arduino IDE. This is found in the section labeled "Hourly Builds".

    If you want the most recent update, you can download from this section. But this is just as the name implies. The information here can be updated as often as hourly, and may not be as stable as an official public release.

    Therefore, in this lesson, I will demonstrate the Windows Installer. This is the best route to go in almost any case. It's rare that another option is better.

    Download and Install

    I'm using Mac OS X. Therefore, I'll click that. It then prompts me to save a Zip file.

    It doesn't matter where you save this Zip file. I'm going to save it to my Downloads folder.

    I'm going to save it to my downloads folder. This will initiate the download.

    It's not a big file. It's around 131 Megabytes for this current release. I have just an everyday, run of the mill cable internet connection, and yet it still doesn't take very long to download.

    Once it's completely downloaded, I'm going to find it using "Finder". It found it in my Downloads folder.

    Double-click your Zip file. The Archive Utility for Mac will automatically unzip it for you.

    After the Zip file has been unzipped, you'll see that the Arduino IDE icon will be created inside whatever folder you unzipped the Zip file. (I'm just trying to see how many times I can say "Zip".)

    I'm going to move the Arduino program to the Applications folder on my Macintosh computer. So go to the Macintosh hard drive, then Applications, and then drop it in there.

    Now, I already have Arduino installed. If you already have an older version of Arduino installed, it will ask if you want to first uninstall the older version before continuing the download of the newer version.

    My recommendation is to select "Replace" to uninstall the older version. It will not harm anything or delete any work you have done.

    It simply gets rid of the older Arduino IDE, not your sketch folder. If you don't know what that means, it's not important. Just know that you will not lose anything if you uninstall.

    Next, it will run through the uninstallation process. Once completed, you can see that the Arduino icon is in the Applications folder on my Mac. Right-click on this and choose to open it.

    It's going to give me a prompt the first time I open up the Arduino IDE.

    It double check whether or not you really want to open it since it is from an unidentified developer. Just click "Open".

    By the way, if you try to open the Arduino icon from the Applications folder in your dock, you may not even get an "Open" option. In this case, locate the Arduino icon in the Finder and right click to open.

    Set Preferences for Arduino IDE

    Now that the Arduino IDE is open, maximize it. In another video, we'll discuss how this works in-depth, but for now I just want to set some preferences.

    Go up to Arduino, then click "Preferences".

    Probably the most important thing to look at is the first line that comes up - the Sketchbook location.

    When we write a program in the Arduino IDE, it's called a sketch. All sketches are saved within a Sketchbook.

    The Sketchbook is a folder where you can to keep all of your work. The default location is usually under Users\The User's Name\Documents\ and then a folder created that is named Arduino.

    If yours does not look like this, or if you would prefer the Sketchbook folder be in a different place, you can browse to select a different location.

    I would definitely recommend using a folder named Arduino. This default location has always worked pretty well for me.

    The next preference to set is the Editor language. You can pick from a bunch of different languages. I'm using English, obviously.

    Another setting is editor font size. The default is 12, but I prefer a larger font. Font size 18 works very well for me.

    Be aware that sometimes if you make the font too big, you'll see that one line actually gets written overtop of the other. Therefore, you might have to play around with font to find your optimal size.

    There are a few other things that I think are good to set in preferences. One is whether or not to display the line numbers.

    I suggest you check the box for this. It means that each line of your program, or sketch, will be displayed on the left side of the Arduino IDE.

    Another preferences I suggest you choose is to verify the code after upload. This won't mean anything to you now, but you'll see later why this it's an excellent idea to check this feature.

    The next setting I usually choose is to check for updates on startup. It's not imperative. You can check or uncheck this box depending upon your own personal taste.

    It depends on whether or not you want to stay with the same current version the whole time. If you just want the most updated version, you can keep that box checked.

    I do recommend, however, keeping the "Update sketch files to new extension" checked.

    Basically, this means that whenever you open an Arduino file, it ensures that if the file doesn't have the proper extension, then that file will automatically be converted to .ino.

    Arduino files used to have a .pde extension. However, now they are .ino files. That's why it's handy to keep this option active.

    Finally, I think having the last preference chosen is also a good idea. That setting is to save the file when you are verifying or uploading.

    Again, we'll talk about verifying and uploading in depth in later lessons, but just take my word for now that it is always good practice to save as frequently as possible.

    Going Old School

    Not all versions are the same. It could be that maybe you prefer the look and feel of a previous version. Or maybe you're just really familiar with and used to working within the framework of a certain version.

    If you prefer to download and use a previous version of Arduino, never fear. We have a solution for you that like to go old school.

    On the Arduino website for downloads, look to the bottom right panel. There is the section for previous releases.

    Clicking that will show you a list of all previous releases for each type of operating system, along with the date they were released. Click which you prefer, and from there downloading is the exact same process as before.

    Again, this lesson applies to those who own Macs. If you are using a PC, you can go back one lesson and see this same download, installation, and preference concept for your particular operating system.

    8 min

About Learn Programming and Electronics with Arduino

From the publisher's feed

Video lessons on learning programming and electronics with Arduino. This is part of our Arduino Crash Course and Arduino Course for Absolute Beginners. It's designed to take someone with little orโ€ฆ