Arduino Tutorial: Learn the Basics

banner_arduino

By Peter Dalmaris for Udemy

Interested in more than the basics? Check out Peter’s complete Arduino course

Note: This post is part of our “Getting Started” series of free text tutorials on some of our most popular course topics.

To jump to a specific section, click the table of contents below:

What is the Arduino?

Places to find help

Arduino.cc
Reddit.com
Instructables
Dangerous prototypes
Vendor websites

Arduino boards

Parts of an Arduino board

Components

Shields
Breakouts
Components
Discrete components

What’s it like programming for the Arduino?

Quick setup guide

Installing on a Mac
Installing on Windows

Arduino libraries

Installing a new library

The basics of Arduino programming

What is the “Arduino Language”?
The structure of an Arduino sketch
Custom functions
Variables
Constants
Operators
Loops and Conditionals
Classes and objects
Input and output

What’s next?


This guide is designed for people new to the Arduino platform. It will help you understand the Arduino as a technology and platform, set it up on your computer, do your first experiments with hardware, and understand the role of the Arduino in the evolution of the Internet of Things.

What is the Arduino?

Let’s start from the very beginning. What is the Arduino, and where did it come from?

The Arduino is not a single thing, but a prototyping platform. The platform is a collection of hardware, software, workflows and support networks designed to help people create prototypes (and often, finished products) very quickly. All of these components are open source, meaning that their designs and source code are available for anyone to copy and use.

At the center of the Arduino platform is a microcontroller chip. A microcontroller is like the processor in your computer, except that it is very cheap, is much “weaker” in terms of performance, and has many connectors for peripherals like sensors and switches. As a result, microcontrollers are great for sensing and controlling applications, and you find them everywhere: in your toaster, fridge, alarm system, in your car, printer and paper shredder.

image28

An early Arduino. It uses the RS232 serial interface instead of USB, an ATMEGA8, and male pin headers instead of female.

The Arduino was created by educators and students at the Interaction Design Institute Ivrea in Ivrea, Italy. Massimo Banzi, one of the founders, was one of the instructors at Ivrea. At the time, students were using expensive hardware to build their microcontroller-based creations. The Ivrea students and their instructors decided to build their own microcontroller platform by using a popular “AVR” microcontroller from Atmega, and a light version of the Wiring development platform written by (then student) Hernando Barragan.

Wiring is what we now call the “Arduino Language” and the Integrated Development Environment (IDE), the core component that is a bit like what the HTML and the first graphical web browser were for the Web: It made the Arduino platform easy to use so that people who are not engineers can build sophisticated microcontroller-based gadgets.

Places to find help

As you go about exploring the Arduino, you will hit roadblocks. These are great opportunities for learning! The Arduino is very well documented, with many places where you can find documentation and personalised help from other Arduino enthusiasts. Here are a few places worth visiting:

Arduino.cc

This is the premier resource for anything Arduino. This is the home of the original documentation for the IDE, bundled libraries (more about this is coming up), and the hardware. To access this documentation, go here.

The home of the Arduino.cc documentation resources.

There are also numerous discussion forums where you can find or offer help. There are forums on general electronics, LEDs, microcontrollers, audio, sensors, robotics and much more. If you are an artist, you will find peers discussing relevant issues in the Interactive Art forum. If you are a teacher, you will find the Education and Teaching forum relevant. There are also forums for people based on their location and language, device, products, and more.

The forums home page.

Reddit.com

Reddit is an online community with people talking about virtually everything and anything. Each topic is called a “subreddit”, and Arduino has its own.

image16

The Arduino subreddit

 

The Arduino subreddit is at https://www.reddit.com/r/arduino/. Here, people talk about their projects, ask questions, and participate in conversations.

Instructables

Instructables is a website where people post project guides so that other people can go ahead and build their own versions of these projects.

image21

Instructables

Instructables is a great resource because it contains details of things people have created in a way that other people can follow. If you want to learn how to build an Arduino-based, cloud-powered home notification system, an Arduino stopwatch, or Arduino-powered musical chairs, then go to Instructables.com

Dangerous Prototypes

Dangerous Prototypes is a blog featuring relatively advanced projects. New projects are added every month, and they are mostly geared towards more advanced makers. These projects tend to push the limits of what you can do with microcontrollers, so they are worth looking at even if you are not yet at the skill level required to actually build them.

image36

Dangerous Prototypes

If you want to know how to repurpose your old Nokia 3100 as an Arduino shield so that you can send out SMS messages, this is the place to visit.

You can access the Dangerous Prototypes site at http://dangerousprototypes.com/.

Vendor websites

The major electronics hardware vendors often also provide excellent documentation and guides for the products they sell. In particular:

These resources are free to use regardless of whether or not you have purchased one of their products.

Arduino boards

Coming across an Arduino board for the first time can be intimidating. Only a few years ago, there were just two or three boards to choose from. Today, there are dozens of boards designed by Arduino and various manufacturers. Some but not all of these manufacturers work closely with Arduino to ensure that the boards they produce are fully compatible with the official Arduino boards. The boards produced by these manufacturers are stamped as “official” and are listed on the Arduino.cc web site products page.

