Arduino Programmation Basics

Arduino, Home Automation, Robotics5 Comments

You Are Here:, Home Automation, RoboticsArduino Programmation Basics

 

In this tutorial, we’ll see the basics of the Arduino programming langage. Once you understand this post, you will be able to understand all the other posts/tutorials on this website, you will also have algorithmic skills and it will be easy for you to learn other programmation langages.

If the Arduino is not clear for you, I advice to look at the Essential of The Arduino.

Introduction questions.

  • What is a programming langage ?

Like English, French or Spanish, a programming langage is a way to communicate with… a computer. Like any other langage, a programming langage have syntactic rules. The problem is that when you try to talk to a stranger with another langage, the person will try to understand you. With a programing langage, if you don’t respect carefully those syntactic rules, the program will not be executed. Anyway there is a really cool advantage : all programming langage are similar. For example, if can code with Arduino, you can easily learn PHP without any trouble.

  • How does a program works ?

A program (or code) is read from the top to the bottom. It is constituted of instructions and conditions that keep the program dynamic. When we’re executing the program, it is compiled (translated in binary langage) for the computer. When compilation is ended, the program is working.

  • Do I need to be good at maths to code ?

Definitely not. If you know how works sum, subtraction, division and multiplication, then the wonderful world of coding belongs to you.

  • But, where is the difficulty ?

The difficulty is to imagine how to automate a task and think like a machine. Convert a human activity to instructions. Example : a human can easily detect motion in front of him. How to give this capacity to a computer ? How to translate this in a programing langage ? Those are the type of questions that coders are confronted to.

I. Variables, Constants and Types

Admit that your goal is to set up a program that gets the temperature of a room. Where will go this information ? That’s the role of variables and constants to store information/values.

Admit the room temperature is 27°. In Arduino langage we would write like this :

int temperature = 27;

There, int means Integer. We precise to the Arduino that the kind of data we want to store is an integer (27).

temperature is the name of the variable that I just created, I can call it differently; you simply need to know that the name of a variable mustn’t contains spaces or special characters like “é” or “à”.
= 27 affects the 27 number to the temperature variable. This means that if we solicit the temperature variable, the Arduino will indicate 27.

You probably noticed a semi-column at the end of the variable declaration. Retain that you need to put a semi-column at every expression you’ll write in the Arduino langage. That’s why you’ll make some mistakes at the beginning and that’s perfectly normal, it’s an habit to have.

We talked about variables and constants, here temperature is a variable. That means that we can modify it at every moment in the program. To do this, it’s really simple, admit the temperature is now 31° we would write like this :

temperature = 31;

The temperature variable is now equal to 31.

But if we had declared temperature as a constant, not a variable, we would not be able to modify it. To declare a constant, you only need to add const before the type.

const int temperature = 31;

Why initiate constants while I can only declare variables and just not modify them into the code ?

You can. But it’s about security and optimisation. To make it simple, when you indicate to the Arduino or a computer in general that you are using a constant (that your data will not be changing), then the compiler can optimize your code and make it more efficient, faster. It’s obvious that for the little programs that we are making, the difference is not noticeable. But in big programs which need power, it become crucial.

In coding, you must have the habit to be precise in everything you’re writing, that way, you’ll be able to write a non ambiguous and efficient code.

Talking about precision, you noticed that we also indicated that our variable was an integer. Integer is a type of data, there is multiple type of data in the Arduino langage :

  • Integer

Simply a number, we delcare an integer with int

int myInteger = 556;
  • Decimal

Simply a decimal number, we declare it with float

float myDecimal = 47,5678;
  • Characters

This is a bit special this time, we declare it with String. An example :

String myChars = "Hello";

When you initiate characters (strings), it must be between quotes like the example above. If I didn’t have put quotes “” to my string “Hello”, my program could understand that it was a reference to a variable named Hello.

  • Boolean

The boolean type is a bit special, it accepts only two values : true or false.

boolean myBool = true;
boolean myOtherBool = false;

Why ? Because it will be very useful in tests and conditions, you will understand later. Simply consider that true and false corresponds to the binary of computers 1 and 0. They are very importants.

II. Maths, Print and Concatenation

In this part, we will be looking at three important elements you will be using when you’ll write some code.

  • Maths

Don’t worry, we will not do hard maths, I will simply show you the basics 😀

Admit you have the temperature of three rooms in your house and that you want to have the average temperature of your house. Let’s start by initiating our variables :

int tempBedroom = 27;

int tempKitchen = 25;

int tempLivingroom = 30;

Let’s calculate the average temperature :

int sumOfTemps = tempBedroom + tempKitchen + tempLivingroom;

