First tutorial: Software and Hardware
1 Introduction.
These are the Arduino Tutorials for the Studio 4, at KTH School of Architecture. In the following tutorials we will look at the basics of programming using the Arduino micro-controller platform.
A micro-controller is a small computer that can easily interact with input and output peripherals such as sensors and actuators. Daily environments, from cars, shops, offices or homes, include large number of micro-controllers that may regulate and control light, access, ignition of motors, open doors or run washing machines, toasters and most electric appliances at home.
Arduino is a platform consisting of software and hardware that allows to easily prototype with micro-controllers. It was developed within the context of interaction design, and thus it is well suited for designers, artists and architects, or anyone that may not have an initial deep knowledge of programming and electronics. More generally, Arduino’s modular hardware allows to easily add and test extensions or “shields”,easing the process of testing alternatives and quickly developing working prototypes.
You all should have your Arduino Uno boards, a USB programming cable, and some bits of electronic components lying around (some LEDs and resistors, perhaps some servo motors, potentiometers and even proximity sensors). We will then first proceed with downloading and installing the Arduino IDE (Integrated Development Environment) software.
The best place to get a good overview of Arduino, as well as tutorials and general help is the Arduino website itself: https://www.arduino.cc . You can find an easy introduction to Arduino here.
Another important characteristic of Arduino is that it is Open Source: Arduino hardware, software, and even graphics and other material are adequately licensed under Open Source (Creative Commons Share Alike, GPL and LGPL, for example) . This has resulted in a large user community and a large amount of easily accessible material and help, which you can always make use of.
2 Setup
First we will install the Arduino IDE (which stands for Integrated Development Environment, or in short,the software you need installed in your computer to program and talk to the Arduino board) . You can find the corresponding instructions here: Getting started.
Now that you all have it installed we will proceed to test that everything works, before progressing further, and explore a bit the Arduino IDE:
- Open the IDE. In the menu, go to: File>Examples>01.Basics>Blink . Now you will have opened a file, that if you have never programmed before, will look like a pile of gibberish. In a little while you will understand what it all means.
- Now, You can either click the arrow on top of your sketch (this is, by the way,how the programs one writes are referred to in the Arduino IDE) or go to Sketch>Upload on the menu, or use the equivalent keyboard shortcut in your computer. For this to work, you have to make sure that in Tools>Board Your Arduino Uno board is selected, and that under Tools>Port the correct usb port is selected also. Usually this is called something with Arduino Uno in it, depending the system you are using.
Hopefully, if all worked out and did not get any error message a little orange LED close to pin 13 on your board will be blinking (all “pins” on the board are marked with a number or a small text saying what they do, but we will go through that in a little while) . If you want to change the frequency of the blinking, you can do that by changing the value in code that says 1000, to any other number, for example 500:
delay(500);
Upload again, as above, the sketch to the Arduino. Now the light will blink every half a second (or 500 milliseconds), if you have changed the value in both places in the sketch. A humble begin, but here it is, you can control something in the real world by writing a piece of text… isn’t that magic?
A last thing recommended to do before we get on (though not necessary) is to define where in your computer yo want to save your Arduino programs (for example somewhere in your documents). The default location may work for you (different depending of your operating system), but otherwise you can set this in Arduino>Preferences (In OS X) Sketchbook location.
3 Programming
The basic of this magic is the relation between this piece of text that is the program, and what it does, in this case control a small LED on the PCB (Printed Circuit Board) that makes up the Arduino. When you press the Upload button the Arduino IDE is actually doing a couple of things: First it is “compiling” the code in the text, into “machine code” that the small micro-controller can run. This machine code is also a language, but quite cumbersome to understand by humans, though of course not impossible (it is quite rare to use machine code directly to program, but done in some extreme cases). The text one writes the programs in for the Arduino is written in a mix of some of the most common two languages used in programming, C and C++. Both are quite similar since C++ developed from C, and C used to be a “subset” of C+, that is, C++ was an extended version of C, but that is not strictly the case anymore. C and C++, in its different flavours and variations, are used to program most of the software you use in your laptop, mobile, tablets… and it is thus very useful to be familiar with. But what is programming, really?
3.1 What is programming?
The word program is made of the greek words pro-, meaning forth or forward and -gram, which means writing.Then literally program means to write in advance, or to write forth something that is going to happen.This is the same meaning as the program of a theatre performance or a TV program. Computer programs consists usually of texts written in a programming language. If you are interested in the history of programming languages, there is a nice entry on wikipedia. The history of computers and programming are closely related to the developments of logic during the nineteenth century and early twentieth century, and to the associated “linguistic turn” in philosophy during the twentieth century; for example the philosopher Charles Sanders Peirce, already demonstrated in the nineteenth century the possibility of using electric circuits to perform logical operations; a closer example is the influence of Noam Chomsky’s theories of language in the development of computer languages during the sixties. Languages have developed different paradigms (for example procedural or object-oriented, C is a procedural language, C++ is also object oriented); these paradigms define the basic concepts that make up the languages, and define its characteristics in terms of expressiveness or easy of use. We are going to look at the characteristics of C/C++ commonly used in Arduino. We will alsoleave some very important aspects of C/C++, perhaps the most important one being C pointers, not to mention the vast amount of features of C++, such as templates, lambdas… one may expend all of one’s time programming and still not master all techniques and features of a language, which, in the case of C++, keep constantly evolving and under development.
3.2 Basic concepts.
Syntax.
A difference between natural languages -the everyday spoken, signed or written languages- and formal languages (like programming languages) is that the former are strictly defined. This means that the instructions of a program need to be written following certain strict rules, or syntax, in order to be executed. In a natural language one may have grammatical or syntactic errors and still be understood; this is not the case in computer languages, which need to follow a rather strict syntax and logic.
Comments and other syntax.
If you open a new sketch in Arduino (File>New) you will see that the IDE generates a texts with some text in different colors: some of the text is greyed out, and som in blue, some is green and some is black. This is because the Arduino IDE highlights the syntax of the text that makes the program, to makes us easier to see it. If you look closer you see that the lines of greyed texts starts with a “//”. This menas that the text is a comment, that is, it is a piece of text that the computer will ignore, it is only there to explain something to a human reading the code. You can write anything after ‘//’ and the computer will ignore it, as it will ignore anything between ‘/*’ and ‘*/’. In these tutorials we also use syntax highlighting, though the colours are different:
//This is a comment, and it will be ignored by the computer... //you can have many lines of comments. /* And this is the other way of making comments, which tells the computer to ignore all text between the slash-star and the star-slash... */ void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run repeatedly: }
Comments may look quite useless, but are very important to explain (often to yourself) what the code does. One should not over-comment, but it is a good practice to comment as extensively as possibly your code!
Obviously then the colored bits do something… in this case these bits called setup() and loop() make the most basic program (and trivial, since it doesn’t do anything) in Arduino. As the generated comments indicate, the text between the ‘{‘ and ‘}’ after void setup() will be executed only once when the program starts running in the Arduino. The text between the ‘{‘ and ‘}’ after void loop() will be repeated endlessly after it has done everything on setup() , that is, once it has executed the code in loop(), it will start at the beginning of loop() again. You can find an explanation of this program in the Arduino site, here.
We can now go back to the previous Blink code and analyse what it does, line by line. (in the comments!)
// the setup function runs once when you press reset or power the board void setup() { // this sets the pin 13 (which is connected to the Orange LED in the board). // as an output. We will see later how we can use pins for output and input, // digital and analog. Pin 13 can only be digital input or output. We tell it // to be an output, since we want to use it to "put electricity out" ... pinMode(13, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(13, HIGH); // turn the LED on (HIGH means voltage "on") delay(500); // this tells the micro-controller to wait for a half a second digitalWrite(13, LOW); // turn the LED off by making the voltage LOW delay(500); // wait for half a second } //when it gets here, at the end of loop, it starts from the beginning //of loop again (that is why the LED blinks, even if we have only said it //to turn on and off once... it does it endlessly now.
Things you may have noticed:
both setup and loop have the word ‘void’ in front of them. We will not explain the use of it now, we will do that when we explain how to create our own functions. You may have also observed that all instruction lines end up with ‘;’. This is very important, as it means that this is the end of an instruction. You may think that it is easy to see for you, but the compiler (which translates the C/C++ code to machine code) needs to be told this. A typical error in many programs is to forget these semicolons (try out deleting one yourself, and see what happens).
The form of functions.
You may also get a flavour of the form of the instructions, which are called functions. They start with a word (the name of the function) and some values that are given between parenthesis. These are called the parameters of the function. In the case of pinMode() these parameters are the number of the pin (those written on the Arduino board) and the mode we want to set it to, INPUT, OUTPUT, or INPUT_PULLUP (we will have a look at this last one at some point). You can see all functions available in Arduino in the reference, available online here, or under Help>Reference in the IDE. Take a time to browse a bit to get a feeling of the functions available! we will later see how you can create your own.
Functions are a bit like verbs in a natural language, they indicate actions… if you want you can see functions as verbs in imperative form, in which you tell a computer, in this case the AVR micro controller in the Arduino, what to do.
Variables and data types.
As we have seen in the simple example above, we have a delay() function that has in this case the same value (1000, or 500). Of course this value can be different in the examples, so the time the LED is on is different of the time is off, but for the sake of the argument lets say that we want it to be the same, and we want to change it in one place, rather than write it twice by hand (imagine that instead of two times we would have a value that is the same written 10 or 20 times). We can instead create a symbol that holds the value of 500, and use the symbol instead of the number 500. When we want to change the value we only to change it in one place, in the symbol, and then it will be the same everywhere we use that symbol. This kind of symbol is called a “variable” (in contrast with writing the number directly as we have done above, which is called a “constant”. This is the way we would write it in C/C++:
int interval=100; //we define an interval variable and set it to 500. void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(interval); // we use our variable digitalWrite(13, LOW); delay(interval); // we use our variable here again }
Copy/Paste the code above on an empty sketch and upload it to the Arduino, and see what it does, change the value assigned to “interval” and test it!
You can see how we have change the delay() functions, to use our variable. Now we look at the first line in detail:
int interval=100; //we define an interval variable and set it to 500.
the first word we use is int. This defines the variable “interval” as of type integer, that is, a number that has no fractions. Usual types of variables are also float, for values with fractions, or boolean for values that are true or false. One can also define if the integer may also define positive numbers, by writing ‘unsigned‘ before it . For all possible types of variables see the reference. We will use some of them in the future…
After int, we have written “interval”. This is a word we have just chosen, a name for the variable. You can choose any other name, like “foo” or just a letter, as long as you always call it the same… try it!
Ten we use “= 500” to assign a value to our variable, and finish with ‘;’. = is the assignment operator, and it can be read as “set” (set our variable to the specified value). Sometime it can be a bit confusing, since it may be read as the mathematical meaning of “equal”, but actually it does not mean the same thing!
The above code could also be written as follows, by separating the variable declaration from the assignment:
int foo; //this is the declaration part of the variable void setup() { /* here we assign the variable foo. we can't really use it before we assign or "set" it, since we often cannot know what value it may hold, possibly a random or arbitrary number... */ foo=100; pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); delay(foo); // we use our variable digitalWrite(13, LOW); delay(foo); // we use our variable here again foo += 50; // and here we change it!! }
The use of variables opens many possibilities. You can see how at the end of every loop(), we write:
foo += 50; // and here we change it!!
+= means add 50 to whatever value is in variable foo, and set foo to it. it could have been written also like this:
foo = foo + 50; // set foo to the value of foo plus 50
Remember, = means “assign” or “set” , not “equal”. Otherwise the line above would make no sense…
Control Flow.
So far we have seen how to repeat some commands in sequential order. It is as if it would have been a roll on a play piano or a musical box, doing the same thing time and time again. A basic characteristic of a program is that it can branch and do different things in different order, depending of some conditions (for example some input). The order in which a computer (like the micro-controller) executes its instructions is called the control flow or flow of control. The instructions to control this flow can be found under “Control Structures” in the reference.
For analysing control flow we need some input, so we will proceed to a next example, as well as using the breadboard. We will connect the Arduino as in the example here.
And copy this code to a sketch (and upload it!)
// we attach a button th digital pin 2. If we want to change it //to another pin later, it is convinient to define the pin we are using //as a variable, which we can for example call pushButton, for convenience. //(remember, we could call it anything we want) //we do the same for the LED int pushButton = 2; int ledPin = 13; int waitTime = 100; void setup() { pinMode(pushButton, INPUT); pinMode(ledPin, OUTPUT); } void loop() { int buttonState = digitalRead(pushButton); if(buttonState == 1){ waitTime += 50; //if the button is pressed, make the interval larger } else if(waitTime >= 50){ //otherwise make smaller, but only if waitTime is larger than 50 waitTime -= 50; } digitalWrite(13, HIGH); delay(waitTime); digitalWrite(13, LOW); delay(waitTime); }
You can see how we have used an ‘if‘ or conditional statement; actually we have used a bit more complex version of it, an ‘if/else‘ block. You can see the basic logic of it: If a condition is met (the buttonState variable read and assigned through the digitalRead() function, being equal to one, that is on) do the statements that follow (between {} curly brackets). Else (that is, if buttonState was not 1), if another condition is met (waitTime being larger or equal to 50), then do what follows between the {} curly brackets. Besides the syntax of the conditional, you can see quite a few new operators, such as ‘==‘ which is the conditional “equal to” operator, or the ‘>=‘ , “larger or equal to” operator.
Scope.
Lastly for today, we will look at scope. Variables have a visibility depending of where they are declared. you can see this by moving the declaration of any of the variables we use inside another pair of ‘{‘ ‘}’ , and trying to compile (or upload) the code. The IDE will tell you something like “‘foo’ was not declared in this scope” (you can copy error messages and paste them somewhere else to see them in more detail). Every ‘{‘ ‘}’ pair defines the visibility of a variable. Anything declared within a {} pair is visible inside those brackets and in any brackets inside it, but not outside. Variables declared outside functions such as ‘pushButton’ or ‘ledPin’ are ‘global’, and means that they are visible anywhere.
In the next tutorial we will look at more forms of input and output, and also to functions. With that we basically have got a quite extensive view to the basics of Arduino!