If a board is not listed on the Arduino products page, then it probably a clone. In my experience, clones will work like the original, but usually they are made with cheaper components that will wear off after a while, especially the connectors in the headers. It is worth investing in official Arduino boards even if they are slightly more expensive because they will work better so that you will not have to spend hours figuring out problems with the board instead of building your gadget.

At the time I am writing this, there are around 20 official Arduino boards.

If you are a beginner in Arduino and electronics, I recommend getting the Arduino Uno R3. This is the classic Arduino board. It is hard to destroy (I have tried!), has tons of high-quality documentation, example sketches and libraries while still being surprisingly capable. It is relatively easy to expand as your projects grow.

image07

The official Arduino Uno – the best board for the beginner and beyond.

If you are looking to build projects that require small size, you can go for one of the small footprint Arduinos, like the Pro Mini or the Micro.

image29

The tiny Arduino Pro Mini

 

There are also Arduinos based on more capable microcontrollers, like the Mega, or even microprocessors running Linux, like the Arduino Yún, which also has built-in Wi-Fi capability and is well suited to Internet of Things applications.

image05

The Arduino Yún, geared for Internet of Things applications

Worth mentioning are also the various wearable Arduinos. If you are interested in making electronics that you can embed in clothing, then you can look at something like the super-tiny Arduinos Gemma or Lilypad. These are small, battery-ready, low-power Arduinos, circular in shape so that they don’t catch on fabrics.

image47

The super-tiny Arduino Gemma

 

Parts of an Arduino board

Arduino boards have certain features that are shared between them and are good to know about. I’m describing the most important ones in this image:

image53

The most important parts of the Arduino Uno

Components

The Arduino can’t do much on its own. Its purpose is to control components that you connect to it. And there are a lot of them! In this section I will discuss the kinds of components that you can connect to an Arduino, and give some examples of each.

Shields

An Arduino shield is a printed circuit board with various components already installed on it, ready to perform a particular function. They hook onto an Arduino without any wiring or soldering. Just align the shield with the Arduino, and apply a bit of pressure to secure them.

Most shields are built to work with the Arduino Uno, and as a result, virtually all other full-sized Arduinos have an Uno-compatible header configuration.

image48

The Arduino Ethernet shield (top) about to connect to an Arduino Uno (bottom). To make the connection, simply align the pins of the shield with the headers in the Uno and gently press down.

 

There are shields for almost anything: Ethernet and Wi-Fi networking, Bluetooth, GSM cellular networking, motor control, RFID, audio, SD Card memory, GPS, data logging, sensors, color LCD screens, and more.

There are also shields for prototyping, with which you can make permanent any circuits you created on a breadboard and are too good to destroy.

image09

A prototyping shield like this one from Adafruit makes it easy to preserve your best circuit designs.

 

Shields are great for beginners because they require no tools to add components to an Arduino.

Breakouts

Breakouts are typically small circuit boards built around an integrated circuit that provides a specific functionality. The board contains supporting circuitry, like a subsystem for providing power, LEDs for indicating status, resistors and capacitors for regulating signals, and pads or pins for connecting the breakout to other components or to an Arduino.

In many cases, the same functionality is offered in a shield or a breakout format. For example, you can get the exact same GPS system as a breakout or as a shield. In such cases, the difference is the size. The breakout is smaller, and it can work with boards other than the Arduino Uno or Arduinos with the Uno headers.

image41

The Adafruit GPS breakout. It comes with a header and a battery holder that you must solder on (image courtesy of Adafruit).

 

A breakout has to be wired to an Arduino using jumper wires and often a breadboard.

image22

You must connect the breakout to the Arduino using wires and a breadboard (image courtesy of Adafruit).

 

Sometimes, apart from using jumper wires to connect the breakout to the Arduino, you may also need to do a bit of soldering, like I had to do for the GPS breakout. Here’s the quick version of how this soldering job went:

The really nice thing about breakouts is that unlike shields, which only work with the Arduino, a breakout can be connected to anything, including the boards that you will design yourself down the track. Therefore, apart from being good for learning, breakouts can be embedded into a final product.

Components

While breakouts give you easy access to components by putting them on a board with their supporting electronics, you will eventually need access to the individual component so that you can fully customize the way it works in your circuit.

For example, if you would like to have a keypad so that the user can type letters and numbers as input to a gadget you are making, you could use a soft membrane keypad. This keypad is available as a component. To use it properly, you will need to add several wires and resistors.

image40

