Make it for less logo

Coding basics

In this section we will talk about the basic parts of a program so that we can use them to write our own programs later on.

Two important things to know

Comments

The first thing that we need to talk about are comments. A comment is some explanatory text that programmers leave to explain how some code works or provide extra information. Comments do not get turned into instructions for the microcontroller and can say anything. Commenting code is a good practice to get into and can be a massive help when going over old code in large projects. There are two ways to write comments. The first is called a single line comment and as the name suggests it is used to comment out a single line in the code. In order to use a single line comment you just need to go to the beginning of a line and type //.

//This is a single line comment!

Another option for commenting is called the multi line comment. In a multi line comment there is a beginning and an end. The comment is started by typing /* and ends with */.

/*This is an exmaple of a multi line comment! Look, its on multiple lines! Imagine that!*/

Anything in between the /* and */ will be commented out of the code. Single line comments are good for making quick notes and multiline comments are good for leaving detailed descriptions.

Variables and Data Types

When writing a program there are things we want to keep track of and information that we want to be able to access later on. In order to do this we use something called variables. They are just what they sound like, something that can vary throughout the life of the program. In order to declare variables they need two things, a data type and a name.

What is a data type?

When working with computers everything at the lowest level is 1s and 0s, but by telling the computer how to interpret those 1s and 0s we can decide if they are numbers, letters, etc. This is what the data type is and the simple ones we will need are as follows

When we create variables we give the data type so the computer knows what kind of data we want to put in our variable. The second thing our variable declaration needs is a name. We give it a name so that later on we can get to the information our variable is holding onto for us. The name can be almost anything we want. There are a few rules however. The first is that the variable cannot start with a number, and the second is that the variable must not be from a set of special words. There are a few of these special words(called reserved words) that we will talk about more later, but don't worry. If you try to use a reserved word as a variable name the program will not upload and will tell you where you used a reserved word incorrectly.

image of var name error

Note

capitalization matters, myVar is not the same as MyVar or myvar

We declare a variable like this

int aNumber; char aLetter; String aSentence;

Now that we have declared our variables we can set them to be equal to whatever we want for example if we wanted out aNumber variable to equal 1 we would type

aNumber = 1;

If we wanted aLetter to equal a we would type

aLetter = 'a';

If we wanted our sentence variable to say Hello World! we would type

aSentence = "Hello World!";

Now our variables are equivalent to the values we set them equal to.

Note

