Programming Principles

This page explains basic programming principles in terms that those new to programming can understand. If you are after specific examples rather than plain language explanations, there are links within each section.

What is a Variable?

A variable is a storage container that holds changing information. It has a name that does not change. This name is used to refer to the changing or variable information. A simple everyday analogy is a biscuit jar in a pantry.
jar.jpg chocolate.jpg plain2.jpg
This biscuit jar has changing contents. One day it might contain chocolate biscuits. Another day it might contain plain biscuits. The name on the front of the jar, however, does not change. If you wanted to ask someone to fetch the jar for you so that you could eat a biscuit, you could ask for it by referring to the contents -e.g. "Fetch me the chocolate biscuits". A person who has a brain as logical as a computer's would return empty-handed if there were plain rather than chocolate biscuits in the jar. Referring to the jar by the unchanging name on its front - "Fetch me the Biscuit jar" - avoids any confusion and means that you do not need to know what the contents are when you ask someone to fetch it for you. No matter what type of biscuits are inside the jar you will get your jar fetched and be able to eat its contents.

A variable operates in a similar way when you are writing code. The pantry is the computer's memory. If you want the computer to remember something you need first to create a container for it by declaring your variable name. This is the equivalent of creating a jar with a label on the front. In many cases you will also at this point need to specify what type of container you are creating. For example, is it one that will hold numbers or one that will hold text? What you are doing in this step is making sure that the jar has features that suit the type of thing you are going to put into it - like the way the shape of a spaghetti jar suits the storage of long tall pasta.You are also defining what types of actions can be done to the contents of your jar. For example, numbers can be used in mathematical equations while text cannot. Or, to continue our pantry analogy, spaghetti can be cooked in boiling water while biscuits cannot. In coding terms this is known as the data type. [Data Types in Arduino - see middle column]

Once you have given your variable its name and specified what type it is you can place data inside it. This piece of data can then be retrieved by using the variable name in your code. In the shorthand language of code, just typing the name of the variable e.g. BISCUIT is the equivalent of saying "Fetch me all the information inside the container named BISCUIT". [Variables in Arduino]

One important thing that you need to be aware of when creating variables is that the place in your code where you create your variable can determine how long that variable remains in the computer's memory. This is known as the scope of the variable. Usually variables created inside functions only exist while that function is running. As soon as the function ends they are forgotten. This saves computer processing power and is good practice for any data that is only needed short-term e.g. the current position of the mouse. This type of variable is known as a local variable. Variables created outside of functions are remembered the whole time an application is running. This type of variable is known as a global variable and is useful for storing or retrieving information that needs to be accessed from within multiple functions and/or stored for a long time e.g. the player's score within a game. [Scope in Arduino]

One key difference between our real-world biscuit jar and a variable in code is that a variable can only hold one piece of data. If you want to store multiple pieces of data you need to create what is known as an Array.

What is an Array?

An array contains multiple variables in a list. To continue our pantry analogy, an array is like a shelf that contains many storage jars each with its own changing content. An array has a name and this name is used in code to refer to the list. The individual variables within an array are referenced by numbers that describe their order in the list. By combining the name of the array with the position number of an element within it you can store and retrieve individual variables.


One important thing to remember is that the position numbers for items within an array usually start at zero. So the first element is zero, the second is one, the third is two and so on. For example in the situation described in the picture above, the third jar on the shelf would be referenced by using the array name "secondShelf" and the position number "2".

As described in the scope discussion above, arrays can be local or global depending on where you create them. [Arrays in Arduino]

What is a Conditional (if/then/else)?

Conditional statements allow you to program different responses for different conditions. In plain language the basic statement goes:
If condition A has occurred then do action B

You can program multiple responses to a condition:
If condition A has occurred then do action B, action C and action D
These actions will be carried out in the order that you write them in your code. [If in Arduino]

You can also combine the basic statement with an else to create two responses - one for if the condition has occurred and one for if it hasn't:
If condition A has occurred then do action B
else if condition A has not occurred
then do action C

In the simplified language of coding the single word "else" is usually used to represent the whole concept "else if condition A has not occurred". However in your head, you should always think of it as the whole concept so that you don't misinterpret what is going to occur.

You can also add a second condition after the else as in:
If condition A has occurred then do action B
else if condition A has not occurred
See if condition C has occurred and if it has do action D

And finally, you can daisy-chain multiple conditions each separated by an else as in:
If condition A has occurred then do action B
else if condition A has not occurred
See if condition C has occurred and if it has do action D
else if condition C has not occurred
See if condition E has occurred and if it has do action F
else if condition E has not occurred
See if condition G has occurred and if it has do action H...

As you can probably imagine, you need to be very careful about the flow of your logic when you are creating complex conditional statements like the one above. Otherwise you are liable to get responses that you do not expect. In most coding languages conditional statements are formatted so that the statements are progressively indented from first to last. This helps you to see which condition will override another. [Else in Arduino]

The conditions within conditional statements test to see if something is true or false. Usually the thing that they are testing is the value of a variable e.g.
Does my variable called firstName equal "Bob"?
Is the variable myScore greater than ten?
Is the value of my light sensor that is stored in the variable sensorData less than 50?
Is the variable sensorData not equal to zero?
The elements within code that represent the concepts of "equal to", "greater than", "less than", "not equal to" etc are known as operators and specifically as comparison operators. [Operators in Arduino - scroll down left column]