Using a 4×4 keypad requires external wires, diodes and resistors. This is more work (compared to a shield, but often the flexibility you get in return is worth the effort.

Another example of an individual component is a character LCD screen. To make this one work properly, you have to provide a lot of wires and a potentiometer.

image17

An LCD screen on a breadboard. A lot of wires are used to connect it to an Arduino Uno, on a breadboard with a potentiometer.

image11

A shift register IC makes it possible to control many digital components with a single pin of your Arduino.

As you become more skilled in Arduino prototyping, you will find yourself using increasingly more components like these. Almost any functionality you can imagine is available as a component. Sensors of all kinds, motion, user input, light, power, communications, storage, multiplexing and port multipliers, binary logic integrated circuits, amplifier circuits, and even thumbprint scanners can be connected to an Arduino as components.

Discrete components

At the bottom of the scale in terms of size and complexity, we have a wide range of discreet components. Things like resistors, capacitors, transistors, LEDs, relays, coils, etc., fall under this category. They are the “bricks and mortar” of electronics. Most of these discrete components are very simple, but very important.

For example, a resistor limits the amount of current that can flow through a wire. A capacitor can be used as a small store of energy or as a filter. A diode limits the flow of current to a single direction. An LED is a diode that emits light. A transistor can be used as a switch or an amplifier. A relay can be used to switch on and off large loads, like an electrical motor. A coil can also be used as a filter or as part of a sensor, among other things. There are many more discrete components than the examples mentioned.

image52

A resistor limits the amount of current that flows through a wire.

image13

A capacitor stores energy, or works as a filter.

image12

A diode limits current to flow towards one direction only.

image30

An LED is a diode that emits light.

image27

A transistor can be used as a switch or an amplifier.

image04

A relay is used to drive large loads from your Arduino.

image20

A coil can be used as a filter.

 

As you are starting your electronics adventures, no matter which Arduino you choose, you will need to stock up on these components as you will need to use them in virtually everything you make. Luckily, they are very cheap, and it is worth buying them in bulk so that you always have some when you need them.

What’s it like programming for the Arduino?

To write programs for your Arduino, you use a simple tool called the “Arduino IDE”.
Advanced makers have the habit of replacing the one provided by Arduino with one of their choice in order to take advantage of various advanced features, but you don’t have to worry about this until much later.

No matter what your platform is, be it Windows, Mac or Linux, the Arduino IDE looks like this:

image54

The official Arduino IDE

 

Programming text editors don’t come much simpler than this. You type the program in the white box, and as you type, the IDE will recognise keywords based on their type and highlight them with a special colour for each type. When you are ready to upload, connect your Arduino to your computer with a cable:

image24

Connect your Arduino to your computer with a USB cable.

In most cases, the IDE will detect the connected Arduino and will configure itself with the correct USB port. If not, you can use the Tools menu to set the Arduino board model and the USB port it is connected to.

A few seconds later, the upload will finish and your sketch will start running on your Arduino. In this example, I uploaded a sketch that simply makes one of the LEDs on the Arduino board itself blink. Here is what that looks like:

This is what the process of connecting and uploading a sketch to your Arduino looks like.

The Arduino engineering team has done an amazing job of making a once complicated process almost as easy as sending an email!

Quick setup guide

Now that you know what to expect, let’s go ahead and set up your IDE. The process involves downloading the software from arduino.cc, and installing it on your computer. The only requirement is that you already have a Java runtime environment already installed. This is usually not a problem on Windows and Mac computers.

To download the IDE for your operating system, go to here.

image34

The Arduino IDE download page. Pick the installer to match your computer’s operating system.

Look for the installation file in your download folder: “~/Downloads” for the Mac and “Downloads” on Windows.

image25
The IDE installer on a Mac

image10

The IDE installer on Windows

 

Installing on a Mac

To do the installation on the Mac, double-click on the installation archive file to have it extracted. The picture below may be different from what you will see, depending on which program you use for extracting ZIP files.

image14

Extracting the IDE installer on the Mac

 

When the extraction completes, you will have new file, which is the actual IDE. All you have to do then is to move it into your Applications folder.

image15

The IDE application is now in my Downloads folder.

image18

… and finish the process by copying the file into your Applications folder.

 

To start the IDE, just double-click on the Arduino icon inside the Applications folder.

Installing on Windows

In Windows, start by double-clicking on the installation file. Be ready for a long series of confirmation dialogue boxes. In all of them, it is safe to accept the defaults.

A pop-up will ask you for permission to run the program; click on Yes to continue:

image26

Yes, it is safe to continue.

Agree to the license agreement:

image51

Yes, I agree.

Accept the checked components:

image50

Yes, all these components are useful.

Accept the default installation location, and the file copying will begin:

image37

Yes, this location looks fine.

 

The installer will start copying files to the installation location:

image49

Copying files to the destination

You will be asked to install device drivers a couple of times; just click on “Install”:

image45

Yes, these USB device drivers are also useful.

The copy process will finish; click “Close” to close the installer:

image08

Okay, the installer is finished, so let’s close it.

You can start the Arduino IDE just like any other Windows program. You can search for it or use the program list:

image39
To start the Arduino IDE, you can search for it.

image33

… or you can list all apps and look under “A”.

Arduino libraries

A great deal of software has already been written for the Arduino in such a way that makes it easy for people to reuse it in their own sketches. Often, this software is organised in a library and then distributed via the web, through sources like the arduino.cc site and Github, an online software source code repository.

Many useful libraries are included in the Arduino IDE by default. Have a look. Start the IDE, and then click on the File → Examples menu item (same for Windows and Mac). You will see a list of items, like in this screenshot:

image46

A list of libraries that ship with the IDE

This is not a complete list of libraries, only those that have example sketches. The IDE contains many more libraries that are hidden in its installation directory.

Do a quick browse through them. You will find libraries that make it easy to connect your Arduino to an Ethernet network, to various peripherals through serial protocols like SPI, servo motors, Wi-Fi networks, and to color graphics screens.

Installing a new library

If there is a library that you need but is not included with the IDE, you can install it. Let’s look at an example.

Let’s say that you want to have a small web server running on your Arduino. You can set up this server so that you can use your browser to control lights and read sensor values connected to it. The Arduino can handle this – no problem. You could spend a few days (or weeks) and write your own bare-bones web server (assuming you have a good understanding of HTTP), or just use Webduino.

Webduino is a library that was written at NYC Resistor to make it very easy to turn an Arduino into a basic web server.

The library is available on Github at https://github.com/sirleech/Webduino.

image35

The home page for Webduino on Github

Download the ZIP file on your computer. It doesn’t matter what platform you are on; the libraries work the same regardless of whether you are on Windows, Mac or Linux.

Also, don’t worry about extracting the files from the ZIP archive. The newer versions of the Arduino IDE have an easy library installer that takes care of extracting the library from the ZIP file and copying the files to the right location.

Assuming the library ZIP file is in your Downloads folder, start the Arduino IDE. Then click on “Sketch → Include Library → Add .ZIP Library…”, like this:

image06

Including a new library

A new dialogue box will pop up. Browse to the location of the ZIP file, select it, and click on Choose to complete the process:

image23

The Library addition dialogue box

When you click on “Choose”, the dialogue box will disappear, but nothing else is going to happen. No confirmation, no sound… To make sure that the Webuino library was actually installed, you can look for the example sketches that most libraries include.

Go to File → Examples, and look at the bottom of the list for your new library:

image32

There’s the new library, right at the bottom of the list!

You can also find a list with names and descriptions of all the libraries currently installed in your IDE. Go to Sketch → Include Library → Manage Libraries, and this window will pop up:

image00

The library manager can tell you what’s installed, and install new libraries.

The Library Manager, apart from telling you what is already installed, it can also install new libraries from online sources with the click of a button.

image55
You can add a new library from the Library Manager.

Hopefully now you have a good overview of the IDE and its most important functions. Let’s have a look at the Arduino programming language next.

The basics of Arduino programming

What is the “Arduino language”?

The Arduino language is actually C++. Most of the time, people will use a small subset of C++, which looks a lot like C. If you are familiar with Java, then you will find C++ easy to recognise and work with. If you have never programmed before, don’t worry and don’t be afraid. In the next few paragraphs, you will learn everything you need to get started.

The most important “high-level” characteristic of C++ is that it is object-oriented. In such a language, an object is a construct that combines functional code (the code that does things like calculations and memory operations), with state (the results of such calculations, or simply values, stored in variables).

Object orientation made programming much more productive in most types of applications when compared to earlier paradigms because it allowed programmers to use abstractions to create complicated programs.

For example, you could model an ethernet adapter as an object that contains attributes (like it’s IP and MAC addresses) and functionality (like asking a DHCP server for network configuration details). Programming with objects became the most common paradigm in programming, and most modern languages, like Java, Ruby and Python, have been influenced heavily by C++.

Much of the sketch code you will be writing and reading will be referencing libraries containing definitions for objects (these definitions are called “classes”). Your original code, to a large extent, will consist of “glue” code and customisations. This way, you can be productive almost right away by learning a small subset of C++.

The code that makes up your sketch must be compiled into the machine code that the microcontroller on the Arduino can understand. This compilation is done by a special program, the compiler. The Arduino IDE ships with an open-source C++, so you don’t have to worry about the details. But just imagine: every time you click the “Upload” button, the IDE starts up the compiler which converts your human-readable code into ones and zeros, and then sends it to the microcontroller via the USB cable.

Like every useful programming language, C++ is made up of various keywords and constructs. There are conditionals, functions, operators, variables, constructors, data structures, and much more.

Let’s take the most important of those things and examine them one at a time.

The structure of an Arduino sketch

The simplest possible Arduino sketch is this:


void setup() {
  // put your setup code here, to run once:

}

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

}
​