Characters always have single quotes(') on each side and strings always have double quotes(“)

We can also set the type name and initial value all in one line like this

int aNumber = 1; char aLetter = 'a'; String sentence = “Hello World!”;

Now that we have our variables we can access and modify the data inside them whenever we want.

Math operations

There are several mathematical operation we can perform on integer and float variables.

There are a few more advanced operators that we will talk about when we need them. Something important to know is that when performing operations on integers the result will always be and integer so 1/2 will not equal 0.5(a float). In order to turn the value into an integer the decimal and everything after it will be dropped so 1/2 = 0.5 drop the .5 and it equals 0. If use a float on either side of the operation the result will be a float and the decimal will be preserved 1.0/2 = .5 Make sure that any variable you will be saving the result into is the correct data type or the same truncation will happen

int a = 1.0/2; //a = 0 float b = 1.0/2; //b = .5 float c = 1/2; //c = 0 additionally there are special operators to increse, decrease, multiply, and divide values, they are int a = 1; a++; //a = 2 int b = 1; b--; //b = 0 int c = 1; c *= 4; //c = 4 float d = 1; d /= 2; //d = .5 int e = 1; e += 2; //e = 3 int f = 1; f -= 5; //f = -4

Arrays

Sometimes we may want to save a couple of values under the same variable name because they are related in some way. For example, imagine we have a set of 10 temperatures. We don't want to create 10 variables to track each one because they are all related to each other. Luckily we have something called arrays. Arrays allow us to save a set of different values all under one variable name. We declare an array in the same way as a regular variable but with one difference. After we declare the name of the array we put square brackets[ ] after it. Inside the square brackets we need to specify how many values are going to be stored in our array. For our temperature example it would look something like this

float temps[10];

Now we need to set each of the values in our array. In order to access some particular value in our array we just have to type the name and then the index of the value we want into the square brackets after it. For example if we wanted the first value in our array we type

temps[0]

What!! 0??

Yes 0, the first element of an array is always element 0. This may seem confusing at first but eventually you will remember that this is always the case. Its also important to know that the last element of the array is at the size of the array - 1. So in our 10 element array the values are in positions 0-9.

So now we can set all of temperature variables

temps[0] = 65.6; temps[1] = 45.6; temps[2] = 67.6; temps[3] = 55.6; temps[4] = 78.2; temps[5] = 65.56; temps[6] = 15.4; temps[7] = 89.9; temps[8] = 23.6; temps[9] = 43.1;

Now we have all of our temperatures saved in one place.

Note

If you try to access a value outside of the size of the array there will be an error and the program will not work

temps[-1] = 42.5; //error - 1 is less than 0 temps[10] = 56.6; /*error our array goes from 0-9 and 10 is out of range*/

The final thing to know about arrays is that they can be declared and have their values set in one line just like variables. The method is a little bit different however. It looks like this

float temps[] = {45.6,34.7,12.8,24.9};

This creates our array of temps and automatically sets its size to 4 and puts our values in curly brackets into the array.

Functions

Functions are an incredibly powerful tool for us. They allow us to write code once and then use it as many times as we want by “calling” the function. Functions, like variables, get a data type and a name. When we use functions, the data type we assign to them is whatever kind of data we want them to return to us after we call them. Functions have an extra data type called void. The void data type is used by functions to say that we don't want the function to return anything. It should just run the code inside of it when we call it. The data type for a function can be any of the ones we talked about with a variables but if it is anything other than void the function will need to return a value which we will discuss in a minute. When we want to declare a function we type it out like this

void myFunc(){ //Code to run here }

Another feature of functions is that we can pass information into our functions through something called parameters. If we want to give our function parameters instead of leaving the parentheses after the function name blank, we can add in variable declarations separated by a comma. For example

void myFunc(int a, String b){ //Code to run here }

In this example code we can see that we have declared two variables for our function, an integer called a and a string called b. We can have as many or as few parameters to a function as we want. These variables are special to our function and can only be used inside of it.This is because of something called Variable scope which we will talk about after we finish with functions. The next important thing to remember about functions is that if they have a data type other than void then we need to return something from the function. We do this with the special word “return”. Whatever we put after the word return in our function will be the value that is returned when we call our function.

int add(int a, int b){ return a+b; }

In this example function we take in two parameter variables a and b and then add them together and return the results. The last thing we need to talk about with functions is actually calling them. For functions with no parameters all we have to do is type the name of the function followed by open and closed parentheses.

void myFunc(){ //do something } myFunc(); //Calling myFunc

If our function has parameters it is basically the same but we need to pass in the values we want to set our parameters to

void parameterFunc(int a, int b){ //do something } parameterFunc(1,2); //calling myFunc with a = 1 and b = 2

Whenever we use this function whatever comes out of it will replace the function call

int sum = add(1,2); //sum = 3

In this example the variable sum gets set to the return value from add which in this case is 3.

Note

Variables can be used in place of any new values for parameters

int a = 1; int b = 2; int c = add(a,b); //c = 3

Variable scope

We touched briefly on variable scope (usually shortened to just scope) when discussing functions. Essentially what variable scope means is that not all of our variables can be used everywhere in our program. If we have a variable we want to be able to access at any time we need to create what is called a global variable. A global variable is basically just a variable that is not declared inside of any function. If we declare our variable in a function or as parameters then using those variables is limited to just the “scope” of that function

int a = 1; void func1(){ int b = 2; } void func2(int c){ c = 5; } void useVars(){ a = 2; //works because a is global B = 3; //does not work because b is local to func1 c = 7; //does not work because c is local to func2 }

As you can see the variable a we declared outside of any function can be used anywhere in the program but the variables b and c declared inside of functions can only be used in those functions.

Conditions

Before we can talk about the next few sections we need to go over conditions. Conditions are Essentially questions that will evaluate to true or false. Some examples of condition are

Sometimes we may want to check multiple conditions at once, to do this we use and, and or statements. With and a statement will be true only if the values on the left and right are true. With or a state will be true if the values on the left or right are true. To use and in our conditions the symbol is && and to use or the symbol is ||

a<b && b<c; /*True only if a is less than b and b is less than c*/ a<b || b<c; //True if a is less than b or b is less than c

look at the table below to see all the possible outcomes of and and or

AND (&&) RIGHT
TRUE
RIGHT
FALSE
LEFT
TRUE
TRUE FALSE
LEFT
FALSE
FALSE FALSE
OR (||) RIGHT
TRUE
RIGHT
FALSE
LEFT
TRUE
TRUE TRUE
LEFT
FALSE
TRUE FALSE

There is one one symbol important when working with conditions which is the not operator. THe not operator is written as ! and turns any true value to false and any false value to true.

if(a<b); //works if a is less than b if(!(a<b)); //works if a is not less than b

Note

Conditions will evaluate from left to right so for example

a<b && b < c || c == d

a<b will be evaluated first and then its result will be anded to b < c and the result of that will be ored with c==d. If we want to evaluate b<c || c==d separately we can put them in parentheses

a<b && (b<c || c==d)

If/else if/else

The next concept we will talk about are if statements. If statements allow us to make decisions in out code based on the values of some variables. To do this we use the keyword if followed by parentheses and in the parentheses we define a condition. If the condition evaluates to true the code inside of the if block will run otherwise it will be skipped over. Now for an example imagine if we wanted to turn a light on if we have a variable greater than 5, to do this we if statements we write

if(myVar > 5){ turnLightOn(); }

Now what if we wanted to turn the light off if our variable is less than 5? We could either right another if statement or we can use the else keyword like so

if(myVar > 5){ turnLightOn(); }else{ turnLightOff(); }

Anything inside of the else block will only happen if the if condition is false.

Note

Notice that the else keyword does not get parentheses

Now what if we want the light to blink if the var is equal to 5? We can put more conditions between our if and else with else if

if(myVar > 5){ turnLightOn(); }else if(myVar == 5){ blinkLight(); }else{ turnLightOff(); }

We can have as many else if statements as we want and they will be evaluated from top to bottom.

Note

Only one if/else if will run when they are stacked and the else statement will only run if all if/else if statements are false

While loop

Sometimes we want our programs to run something multiple times. For example lets say we want to blink a light on and off 50 times. We could right our code like this

lightOn(); lightOff(); lightOn(); lightOff(); //continued 50 more times

But that would take up a lot of room and be annoying to type out. The solution is called a while loop. Setting up a while loop is similar to an if statement.

while(a < b){ //do something }

As you can see we put the keyword while followed by a condition in parentheses and then a block of code to run. The difference is that with a while loop after the code in a block is run execution jumps back up and checks the condition again. The cide will do this over and over again until the condition evaluates to false

NOTE

It is possible to create infinite loops which will make your program stall and be unable to continue

Let's look at our light example again. If we wanted to turn the light on and off 50 times we could right it like

Int a = 0; while(a < 50){ lightOn(); lightOff(); a=a+1; }

This loop will run and increase the value of a by one every time it does. Eventually a will be greater than 50 and the loop will stop running. This is the power that while loops provide us.

For loop

The other kind of loop we need to talk about is called a for loop. A for loop is used traditionally to go through an array or do something a number of times. Declaring a for loop looks like this

for(int i = 0; i < 50; i = i + 1){ Do something(); }

You may notice that our for loop has some other parameters in addition to the condition. In the for loop declaration we define an integer variable i, the condition, and then increment i by 1. Looking back at our while loop example you can see that it is doing the same thing but is much cleaner and does not require messing with the incrementing variable inside of the code block.

Next Steps

Congratulations!! You now have all of the information to start coding!! click here to learn how to use what youve learned to program an arduino