Effectively, we can create a variable and affects the value of another variable or like here : the sum of multiple variables. For the sum we use the sign “+”, the subtraction “-“, the multiplication “*” and division “/”.

So, the average would be :

int averageTemp = sumOfTemps / 3;

We can improve this code :

int tempBedroom = 27;

int tempKitchen = 25;

int tempLivingroom = 30;


int numberOfRooms = 3; //We put a variable which contains the number of rooms.


int averageTemp = (tempBedroom+tempKitchen+tempLivingroom) / numberOfRooms;

(What’s beside the “//” is named a comment, very useful if you forget how works an instruction or if you share your code with some people. Comments are ignored in the code execution).

So, the result would actually be : 27,333333333…

But the value of tempMoyenne will actually be 27. Why ? If you noticed, we initiated our variables as integer. So a division of integer will give an integer. To have a decimal result, you need to declare our variables as float.

We would write :

float tempBedroom = 27.0;

float tempKitchen = 25.0;

float tempLivingroom = 30.0;


int nomberOfRooms = 3; 


float averageTemp = (tempBedroom+tempKitchen+tempLivingroom) / nomberOfRooms;

Now that we have our average temperature, it would be good to show it somewhere.

  • Print

There is a lot of possibilities to show or transmit information somewhere. You can put it on a LCD screen or simply on your computer screen or on a server.

You will “Print” the data on your screen.

When we work with the Arduino and Print, we display data in the : serial monitor.

The serial monitor is a way to live communicate with the Arduino. It’s a window with an entry and an output. To open the serial monitor, open the Arduino IDE, connect your Arduino, make sure it’s well recognized by the software and click on the magnifying glass on the top right of the interface.

Let’s try :

Open a new sketch and write this :

float tempBedroom = 27.0;

float tempKitchen = 25.0;

float tempLivingroom = 30.0;


int nomberOfRooms = 3; 

float averageTemp = (tempBedroom+tempKitchen+tempLivingroom) / nomberOfRooms;

void setup() {
  Serial.begin(9600);
  Serial.print(averageTemp);
}

void loop() {
  
  // put your main code here, to run repeatedly:

}

You can notice in the setup() function, new instructions.

The Serial.print() is simply the Print. Between those brackets we put averageTemp which is the variable that we want to show. We can put between those brackets whatever we want. Very useful for testing.

The Serial.begin() is mandatory and indicate the Arduino that we will use its serial monitoring service. We put 9600 inside. This is, in fact, the rate of flow where the data will pass. Here its 9600 bytes per seconds.

Upload this code to the Arduino and open the serial monitor. When the upload is complete, you should see the average temperature is the monitor.

Like said above, print is a powerful tool for testing and debugging. You can put it everywhere to verify that your variables got the value that you wish there have.

  • Concatenation

Concatenation simply stands for fusion of two strings or more.

Example :

String myString1 = "Hello ";
String myString2 = "world!";

String concatString = myString1 + myString2;

By yourself, try to write a little program which shows in the serial the variable concatString. The solution is below :

String myString1 = "Hello ";
String myString2 = "World!";

String concatString = myString1 + myString2;
void setup() {
  // put your setup code here, to run once:
 
  
  Serial.begin(9600);
  Serial.print(concatString); //Prints "Hello World !"
}

void loop() {
  
  // put your main code here, to run repeatedly:

}

III. Control structures

A program without control structures is a non-dynamic program.

The few programs we wrote until now are perfect to teach you coding but are a bit boring. Programming goal is to build an autonomous program that take decisions depending of the provided date. In this part, we will be looking at the 4 fundamentals control structures.

  • If… else

If it’s raining, I go out with my umbrella, otherwise (else) I simply go out.

La structure If…else correspond tout simplement à une condition : en anglais if…else veut dire si…sinon en français.

The if…else structure simply corresponds to a condition.

Unfortunately, you must learn a little operators table :

operators

 

This table will be used for every control structures.

NB : When we are testing the equality we are using a double equal instead of a simple equal, it’s because the equal sign is already used when we initiate a variable.

Here is how it works :

if

 

In this example, we test if 10 is higher than 5 or not. If it’s true, we execute what’s inside the green curly brackets. If it’s false, then the code between the yellow curly brackets is executed. We test if what’s inside the brackets is true or false, you remember the boolean type who stands for true or false values. You can now understand the utility of this type.

Because 10 is higher than 5, the condition is true and the code between the green curly brackets is being executed. What’s inside the else is ignored.

Of course, testing if 10 is higher than 5 is not very exciting, here is a concrete example of what we can do with a if…else with home automation :

int tempLivingRoom = 0; //Affects 0 because we do not know the value at first.


void setup() {
  
  Serial.begin(9600); //Open the serial

}

void loop() {

tempLivingroom = getTemp(); //tempLivingroom will be equal to the actual temperature.

if (tempLivingroom < 20){ 

Serial.print("It's cold, let's switch on the radiator.");
//Here, we put the command to switch on the radiator. 

} 

else { 

Serial.print("Temperature is reasonable, we do nothing.");
//We do nothing.


}

}

In this example, we retrieve the temperature and we analyse it : if the temperature is inferior to 20 then we execute what’s inside the { } otherwise we execute what’s inside the else {} . Thanks to the main loop of the Arduino, it’s gonna check the temperature while it’s on.

One if…else, ok but  can we put more conditions ?

Of course, thanks to the else if.

The else if is simply a repetition of if adding more conditions, here is the same example with else if.

if (tempLivingroom < 20){ 

Serial.print("It's cold, let's power the radiator.");
//Here, we put a command to switch on the radiator.

} 

else if (tempLivingroom == 25) {

Serial.print("Good temperature, shut down the radiator");
//Here, we put a command to switch off the radiator.

}

else if (tempLivingroom > 25) {

Serial.print("Really hot, switch on the AC");
//Here, we put a command to switch on the AC.

}

else { 

Serial.print("Temperature is good.");
// We do nothing.


}

Else…if adds as much conditions as you like, because you can duplicate it depending on your will.

On the other hand, if you have a lot of else if, you should think about using another control structure called the switch.

  • Switch

The switch is an optimized if…else allowing you to have more conditions faster :

switch (yourVariable) {   //We test a variable, (string, number...) like with if...else
   case 1:
      Serial.print("yourVariable is equal to 1");
      break;

    case 2:
      Serial.print("yourVariable is equal to 2");
      break; 

    case "Hello": 
      Serial.print("yourVariable is equal to "Hello");
      break; 

    default: 
      Serial.print("yourVariable is not equal to any of those cases");
      break; 
}

So, between the switch brackets, we put the variable to test, then we enumerate cases. And just after case we write what our variable could be equal to.

You probably noticed the default case in our switch. It’s in fact the else equivalent in the if…else structure. This means that if no case is verified, then what’s inside the default case will be executed.

NB : default is fully optional, you’re not obligated to put one in a switch.

We can also note that there is an instruction named break. We are “breaking” the switch. In fact, this is very useful because it indicates to the code that we want to go out of the switch. You must know that the switch will test every cases, even if a case has been verified before.

  • While

While it’s raining, I don’t go out.

The control structure while is a loop which repeats one or more instructions while the condition you’re indicating is true.

Admit that we initiate this :

int myVariable = 0;

while

Like the if…else, we indicate the condition to test between the brackets.

Before the while we indicates that myVariable was equal to 0. In the while, we verify :  does myVariable, (0) is inferior or equal to 10 ? Yes, the condition is true, then the code between the while curly brackets is ran while it’s true.

What I’ve wrote in the while loop will allow us to get out of this loop.

There is : myVariable = myVariable + 1;

We affects to myVariable its own value plus the number 1. 0+1 is equal to 1, maVariable will be equal to 1.

While is a loop so it will execute the code while the condition is true. So the While will verify again if myVariable is inferior or equal to 10 and will repeat the code in consequence.

After a moment, myVariable will be equal to 11 (superior to 10 lol), it will invalidate the condition (becoming false) and go out of the While loop.

NB : If myVariable was equal to a number superior or equal to 11 in the beginning of the program, the While loop would be ignored (because 11 > 10 lol). We enter in the loop only is the condition is true.

You’ve understand, While is simply a loop with the settings you decide to put. That’s a powerful tool but sometimes dangerous. In fact, if I had not incremented myVariable, we couldn’t be able to get out of this loop; that’s what we call an infinite loop and you must escape this in all of your programs because it repeats until your program or worse : your computer crashes.

When I started programming, I only used the While loop because it was really simple to use but sometimes I used to make my program crash. There is another loop that looks like a While, but less risky. That’s our last control structure, it’s the For loop.

  • For

Before starting using this loop, let’s talk about incrementation.

Incrementation is the action to add a number to a variable. The opposit is called decrementation and its about subtracting a number to a variable. Incrementation and decrementation are usually used with the number 1. We saw that we could increment that way :

myVariable = myVariable + 1;

But you must know that coders are lazy (like me hehe) so we can reduce this expression to this :

myVariable++;

Same with decrementation :

myVariable--;

Now that you know everything about incrementation, let’s go on the For loop :

With the While we :

  1. Initiated a variable.
  2. Placed a condition between the While brackets.
  3. Incremented our variable in the loop so that we can get out of this loop.

Those three steps was separated. With for everything is on the same line !

for

Inside the yellow square we initiate our variable, inside the green square we indicate our condition (like if…else and while), then inside the blue square we indicate the incrementation/decrementation. You may know but if you forget : incrementation will apply each time the loop loops.

And inside the for loop, we put the instructions to repeat.

But why would we use a While loop instead of For ? You said that is was more safer and compact ?

Simply because with the While loop, everything is set up manually, then we are more free to do something precise.

Now that you know those 4 control structures, I strongly recommend you to test them until you understand how it works. You have all the necessary tools (concatenation, print…) to test those control structures.

You’ll probably not fully understand the interest of all of this and that’s perfectly normal. Everything is not to perfectly memorize, you will “learn” with practice. While you’ll be in front of some issues which can be solved by code, those control structure will pop in your head and this tutorial will permit you to understand how to manipulate them precisely.

IV. Fonctions

Coders are lazy. We created the copy and paste, but better than that, we created functions.

Without knowing, until now, some instructions that we’ve been using are in fact, functions. I used the word “instruction” to make it easy.

For example, Serial.print(), Serial.begin() are functions. Setup() and loop() are functions too. Moreover, those are fundamental functions.

Finally, what’s the point of a function ?

Let’s take an example, admit that you have to write 10 times the same 300 instructions. 10 x 300 = 3000 lines of code. That’s too much and unreadable. What we gonna do is create a function where we put those 300 instructions, and in our program we call this function 10 times.

The goal of a function is to not write an infinite number of lines of code and to keep your program readable. Imagine if we have to rewrite all the lines of code of the Serial.print() function every time we wanted to use it ? Functions are like “micro programs” that you call in your main program.

To simplify, we will say that there is two types of functions, silents and noisy functions.

  • Silents functions

Silents functions are those which, when we call them, run the code they contains and without showing anything, we said that they return nothing.

Silent function example :

checktemp

We’re using void to initiate a function which returns nothing (silent).

We named the function checkTemperature.

We put two brackets with nothing inside, we will see later what’s the point of them.

We open the curly brackets where we’ll put instructions that our function will contain.

Then, when we want to call our function is our code, we write : checkTemperature(); and the instructions that are inside of the function will be executed. Pretty cool right ?

 

We can even set up more complex functions :

radiatorornot

You can put everything you want in a function.

  • Noisy functions

Noisy functions, in contrary of silents ones, return data.

We want to create a function which will permit to add two numbers :

sum-function

Look carefully, we’ve replaced void by another type, it’s the type the function will return. We put int because the data our sum will return is an integer.

Next, we name the function (here, sum).

Remember we talked about empty brackets ?

Between the brackets we put what we call arguments and this will allow functions to be more interesting. In fact, with arguments, our function will be able to work according of variables given by the user. We can put as many arguments as you wish and with any type.

Here, we initiated two arguments. Two integers, number1 and number2 (be carefull to separate them with semicolumn). number1 and number2 are numbers that our function will add.

Inside of the function we initiate an integer which is called result which will contains the result of the sum. So we add number1 and number2, those variables will contain what the user set. The result will vary depending of the values set by the user.

 

Next, we have the return. Return is the value that the function will return, but what does that mean ?

Simply, the function will have the value of what it returns. If the variable result is equal to 4, so, the addition function is equal to 4. That’s why you specify the type of function at the begining.

We oftenly affects a noisy function to a variable, like this :

int myNumber = sum(2, 3);

myNumber will be equal to 5. Note that we can also give variables as arguments, but they must fit the argument type.

Finally, we said that a program is read from the top to the bottom, functions must be initiated before you use them.

Code example using function :

int number1 = 10;
int number2 = 12;

int sum(int firstNumber; int secondNumber){
    
    int result = firstNumber + secondNumber;

    return result;

}
void setup() {

  Serial.begin(9600);
  int mySum = sum(number1, number2);
  Serial.print(mySum);
   
}

void loop() {
  
  // put your main code here, to run repeatedly:

}

I strongly suggest you to test by yourself Arduino functions to fully understand how they are working. Even if you don’t fully understand the point to have functions in your code, it’s important for the next tutorials and projects how to manipulate them. Also, do not hesitate to read this tutorial again and again until you understand, if it’s not enough, feel free to leave a comment below, I’ll be happy to answer your problem and solve your problem 😀

About the author:

5 thoughts on “Arduino Programmation Basics

  1. Hey there, I think your website might be having browser compatibility issues.
    When I look at your website in Opera, it looks fine but
    when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that,
    fantastic blog!

Leave a Reply

Your email address will not be published. Required fields are marked *

Top