This code contains two functions in it.

The first one is “setup()”. Anything you put in this function will be executed by the Arduino just once when the program starts.

The second one is “loop()”. Once the Arduino finishes with the code in the setup() function, it will move into loop(), and it will continue running it in a loop, again and again, until you reset it or cut off the power.

Note that both setup() and loop() have open and close parentheses. Functions can receive parameters, which are a means by which the program can pass data between its different functions. The setup and loop functions don’t have any parameters passed to them. If you add anything within the parentheses, you will cause the compiler to print out a compilation error and stop the compilation process.

Every single sketch you write will have these two functions in it, even if you don’t use them. In fact, if you remove one of them, the compiler again will produce an error message. They are two of the few expectations of the Arduino language.

These two functions are required, but you can also make your own. Let’s look at this next.

Custom functions

A function is simply a group of instructions with a name. The Arduino IDE expects that the setup() and loop() functions will be in your sketch, but you can make your own. Group instructions inside functions is a good way to organise your sketches, especially as they tend to get bigger in size and complexity as you become a more confident programmer.

To create a function, you need a definition and the code that goes inside the curly brackets.

The definition is made up of at least:

  • a return type
  • a name
  • a list of parameters

Here’s an example:


int do_a_calc(int a, int b){
	int c = a + b;
	return c;
}
​

The return type here is “int” in the first line. It tells the compiler that when this function finishes its work, it will return an integer value to the caller (the function that called it).