Most languages have another way of writing complex conditional statements that is known as case or switch case. A case statement allows you to begin with a single variable and then write multiple case statements that check to see if it equals a certain value and if it does then execute a specified action. The way that case statements are written in code makes them easier to write and read when you want to code different responses for multiple values of a single variable.

In plain language the case statement goes:
Look at the value of my variable nameofVariable
In the case where nameofVariable equals B do action C
In the case where nameofVariable equals D do action E
In the case where nameofVariable equals F do action G
else if nameofVariable doesn't equal B,D or F
do action H

[Switch Case in Arduino]

Conditional statements are an important tool that will enable you to program responses to variable input e.g. human movement or environmental factors like light and temperature.

What is a Loop?

A loop is used in code to perform actions that you need to happen over and over again, for example, checking the reading from a sensor. The actions inside a loop will be carried out one by one. After the last action in a loop is completed the loop will return to the first action and begin carrying the sequence of actions again.

Sometimes you want a loop to continue operating for as long as your application is running.[Loop Function in Arduino] Other times you want to give the loop a defined end point or break out of the loop if a certain condition occurs.

To define an end point you create a loop with a counter and a defined number of times to run. This type of loop , known as a "for loop", will count how many times it has run its list of actions and will stop looping when its counter number matches its defined end point. [For Loop in Arduino]

To create a loop that only runs if a certain condition is met, you need to create what is known as a "while loop". The while loop checks to see if a specified condition is true before it executes its sequence of actions. For example, it might check whether the reading from a light sensor is greater than zero (i.e. the room is not pitch dark) and only carry out its actions while this state is happening. [While Loop in Arduino]

What is a Function?

A function is a container with a set name that you can put a sequence of actions into. Calling the name of a function causes the actions inside it to be carried out. Functions are the workers within your code.

In a work team, like say that on a film set, each worker has a specific role to play and that role involves a specific set of tasks. The make-up artist puts make-up on the actors. The sound recordist records the sound. The camera operator operates the camera. These roles are very distinct and do not overlap. When the director calls for "makeup" the makeup artist springs into action. When he calls "roll sound" the sound recordist springs into action. When he says "roll camera" the camera operator turns on the camera and frames a shot. When they are not needed these workers wait, prepared and ready to be called. This modularization of roles and tasks enables a film shoot to run quickly and efficiently.

Functions perform the same way within your code. You write each function to perform a specific set of related tasks and you give the function a name that represents the role that it performs within your code. When you need those tasks performed you call the name of the function and it springs into action.

Like the members of a work team, sometimes functions need to communicate with each other. They might need instructions about where, when or with what they should perform their tasks. They might, for example, be a function that adds numbers together and need to know which two numbers the function is adding together. These instructions that you give a function before it performs its tasks are usually referred to as parameters or arguments.

Functions can also communicate with each other after they have completed their tasks. For example, if they have added two numbers together they might send a message saying what the result was. In coding terms, this type of communication is described with the word return, as in "the function has returned the value 5".

When you create a function you want to write it so that the function can perform its role in multiple contexts because this makes it more useful. You don't want to write a function that adds two numbers together and specify that those two numbers are 2 and 4 because this would make this function only useful when you needed to add 2 and 4. It would be like having a makeup artist that could only apply red lipstick or a camera person who could only frame close-ups of dogs.

Instead you want to write a function so that you can send the function any two numbers to add together. This means that you need to use variables to represent the changing information within your function definition. You use variables to represent both the incoming parameters and the outgoing value that the function returns.

In very verbose plain language, then, a function is usually defined like this:
This is myFunctionName and in order to perform its tasks it needs parameter1VariableName and parameter2VariableName
Here is the beginning of the tasks that this function performs
perform action A with parameter1VariableName
perform action B with parameter2VariableName
put the result of action B into a new variable called resultofActionVariableName
return a message giving the value of resultofActionVariableName
Here is the end of the tasks that this function performs

And in plain language if you wanted to then make this function perform its tasks you would go:
Call myFunctionName and give it specificParameter1 and specificParameter2

If you wanted to make this function perform its task and you wanted to record the result it returns you would go:
Create a new variable called functionResultVariableName
Make functionResultVariableName equal what is returned when myFunctionName runs with specificParameter1 and specificParameter2

[Declaring Functions in Arduino]

As with any variables, the parameter variables and result of action variables in your function definition need to be given a specific data type so that the computer knows what type of containers to create and what type of actions can be done to them. [see variables above] [Data Types in Arduino - see middle column]

The picture below shows an example of a function called myAddFunction written in Arduino code that performs the specific task of adding two numbers together and returns the result of the addition.

Note that the curly brackets represent the lines in the plain language version that say "Here is the beginning of the tasks that this function performs" and "Here is the end of the tasks that this function performs". You need to make sure that you do not delete one of these by mistake when you are editing your code or else you will get an error.

Note also the way that every variable and even the function itself are carefully data typed as an int (which means integer or number with no decimal places).
[See the every line of the code examples above and below explained in plain speak]

Here is how you would then call this function, pass it some parameters and record the result in a variable:


In Arduino code these two lines would, for example, be placed inside one of the two set structural functions required in an Arduino sketch i.e. either the Loop function or the Setup function.

The Loop and Setup structural functions in Arduino are an example of the type of predefined functions that exist in most programming languages. These predefined functions perform common tasks like printing text, playing audio or reading the time. [Predefined functions in Arduino - see right column and also left column under Structure] The addition function example described in the pictures above is a custom function because its name and tasks have been defined by you, the coder.

© Brigid Costello, EMPA, FASS, UNSW All Rights Reserved 2010