Introduction
Programming is becoming more useful in a variety of fields. There are a lot of uses, but we are most interested in robotics applications. Microcontrollers like the Arduino are programmed in C++, which is undoubtedly the most widespread language. It is powerful, fast, and easier to use than some earlier languages. However, it is not the easiest language to learn. It has a very strict syntax and the errors can be hard to understand. It is still worthwhile to learn due to its usefullness.
If you are just interested in learning programming in general, I highly recommend looking at Codecademy, which is an excellent interactive environment for learning for the first time. Of their courses, Javascript is most similar to C++, but Python is the easiest and most powerful choice.
The Basics
Programming is actually quite simple. There are really only a few things that you need to know to get started.
- Data is stored in "variables"
- The right hand side of an equals sign goes into the storage with the name at the left
- There are different kinds of variables that contain different kinds of information
- A program is executed top down
- Each line is terminated by a semi colon
- Comments are ignored ( lines that begin with two slashes: // )
- There are three fundamental actions that alter the top-down flow:
- Conditions: do something only if something else is true
- Loops: do something repeatedly
- Functions: do a group of things and get a result
Try It Yourself
Set up a Development Environment
You need a place to code! Code::Blocks is a good place to start, but there are dozens of options. Microsoft Visual Studio Express is actually free to use, but there are free-er (open source) options too.
To install Code::Blocks, go here and choose the mingw-setup.exe. The mingw is important because it includes a compiler, which turns the program that you can write and read into something that your computer can actually run. Install the program like you would any other.
Use the Development Environment
Now get started! Run Code::Blocks. Make a new source file (File > New > Empty file). Put this simple program in there.
#include <iostream>
using namespace std;
int main() {
// anything preceeded by a // is a comment and ignored by the computer
// code goes in between the above and below { and }
cout << "HELLO WORLD!"; //shows "HELLO WORLD!" in a command prompt
}
Be sure to pay attention to things like semi colons and brackets. It won't work if you miss one.
All this program does is print out the words HELLO WORLD to the terminal or command prompt whenever it is run.
Try it out! Hit the green button "Run" triangle at the top of the Code::Blocks to compile and run it.
Fundamentals of Programming
These are the five things that you need to know to program, that's all!
- Variables are places you store data
- Operators do things to data
- Conditions check data, and do something if it is a certain way
- Loops let you repeat actions
- Functions let you group actions together so you can re-use them and return a result of those actions
Variables
Variables are not at all like the variables you find in math. These are just named places you put information. You can change the contents of what's at a name, which is what "varies" about it. You can only store a few kinds of information, and they are:
int
: An integer can hold a whole numberchar
:A character can hold a letter or symbolfloat
: A floating decimal point can (inaccurately) hold really large and really small numbers (and decimals)
First, you need to declare the variable. You start by saying the type of data it can contain. When this is done in C++, it is uninitialized - meaning that you have no idea what it contains. You might want to assume, for example, that a number starts at 0 when you declare that you want to use it, but you have to explicitly say that.
Then, you assign contents to the variable. The contents can be pre-defined by you, or you can get the contents of another variable, or even read it in from somewhere else.
Arrays
All variables can be be arrays. An array is a series of variables put next to each other. You specify the array with the array's name, and which item in the list of its variables you want with a number in brackets after it. The first item in the list is at the number 0. You have to say how large an array is when you declare it.
An array with its index behaves exactly the same as a variable would
int numbers[3]; // declare the array (list) of integers (whole numbers)
numbers[0] = 100; // fill the first item in the list with a 100
numbers[1] = 200;
numbers[2] = 300; // fill the last item in the list with a 300
Swap Example
Swapping variables is an excercise of the very important concept of storage and variables.
Imagine you have two cars in a parking lot you want to swap parking spaces with. You're the only valet and you want to swap the two cars so they match colors with the other cars because you're bored. In order to swap the cars, you'll have to move one car to a third parking space temporarliy while you move the other into the newly vacated space. It's a similar solution to a slightly different dilema. If you were to try to swap directly (without a temporary) with the cars, you would smash one into the other, but in a program you would end up two copies of the same data.
Start by declaring two variables you want to swap, and a temporary variable. Then assign something different to the two variables. Store the contents of one of those into the temporary. This is extremely important because otherwise the contents of "first" will be lost in the next step, which moves the contents of "second" into the "first" variable. Finally, the temporary variable moves the former contents of "first" into the "second" variable.
Swap Integers | Swap Floats | Swap Characters | Swap Array Elements |
---|---|---|---|
//declare integers int first = 100; int second = 200; int temp; //next shift data // Step 1 temp = first; // Step 2 first = second; // Step 3 second = temp; |
//declare floats float first = 1.0; float second = 2.0; float temp; //next shift data // Step 1 temp = first; // Step 2 first = second; // Step 3 second = temp; |
//declare chars |
int num[2]; |
As you can see, it is the same proceedure to swap the contents of variables, regardless of data type.
Operators
An operator is a letter or couple of letters that just say "do something" to a variable. For example, a + sign is an operator that says add two numbers. There are actually not that many operators. Operators do very simple actions. More advanced actions can usually be broken down into a series of these simple actions. Don't worry, you don't have to remember it all at once, but they are fairly intuitive.
- Storage
=
The assignment operator copies the contents at the right into the variable at the left.- Math - modify the data
+, -, *, /
all perform math operations the way you would expect++
and--
increment or decrement a variable by 1- Really,
number++
is just a shorthand fornumber = number + 1
+=
and-=
are shorthand for addition and subtraction then asigment- Again,
number += 10
is just a shorthand fornumber = number + 10
- Logical - Checks something about the data
==
The equivelence operator checks to see whether the contents of the right and left are the same- Be careful not to confuse it with the assignment operator
=
>
,<
,>=
,<=
all check for inequalities- ! also called "not" inverts the condition, making a false into true, and a true into false
&&
,||
also called "and" and "or" respectively are ways to check multiple conditions at once
Operator Usage Example
// declaration
int number = 1; // create space for and store a whole number: 1
// arithmetic
cout << number; // prints 1
cout << number + 2; // prints 3 (1 + 2 = 3)
cout << number; // prints 1. "number" did not change! Nothing was assigned;
// assignment
number = number + 2; // add 1 to 2, then assign that result into number
cout << number; // prints 3. "number" changed! It was assigned a new value
// increment
number++; // adds 1 to the former contents of number (3)
cout << number; // prints 4 (3 + 1 = 4)
// logical operations
cout << number == 4; // prints a 1, which means true. "number" does equal 4.
cout << number > 4; // prints a 0, which means false. Number is not greater than 4
Conditions
Conditions, as the name suggests, will check to see if something is true, then react based on that information. Conditions are used in if statements, and evaluated in loops (more on that later). They are either true or false.
Use the logical operators to construct your conditions. You can check for equalities, inequalities, and chain these conditions together with and (&&) and or (||) operators.
An if will only execute the code within its {brackets} if th condition is true. An else if's code will only get executed if the preceeding "if" was false and it's condition is true. An else's cod will only be executed if the preceeding if and else ifs are all false.
Guessing Game Example
// Ask for a letter from the user.
cout << "I want to play a game. I am thinking of a letter a through z. Guess: ";
char letterRead; // declare space for an character
cin >> letterRead; // read input for the command prompt and store it in letterRead
// use a condition to see if their guess was correct
// note the use of the equivelence checking operator (==), not assignment (=)
if ( letterRead == 'm') { // m was the correct letter
cout << "Correct! You win!";
}
// if the character is after 'z' or it is before 'a'
// then the character was not a lower case letter a through z
else if ( letterRead > 'z' || letterRead < 'a') {
cout << "That was not a letter...";
}
// the character was a letter, but it was not the correct letter
else {
cout << "Wrong. You lose.";
}
Loops
Loops run code on repeat until a condition says "stop".
char continue = 'y';
// the first time, the loop will run since it starts with 'y'
while ( continue == 'y' ) {
//do something here until the user says 'n'
cout << "Continue? (y/n)";
cin >> continue;
}
Most loops simply count a number by one so you can go through all the possibilities in a range because loops are most useful for doing something to all of the elements in an array. As a result, a shorthand has been made. Compare:
While Loop | For Loop |
---|---|
int numbers[10]; |
int numbers[10]; |
Both loops essentially do the same thing. They print the random, uninitialized contents of the "numbers" array with a newline ('\n') at the end of each element.
Functions
Functions group operations into a name. You run the operations by saying the name of the function followed by (). You can give the function parameters by passing them between the parenthesis. Maybe most importantly, a function returns the results of its group of actions once it is done.
Note tha main is a function. It is run by default when you run the program. It also is an int. The value returned by main is actually an error code.
int myPow(int base, int exponent) {
// powers of 1 and negative powers will return 0, regardless of the base
if ( exponent <= 0 ) {
return 1;
}
int result = base; // create a place to store the result
//multiply the result by itself "exponent" number of times
for( int i = 1; i < exponent; i++) {
result *= base;
}
return result; //return the product of the exponent
}
int main() {
cout << myPow(5,0); // prints 5^0, which is 1
cout << myPow(1,5); // prints 1^5, which is 1
cout << myPow(2,4); // prints 2^4, which is 16
cout << myPow(2,5); // prints 2^5, which is 32
cout << myPow(3,3); // prints 3^3, which is 27
return 0; // there was no error
}
Conclusion
Congradulations! If you understood most of this, you are now qualified to do quite a few awesome things with an Arduino. Check out our tutorials for tricks with Arduino and using sensors with an Arduino.
There is still more to know, but it gets easier from here. In larger programs you will need to worry about where a variable can be accessed from. Also, classes and structures help you organize your data and are extremely powerful when you know how to use them.