The name (also known as the “identifier”) of the function is “do_a_calc”. You can name your functions anything you like as long as you don’t use a reserved word (that is, a word that the Arduino language already uses), and as long as it has no spaces or other special characters like “%”, “$” or “#”. You can’t use a number as the first character. When in doubt, remember to only use letters, numbers, and the underscore in your function names.

The parameters passed to the function are named “a” and “b”, and are both integers (“int”). The values that these variables contain can be accessed inside the body of the function. Parameters are optional, but if you don’t need to include any, you will still need to use the open/close parentheses.

In the first line of the body, we create a new variable, “c”, of type integer (“int”). We add a and b, and then assign the result to c.

And finally, in the second line of the body of the function, we return the value stored in “c” to the caller of do_a_calc.

Let’s say that you would like to call do_a_calc from your setup function. Here’s a complete example showing how to do that:


void setup() {
  // put your setup code here, to run once:
  int a = do_a_calc(1,2);
}

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

}

int do_a_calc(int a, int b){
	int c = a + b;
	return c;
}
​

In the setup() function, the second line defines a new variable “a”. In the same line, it calls the function do_a_calc, and passes integers 1 and 2 to it. The do_a_calc function calculates the sum of the two numbers and returns the value “3” to the caller, which is the second line of the setup() function. Then, the value “3” is stored in variable a, and the setup() function ends.

There are a couple of things to note and remember.

Comments

Any line that starts with “//” or multiple lines that start with “/*” and finish with “*/” contain comments. Comments are ignored by the compiler. They are meant to be read by the programmer. Comments are used to explain the functionality of code or leave notes to other programmers (or to oneself).

Scope

In the setup() function, there is a definition of a variable with identifier “a”. In function do_a_calc there is also a definition of a variable with the same identifier (it makes no difference that this definition is in the function definition line).

Having variables with the same name is not a problem as long as they are not in the same scope. A scope is defined by the curly brackets. Any variable between an open and close curly bracket is said to be within that scope. If there is a variable with the same name defined within another scope, then there is no conflict.

Be careful when you choose names for your variables. Problems with scopes can cause headaches: you may expect that a variable is accessible at a particular part of your sketch, only to realize that it is out of scope.

Also, be careful to use good descriptive names for your variables. If you want to use a variable to hold the number of a pin, call it something like:

int digital_pin = 1;

… instead of…

int p = 1;

You will thank yourself later.

Variables

Programs are useful when they process data. Processing data is what programs do, all the time. Programs will either get some data to process from a user (perhaps via a keypad), from a sensor (like a thermistor that measures temperature), the network (like a remote database), a local file system (like an SD Card), a local memory (like an EEPROM), and many other places.

Regardless of the place where your program gets its data from, it must store it in memory in order to work with it. To do this, we use variables. A variable is a programming construct that associates a memory location with a name (an identifier). Instead of using the address of the memory location in our program, we use an easy-to-remember name.

You have already seen variables. In the earlier section on custom functions, we defined a bunch of variables, “a”, “b” and “c”, that each hold an integer.

Variables can hold different kinds of data other than integers. The Arduino language (which, remember, is C++) has built-in support for a few of them (only the most frequently used and useful are listed here):

C++ keywordSizeDescription
Boolean1 byteHolds only two possible values, “true” or “false”, even though it occupies a byte in memory.
char1 byteHolds a number from -127 to 127. Because it is marked as a “char”, the compiler will try to match it to a character from the ASCII table of characters.
byte1 byteCan hold numbers from 0 to 255.
int2 bytesCan hold numbers from -32768 to 32767.
unsigned int2 bytesCan hold numbers from 0 to 65535
word2 bytesSame as the “unsigned int”. People often use “word” for simplicity and clarity.
long4 bytesCan hold numbers from -2,147,483,648 to 2,147,483,647.
unsigned long4 bytesCan hold numbers from 0 to 4,294,967,295.
float4 bytesCan hold numbers from -3.4028235E38 to 3.4028235E38. Note that this number contains a decimal point. Only use float if you have no other choice. The ATMEGA CPU does not have the hardware to deal with floats, so the compiler has to add a lot of code to make it possible for your sketch to use them, making your sketch larger and slower.
string – char arrayA way to store multiple characters as an array of chars. C++ also offers a string object that you can use instead that offers more flexibility when working with strings in exchange for higher memory use.
arrayA structure that can hold multiple data of the same type.

To create a variable, you need a valid name and a type. Just like with functions, a valid name is one that contains numbers, letters and an underscore, starts with a letter, and is not reserved. Here is an example:

byte sensor_A_value;

This line defines a variable named “sensor_A_value”, which will hold a single byte in memory. You can store a value in it like this:

sensor_A_value = 196;

You can print out this value to the serial monitor like this:

Serial.print(sensor_A_value);

The serial monitor is a feature of the Arduino IDE that allows you to get text from the Arduino displayed on your screen. More about this later – here I just want to show you how to retrieve the value stored in a variable. Just call its name. Also, remember the earlier discussion about scope: the variable has to be within scope when it is called.

Another nice thing about a variable is that you can change the value stored in it. You can take a new reading from the sensor and update the variable like this:

sensor_A_value = 201;

No problem – the old value is gone, and the new value is stored.

Constants

If there is a value that will not be changing in your sketch; you can mark it as a constant.

This has benefits in terms of memory and processing speed, and is a good habit to get used to.

You can declare a constant like this:

const int sensor_pin = 1;

Here, you define the name of the variable “sensor_pin”, mark it as constant, and set it to 1. If you try to change the value later, you will get a compiler error message and your program will not even get uploaded to the Arduino.

Operators

Operators are special functions that perform an operation on one or more pieces of data.

Most people are familiar with the basic arithmetic functions, = (assignment), +, -, * and /, but there are many more.

For example, here are the most commonly used operators:

 

Operator

Function

Example

%Modulo operator. It returns the remainder of a division operation.5%2=1
+=, -=,
*=, /=
Compound operator. It performs an operation on the current value of a variable.int a = 5;
a+= 2; This will result in a containing 7 ( the original 5 plus a 2 from the addition operation).
++, —Increment and decrement by 1.int a = 5;
a++;This will result in a 6.
==, !=, <, >, <=, >=Comparison operators. Will return a Boolean (true or false), depending on the comparison result.
  • == → equality
  • != → inequality
  • <  → less than
  • > → greater than
  • <= → less or equal than
  • >= → greater or equal than

int a = 5;
int b = 6;
Boolean c = a == b;This will result in variable c containing a false Boolean value.

!, &&, ||Logical operators. The “!’ operator will invert a Boolean value.! → NOT (invert) of a boolean value
&& → AND of two booleans
|| → OR of two booleansBoolean a = true;
Boolean b = true;
Boolean c = false;Boolean x = !a; // x → false
Boolean y = b && c; // y → false
Boolean z = b || c; // z → true

 

There are more than these. If you want to work at the bit level, for example, and manipulate individual bits within a byte (useful for things like shift registers), you can use bitwise operators. But this is something you can pick up and learn later.

Loops and conditionals

Conditionals are useful when you want to change the flow of execution in your sketch. Loops are useful when you want to repeat a block of code multiple times.

Very often, these two work together; that’s why I discuss them here in the same section.

Let’s start with a conditional. Imagine you have a red light and a green light. You want to turn the green light on when you press a button and the red light on when you leave the button unpressed.

To make this work, you can use a conditional.

Conditional: “if…else”

The most common of these is the if…else statement. Using pseudo code (that is, a program written in English that looks a bit like a real program), you would implement this functionality like this:


if (button == pressed)
{
	green_light(on);
	red_light(off);
} else
{
	red_light(on);
	green_light(off)
}
​

Loop: “while”

If you need to repeat a block of code based on a Boolean condition, you can use the while conditional expression. For example, let’s say that you want to make a noise with a buzzer for as long as you press a button. Using pseudo code again, you can do it like this:


while(button_is_pressed)
{
	make_annoying_noise;
}
​

Loop: “do_while”

You can do the exact same thing but do the check of the condition at the end of the block instead of at the start. This variation would look like this:


do
{
	make_annoying_noise;
} while(button_is_pressed)
​

Loop: “for”

If you know how many times you want to repeat code in a block, you can use the “for” structure. Let’s say you want to blink a light 5 times.

Here’s how to do it:


for (n = 1 to 5)
{
	Turn light on;
	Turn light off;
}
​

Your light will turn on and then off 5 times. Inside the curly brackets, you will also have access to the “n” variable, which contains the number of repetitions at any given time. With this, you could insert a conditional so that you leave the lights on before the last loop ends:


for (n = 1 to 5)
{
	Turn light on;
	if (n < 5) then Turn light off;
}
​

In this variation, the light will only turn off if the “n” variable is less than 5.

Conditional: “switch”

Another useful conditional is the Switch. If you have a variable, like button_pressed, that can take a few valid values, you can do something like this with it:


switch (button_pressed)
{
  case 1:
     Blink light one time;
     break;
  case 2:
     Blink light two times;
     break;
  case 3:
     Blink light three times;
     break;
  default:
     Don’t blink light;
}
​

The switch statement will check the value stored in the button_pressed variable. If it is “1”, it will blink the light once; if it is “2”, it will blink the light twice; and if it is “3”, it will blink three times. If it is anything else, it won’t blink the light at all (this is what the “default” case is).

The button_pressed variable can be an integer and could take its values from a membrane keypad, like this one:

image42

A membrane keypad can be used to provide input to your sketch.

For now, don’t worry how this keypad works; this is something you will learn later. Just imagine that when you hit a key, a number comes out.

Also, did you notice the keyword “break”? This keyword will cause the execution of the sketch to jump out of the block of code that is in between the curly brackets. If you remove all the “break” statements from your sketch and press 1 on the keypad, then the sketch will cause the light to blink once, then twice, and then three times as the execution will start in the first case clause, and then more into the rest.

Classes and objects

You now know that the Arduino language is actually C++ with a lot of additional support from software, the libraries which were mentioned earlier, that make programming easy. It was also mentioned that C++ is an object-oriented programming language.

Let’s have a closer look at this feature and especially how it looks in Arduino code.
Object orientation is a technique for writing programs in a way that makes them easier to manage as they grow in size and complexity. Essentially, a software object is a model of something that we want the computer (or an Arduino) to be able to handle programmatically.

Let’s consider an example. Imagine that you have a robotic hand. The arm only has one finger and can rotate 360 degrees. The finger can be open or closed. You can model this hand in an object-oriented way like in this pseudo code:


class robotic_hand{
	//These variables hold the state of the hand
	bool finger;
	int rotation;

	//These variables change the state of the hand
	function open_finger();
	function close_finger();
	function rotate(degrees);

	//These variables report the state of the hand
	function bool get_finger_position();
	function int get_rotation_position();
}
​

Can you understand what this code does? I am creating a model of the hand and giving it a name “robotic_hand”. The keyword “class” is a special keyword so that the compiler understands my intention to create a model.

Inside the class, I define three kinds of components for the model (=class). First, there are a couple of variables to hold the current state of the hand. If the hand is in an open position, the Boolean variable “finger” will be “true”. If the hand is rotated at 90 degrees, the integer variable “rotation” will contain “90”.

The second set of components are special functions that allow me to change the status of the hand. For example, if the hand is currently open and I want to close it so that it can pick up an object, I can call the “close_finger()” function. If I want to rotate it at 45 degrees, I can call “rotate(45)”.

Finally, the third set of components are functions that allow me to learn about the status of the hand. If I want to know if the hand is opened or closed, I can call “get_finger_position()”, and this function will respond with “true” or “false”.

The names are up to me to choose so that their role is clear. A class hides within it components such as these so that the programmer can think more abstractly about the thing they are working with instead of the implementation details.

Let’s say now that you would like to use this class in your own sketch. Here is an example of how you would do it in Arduino:


#include 
Robot_hand robot_hand();

void setup(){
}

void loop(){
	robot_hand.open_finger();
	robot_hand.rotate(45);
	robot_hand.close_finger();
}	
​

You would start by importing the Robot_hand library which contains the class you just created into your Arduino sketch. You do this with the include statement in the first line of your sketch.

In the second line, you create an object based on the Robot_hand class. Think about this for a few moments: a class contains the blueprints of an object, but is not an object. It is the equivalent of a blueprint for a house, and the house itself. The blueprint is not a house, only the instructions for building a house. The builder will use the blueprint as the instructions to build a house. Similarly, the robot hand class definition is only the instructions that are needed for building the robot hand object in your sketch. In the second line of this example sketch, we are defining a new object build based on the instructions in the Robot_hand class, and we are giving it the name “robot_hand()”. The name of the object cannot be the same as the name of the class; that is why it starts with a lowercase “r”.

In the loop() function, we can call the object’s functions to make the robot hand move. We can open it using robot_hand.open_finger() and close it using robot_hand.close_finger().

Note that these instructions start with the name of the object, “robot_hand”, followed by a dot, then followed by the name of the function we want to call, “close_finger()”. This is called “dot notation”, and is very common throughout most object-oriented programming languages.

There’s much more to learn on this topic, but in order to get started with Arduino programming, this level of basic understanding of object orientation is very important.

Input and outputs

Inputs and outputs are fundamental features of the microcontroller. You can connect devices to special pins on your Arduino, and read or change the state of these pins through special instructions in your sketch.

There are two kinds of input and output pins on an Arduino: digital and analog.

Let’s have a look at them next.

Digital pins

Digital pins are useful for reading the state of devices like buttons and switches, or controlling things like relays and transistors or LEDs. These examples have one thing in common: they only have two possible states.

A button can be either pressed not pressed. A switch can be on or off. A relay can be energised or not.

If in your sketch you want to know the state of a button, you can connect it to a digital pin. You can wire it up so that when the button is pressed, a 5V voltage is read by the connected digital pin, and that is reported as “high” to your sketch.

image43

A button like this one is a digital device. Connect it to a digital pin.

Let’s suppose that you connected a button to a digital pin on your Arduino, as I show in this schematic:

image19

A button is connected to digital pin 2. There is also a 10KOhm resistor that conveys a 0V signal to pin 2 when the button is not pressed.

When you press the button, the voltage conveyed by the yellow wire to digital pin 2 is 5V, equivalent to “logical high”. This happens because when the button is pressed, internally the red wire coming from the 5V source on the Arduino is connected electrically to the yellow wire that goes to pin 2.

When the button is not pressed, the voltage at pin 2 is 0V, equivalent to “logical low”. This happens because of the resistor in the schematic. When the button is not pressed, the yellow wire is connected to the GND pin on the Arduino which is at 0V, and thus this level if transmitted to pin 2.

You can read the state of the button in your Arduino sketch like this:


int buttonState = 0;
void setup() {
  pinMode(2, INPUT);      
}
void loop(){
  buttonState = digitalRead(2);
        if (buttonState == HIGH)
        {        
                //Do something when the button is pressed
        } else
        {
                //Do something else when the button is not pressed
}
}
​

First, create a variable to hold the state of the button.

Then, in the setup() method, tell the Arduino that you will be using digital pin 2 as an input.

Finally, in the loop(), take a reading from digital pin 2 and store it in the buttonState variable. We can get the Arduino to perform a particular function when the button is in a particular state by using the “if” conditional structure.

What about writing a value to a digital pin? Let’s use an LED for an example. See this schematic:

image38

An LED is connected to digital pin 13. A 220Ohm resistor protects the LED from too much current flowing through it.

In this example, we have a 5mm red LED connected to digital pin 13. We also have a small resistor to prevent burning out the LED (it is a “current limiting resistor”). To turn the LED on and off, we can use a sketch like this:


void setup() {
  pinMode(13, OUTPUT);
}
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}
​

Just like with the button example, first we must tell the Arduino that we wish to use digital pin 13 as an output. We do this in the setup() function with pinMode(13,OUTPUT).

In the loop() function, we use the digitalWrite function to write logical “HIGH” and “LOW” to digital pin 13. Each time we change the state, we wait for 1000ms (=1 second). The Arduino has been configured to translate logical HIGH to a 5V signal, and logical LOW to a 0V signal.

Analog pins

Let’s move on to analog now. Analog signals on microcontrollers is a tricky topic. Most microcontrollers can’t generate true analog signals. They tend to be better at “reading” analog signals. The ATMEGA328P, which is used in the Arduino Uno, simulates analog signals using a technique called Pulse Width Modulation. The technique is based on generating a pattern of logical highs and lows in a way that generates an analog effect to connected analog devices.

Let’s look at an example. We’ll take the same LED circuit from the digital pins section and make it behave in an analog way. The only difference in the schematic is that you have to change the wire from digital pin 13 to go to digital pin 9 instead. Here is the new schematic:

image44

In this example, we change the red wire to go to digital pin 9 instead of 13. We do this because we want to make the LED fade on and off via pulse width modulation. Pin 9 has this capability, but pin 13 does not.

We have to switch the controlling pin because we want to simulate an analog signal through the use of Pulse Width Modulation (PWM). Only a few of the pins on an Arduino can do this. One of these pins is 9, which we are using in this example.

Before showing you how to write an analogue value to a PWM pin, look at this video to see what the end result is like:

Here is the sketch to make the LED fade on and off:


void setup() {
}
void loop() {
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    analogWrite(9, fadeValue);
    delay(30);
  }
}
​

In the middle of the loop() function you will find a reference to the “analogWrite” function. This function takes two arguments: the pin number, and an 8-bit PWM value.

In the example, the variable fadeValue contains a number that changes between 0 and 255 in hops of 5 each time; it is analogWrite and is called because it is inside a “for” loop. When fadeValue is at 0, then the analogWrite function keeps the output at pin 9 to 0V. When fadeValue is at 255, then analogWrite keeps the output at pin 9 to 5V. When fadeValue is at 127, then analogWrite keeps the output at pin 9 at 0V for half of the time and 5V for the other half.

Because the ATMEGA is a fully digital IC, it simulates analog by just switching between digital high and low very quickly. For the LED to be brighter, we give analogWrite a larger value which simply increases the amount of time the the pin stays at logical high versus logical low.

What about reading the state of an analog device? Let’s use a potentiometer as an example. This example combines an LED with a potentiometer.

image02

In this example, when you turn the knob of the potentiometer in one direction, the LED becomes brighter. When you turn it towards the other direction, it becomes fainter.

We want to make the LED become brighter when we turn the knob of the potentiometer towards one direction and fainter when we turn it towards the other. To make this happen, we will both get an analog reading of the state of the potentiometer, and produce PWM output for the LED.

In this video you can see how the circuit works:

Here is the sketch:


void setup() {
  pinMode(9, OUTPUT);
}
void loop() {
  int potValue = analogRead(A0);
  int brightness = map(potValue,0,1023,0,255);
  analogWrite(9,brightness);
}
​

In the setup function, we set pin 9 to output because this is where we have connected the LED. Pins are inputs by default, so we don’t have to set analog pin 0 to be an input explicitly.

In the loop function, we get a reading from analog pin 0 (its name is “A0”) and store it in a local integer variable, potValue. The function analogRead returns an integer with a range from 0 to 1024. Remember from the earlier example that the PWM function can only deal with values from 0 to 255. This means that the value we store in potValue will not work with analogWrite.

To deal with this, we can use the Arduino “map” function. It takes a number that lies within a particular range and returns a number within a new range. So in the second line of the loop function, we create a new local integer variable, brightness. We use the map function to take the number stored in potValue (which ranges from 0 to 1023) and output an equivalent number that ranges from 0 to 255.

Note that the parameters of the map function match the range of potValue and brightness. The conversion calculation is done for you.

Analog read and write are easy once you understand the implications of the available resolution and Pulse Width Modulation. With what you already know, you will be able to work with a multitude of devices using the circuits from the examples in this section.

For example, if you would like to use a membrane potentiometer like this one:

image31

A membrane potentiometer. Electrically it works like a normal rotary potentiometer.

… just remove the rotary potentiometer from the example circuit and replace it with the membrane potentiometer. You will be able to control the brightness of the LED by sliding your finger up and down the membrane.

What’s next?

Congratulations on making it to the end of this introduction to the Arduino! If nothing else, it shows that you are serious about learning more about it, and, of course, about creating things with it.

There’s an incredible variety of things that you can do with your Arduino.

You can build toy cars (as I show in my Udemy Arduauto course), flying drones, useless boxes, home notification systems, environment monitors (as I show in my Udemy Beginning Arduino course), remote-controlled lawn mowers, model train controllers, a satellite (you’ll need to also find a launch rocket), a home security system, a 3-D printer, a robot arm, a GMS phone, a hear-rate monitor, a GPS car tracker, and so many others.

Find a project that is exciting and relevant to you and build it. Making is the best way of learning.

The Arduino is all about making!