0% found this document useful (0 votes)
21 views

Arduino Beginners Guide

Uploaded by

jayme campos jr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Arduino Beginners Guide

Uploaded by

jayme campos jr
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Arduino

Beginner ’ s Guide
By Alex Benjamin
Copyright 2015 by TSM Publishing - All rights reserved.

This document is geared towards providing exact and reliable information in


regards to the topic and issue covered. The publication is sold with the idea that
the publisher is not required to render accounting, officially permitted, or
otherwise, qualified services. If advice is necessary, legal or professional, a
practiced individual in the profession should be ordered.

- From a Declaration of Principles which was accepted and approved equally by


a Committee of the American Bar Association and a Committee of Publishers
and Associations.

In no way is it legal to reproduce, duplicate, or transmit any part of this


document in either electronic means or in printed format. Recording of this
publication is strictly prohibited and any storage of this document is not allowed
unless with written permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that


any liability, in terms of inattention or otherwise, by any usage or abuse of any
policies, processes, or directions contained within is the solitary and utter
responsibility of the recipient reader. Under no circumstances will any legal
responsibility or blame be held against the publisher for any reparation,
damages, or monetary loss due to the information herein, either directly or
indirectly.

Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational purposes solely, and is


universal as so. The presentation of the information is without contract or any
type of guarantee assurance.

The trademarks that are used are without any consent, and the publication of the
trademark is without permission or backing by the trademark owner. All
trademarks and brands within this book are for clarifying purposes only and are
the owned by the owners themselves, not affiliated with this document.
Contents
Introduction
Chapter 1: Introduction to Arduino
Chapter 2: Terminology
Chapter 3: Getting Things Ready
Chapter 4: Running a Simple Project
Chapter 5: Project Creation Process
Chapter 6: Pin Layout for the Uno
Chapter 7: Basic Arduino Command Library
Chapter 8: Programming Expressions
Chapter 9: Programming Structures
Chapter 10: Advanced Example
Conclusion
Introduction
Arduinio: Beginner’s Guide. Have you been thinking about investing in an
Arduino board for yourself or someone else? Have you just bought one, and
want to make sure you get a running start? Then this is the book for you!
Written for beginners, it answers quite a few questions, like …
What makes the Arduino special?
Is it compatible with my computer?
Is there any special software I need to buy?
Is there any special equipment I should be so I can get started as soon as
I get it?
It covers the information you need to jump in feet first:
The terminology you need to survive a basic Arduino book
A short example you can build and run, with step by step instructions
and screen shots
A discussion of the project development process
What you need to know about a typical Arduino pin layout
Programming structures, variables, data types, and expressions –
everything a beginner needs to know to begin writing a program for your
Arduino
A final, more advanced example to expand your skills and reinforce
what you learned
Are you ready to join in on the adventure of creating cool projects with Arduino
boards? Then you have picked the right book!
Thanks again for downloading this book, I hope you enjoy it!
Chapter 1: Introduction to Arduino
An Arduino microcontroller board can be thought of as a user-friendly, open-
source input-output system. An input can range from anything from a finger
pressing a button to a change in light intensity, and outputs can range from
lighting up a simple LED light to sending out a Twitter message.
What Makes It Special
There are several features of Arduino that truly make is stand out from the rest
of the microcontrollers on the market. For example, the software is open source,
so you can “ look under the hood ” so to speak, and is free to download, modify,
and re-use (which is always a plus for more advanced developers).
Even the basic plans for the Arduino are open source, so users can build their
own without having to buy one. There are several companies that make the
Arduinio boards, too, and you can buy full kits breadboards, wiring sensors, and
more. Even fully assembled, Arduino is on the lower end of the cost spectrum,
and is compatible with Windows, Mac, and Unix systems.
Most importantly for beginners, perhaps, is the fact that the development
environment for the Arduino is aimed at people with little to no microcontroller
experience, but powerful and flexible enough for experienced users. There is a
great deal of quality information out there to help even the most inexperienced
user navigate the Arduino and put it to use in exciting and creative ways
In short, it had made microcontrollers accessible to everybody, even those with a
minimal computer background, regardless of age.
There are many different flavors or Arduino boards, too. At the time this book
was written, Arduino offered 20 different boards. This particular book focuses
on the Arduino Uno.
What You Need
To work with the Arduino, you need a laptop, desktop, or tablet that you can
download the Arduino development environment onto. It is written in Java, and
can be downloaded on Windows, Mac OS X 10.7 Lion or newer, and Linux 32
or 64 bit.
To connect your board with your computer, you will need a USB data cable.
Unlike USB charging or synching cables, they have a square, blocky-shaped
interface instead of a small interface like the micro-usb.
It is recommended that, unless you are a well-established electronics hobbyists
with tons of cool sensors and the like lying around, you invest in a kit. These
vary in price, and can save you time and money by helping you obtain the
electronic components that are compatible with your board – and they usually
come with tutorials and source code.
For testing and prototyping, your laptop provides the power for the Arduino via
the USB data cable. However, for laptop independent projects you will probably
want to provide an independent, portable power source for your project. A link
is provided under online resources that shows how to use battery power for your
Arduino.
Online Resource:
Arduino Products: https://www.arduino.cc/en/Main/Products
Arduino Board Specifications: https://www.arduino.cc/en/Products.Compare
Arduino Uno: https://www.arduino.cc/en/Main/ArduinoBoardUno
Batter Power for Arduino: http://www.instructables.com/id/Powering-Arduino-
with-a-Battery/
Chapter 2: Terminology
Whenever you are learning something new, the first hurdle is usually
terminology. Before jumping into an example, we are going to take just a few
minutes to cover some terms and jargon that you need to know to get the most
out of this book. Let ’ s get started!
Breadboard
A breadboard is a reusable tool for building circuits. It allows you to connect
circuits without having to permanently solder them, and is a stable surface for
connecting up your components.

Compiler
A compiler is piece of software that takes a program your write (or sketch, as
Arduino calls it) and translates it into something a computer, or in this case the
Arduino microcontroller, can understand. It is part of the Arduino development
environment discussed in this book.
Device Driver
A device driver is a piece of software that helps your computer communicate
with devices attached to it, like the Arduino board. Without the correct drivers,
you computer cannot communicate with the Arduino board.
EEPROM
EEPROM stands for Electrically Erasable Programmable Read-Only Memory.
This is a type of computer chip that can be written and re-written with code
(instructions). Notice that it is electrically erasable. This means that an electric
current can be used to erase it so that it can be used again. However, when it is
erased, the entire chip must be erased. This is different from RAM, or Random
Access Memory, which can have just certain bytes erased.
RAM is more like writing on sheet of paper with a pencil, where you can erase
and rewrite just the parts you want. EEPROM is like a writing on a sheet of
paper with a pen, where if you erase you need start with a fresh sheet of paper.
The electrical erasure is the equivalent to providing a clean, empty sheet of
paper.
External Interrupt
We all know what it means to be interrupted. The definition in computer lingo
isn ’ t much different. An external interrupt means that something has
occurred outside of the computer system or processor and needs attention.
Flash Memory
Flash memory is another type of memory. It retains data whether power is
supplied to it or not. A good example is the typical flash drive: it still stores you
files even when it is not plugged into your computer. It is good for storing
memory that may change, but needs to remain even when powered down.
Input/Output
Digital Input/Output
Digital pins can have one of two values: low or high, where low corresponds to 0
or false and high corresponds to 1 or true. The number of available digital pins
is another major difference between the different Arduino boards.
The largest boards have 54 input pins and 15 output pins. These would be the
MEGA 2560 and the MEGA ADK (both using the ATmega2650 processor). The
next largest is the DUE (with an ATSAM3X8E processor), with 54 input pins
and 12 output pins. The smallest is the Gemma (using the ATtiny85 processor)
with only 3 input pins and 2 output pins.
Analog Input/Output
Analog is the opposite of digital. Analog involves a continuous electrical signal,
while digital focuses on a signal that has a value of either one or zero (binary).
Another way that the Arduino boards differs is based on how many analog input
and analog output pins they have. An analog input pin can receive an analog
signal as input to the processor. An analog output pin can provide an analog
signal as output from the processor.
The Esplora (with an ATmega32U4 processor) does not have any analog I/O
pins. Most boards have input pins but not output pins, like the Fio (with an
ATmega328P processor) which has 8 analog input pins and no output pins. The
exceptions are the Zero (with an ATSAMD21G18 processor) which has 6 analog
input pins and one analog output pin, and the Due (with an ATSAM3X8E
processor) which has 12 analog input pins and 2 analog output pins.
One of the interesting things is that you can use analog pins and digital pins by
just setting the either to a high value (to represent a digital 1, or true) or a low
value (to represent a digital 0, or false).
Processor
The processor is what takes computer instructions, figures out what to do with
them, and thenruns them – or “ executes ” them, as the classic computer lingo
goes. The Arduino boards typically use one of the following processors:
ATtiny85, ATmega168V, ATmega2560, ATmega168, ATmega328P,
ATmega32U4, AR9331 Linux, ATSAMD21G18, or the ATSAM3X8E/
A processors speed is a measure of how fast it can process instructions, and is
given in units of MHz (or GHz for laptops, desktops, and tablets). Most of the
processors listed above run between 8 MHz and 16 MHz with two exceptions:
the AR9331 Linux 400 MHz, and the ASTSAMD21G18 runs at 48 MHz.
PWM Pins
PWM stands for Pulse-width modulation, which is used to encode data in a
pulsing signal (as opposed to, say, a serial signal). A PWM pin supports
transmitting data using pulse-width modulation.
Serial Communication
When serial communication is occurring, it means that two systems are sending
digital pulses back and forth between each other at an agreed upon rate.
Let’s say you and a friend are talking on a cell phone. You agree to take turns
with each person saying what they want to say for five seconds. When you five
seconds are up, you have to stop – even if you aren’t finished. When their five
seconds are up, it’s your turn to talk again and you will need to pick up where
you let off. That is serial communication in a nutshell.
Sketch
The Arduino word for a program (also known as code) is sketch. It consists of
the instructions that you want the Arduino to run. Before it can be used on the
Arduino board, a sketch must be compiled and uploaded to the board.
SPI
The acronym SPI stands for serial peripheral interface, and is a synchronous
data communication protocol for use over short distances.
SRAM
SRAM is an acronym for Static Random Access Memory. It differs from RAM,
also known as DRAM for Dynamic Random Access Memory, in that it does not
need to be periodically refreshed. As long as an SRAM has power, it retains
memory. That makes it faster than RAM or DRAM. You can think of RAM as a
forgetful person who needs to keep checking something to remember what it is.
SRAM doesn ’ t need to double check because it always remembers.
UART
The acronym UART stands for Universal Asynchronous Receiver/Transmitter.
It is a microchip that is used to convert between serial and parallel data. For
example, it may receive information from several parallel streams of data, but it
can convert those multiple, parallel stream into a single serial stream. On the
other hand, it may receive a single serial stream of data from an outside source
(such as a modem) and converts that into a set of multiple, parallel streams that
the system can work with better.
In short, a UART chip empowers your system to communicate not just using
data sent in parallel, but also data sent in a single, serial stream.
Chapter 3: Getting Things Ready
Now that you understand a bit of the lingo, it ’ s time to jump feet first into a
project. However, you need to get things ready first.
The first thing you need, of course, is an Arduino board. This book makes use
of the Uno board. You will also need a USB data cable, as discussed earlier.
You will need to download the software environment for running the Arduino.
You can find it here: https://www.arduino.cc/en/Main/Software. At the time of
this book, the latest build was Arduino 1.6.5.

As you can see, downloads are available for Windows, Max OS X and both 32
and 64 bit Linux.
This example will download the software on a Windows system with admin
rights. If you are installing the software and do not have administrator rights on
your system, you will want to download the ZIP file instead of the Installer.
Download the file (you may be asked for a donation, but that isn ’ t necessary)
and save it to your computer. Depending on your internet connection speed, it
may take a while.
Once it downloads, run it. If asked if you want to allow it to make changes to
your computer, say yes (that ’ s the only way you can get it installed). Next, you
should see the licensing agreement.

Click I Agree if you do agree.


Next you will see the Setup and Installation options screen.

Click Next. It will ask you where you want it installed on the next screen, and
it ’ s best to go with the default that it suggests.
Click Install, and it will begin the installation process.

After the main installation is complete, you will be asked to install the drivers.
Click “ Install ” .
Once installation is finished, you will receive a notification screen that will look
something like this:
Chapter 4: Running a Simple Project
In this chapter, we are going to create a simple project. The purpose of this
project is not only to familiarize you with the basics of the Arduino, but also
help you to make sure all your settings are correct. We are going to start out by
discussing the equipment and electronic devices you need. Next, we are going
to take a general look at the steps needed to develop an Arduino project. We
then start up the Arduino environment, type in the sketch, build the circuit, and
get ready to test it out.
Requirements
Here is what you will need to build this simple project:
A laptop or desktop computer upon which you can install the Arduino
development environment
Arduino board (this example uses a Uno board)
USB data cable
A simple button
A 10 k Ω resistor
A basic breadboard
Some wires
The Development Process
Here is the process for creating a program to run on your Arduino:
1. Create the sketch in the Arduino software
2. Verify the sketch
3. Correct any errors that are indicated (like typos or misspelled
variable names)
4. Compile the sketch
5. Upload the resulting program to your Arduino
6. Test your program
7. Rewire or rewrite code as needed
8. Return to Step 2
In the Arduino software, you will notice that 4 and 5 occur at the same time.
You will probably notice that Steps 3 and 7 are the most frustrating and time
consuming, but they are.
Getting Ready
The first step is to plug the square end of a USB data cable into your Arduino,
and the other end into your computer.
Next, start the Arduino program. You firewall may block it, but you need to give
it permission to be allowed through the firewall. Next, you will see the Arduino
development interface.

Creating the Circuit


What we are going to do is write some code to respond to a button being
pushed. Here is a simple four-pin button just like the one used in this example:

Here is the circuit, created on a breadboard and represented using the Fritzing
app:
The red wires represent voltage coming in, and you will notice that the red wire
is connected first to the five volt source, then to the five volt line on the
breadboard. From there, it is connected to a pin on the button.
The black wires represent voltage going back to ground. The black wire is first
connected to a GND (ground) pin, then to the ground line on the breadboard.
From there a wire runs from ground to a 10 k Ω resistor. The resistor connects
to a pin on the button.
The green wire represents the flow of information between the button and the
board. If the button is closed, then a signal of HIGH is sent to pin 2. If the
button is open, a signal of LOW is recognized at pin 2.
Writing the Sketch
Here is the sketch code, complete with comments (those are the lines with a
double slash // in front of the computer – the computer will ignore everything
after the slash).
// These commands create two constants (indicated by the word const), which means
// that there values will never change while the program is running
// They are both set to data type int, which means that they will have an integer
// value associated with them
const int buttonPin = 2; // the number of the pin on the board that is connected
// to the pushbutton, and will receive input from the
// pushbutton pin
const int ledPin = 13; // the number of the LED pin on the board

// This command creates a variable of data type int (for integer)


// whose value can change; its purpose is to hold a value to indicate
// whether or not the button has been pushed
int buttonStatus = 0;

// This is the setup code, which is only once run


void setup() {
// initialize the LED pin (remember we set that to pin 13) as an output using
// the function pinMode with two parameters: the pin number and whether it is
// to be used an output pin (as in this case), or an input pin
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin (which we set as pin 2) as an input:
pinMode(buttonPin, INPUT);
}

void loop() {
// read the value of the pushbutton value and store it in the variable buttonStatus
buttonStatus = digitalRead(buttonPin);

// if the button is pressed, it will have a state of HIGH, so turn the LED light on
if (buttonStatus == HIGH) {
// the function digitalWrite is used to write a value of HIGH to the ledPin
// it has two parameters: the pin number to be written to and the value that
// needs to be written to it
digitalWrite(ledPin, HIGH);
}
else {
// if the button is not pressed, then turn it off
digitalWrite(ledPin, LOW);
}
}

Here is the part of the code you actually need to type in, and it must be typed in
exactly as it appears here:
const int buttonPin = 2;

const int ledPin = 13;

int buttonStatus = 0;

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}

void loop() {
buttonStatus = digitalRead(buttonPin);
if (buttonStatus == HIGH) {
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}
}

Save and Verify


Once your code is typed in, you need to save your file. Give it a file name you
can easily recognize. Next, click the Verify button to check your code for any
syntax errors.

You will see a message at the bottom of the screen saying, “ Compiling
sketch, ” which means it is working to translate your sketch program into a
language the Arduino board can understand.
If there are no errors, you should see something like this:
Upload your Program
Next, its time to upload your program to the Arduinio board.
Troubleshooting
You may get an error like this one:

First, make sure the correct type of board is selected. Go to


Tools … Board … and select the correct one. The one used in this example is an
Arduino Uno. Then try again. If you still get an error, the next step is to check
that the correct port is being used.
Next, go to Tools … Port … Serial Port. If you are running Windows, click
Com Port. Now try uploading it again.
If you are still having trouble, restart the Arduino software. Once you have
restarted it, open your last sketch by going to File … Open Recent. Now try
uploading it again.
Once it uploads correctly, you should see a message like this:

You will need to set the COM port each time you open the Arduino environment,
or you will get the same error.
Testing
The green power LED light should still be one, but no other LED lights should
be on. Now try pressing the button and see what happens. The LED light on the
board should light up.
Online Resource:
Troubleshooting Uploads:
https://www.arduino.cc/en/Guide/Troubleshooting#upload
Chapter 5: Project Creation Process
In this chapter, we are going to look at the Arduino project creation process for
programming and using an Arduino microcontroller. We are going to study the
phases involved, then revisit the simple example from the previous chapter in
terms of these phases.
Introduction
There are phases to creating a working microcontroller project:
1. Specify
2. Design
3. Prototype
4. Algorithm
5. Sketch
6. Compile and Upload
7. Test and Debug
Now we are going to look at these phases in more detail.
Specify
Before you can create a good microcontroller project, you must decide exactly
what it needs to accomplish. Then, ask things like this: What kind of input does
it need? What kind of output needs to be achieved? What will you do with the
input? How will you generate the output?
Design
You will need to design a circuit, within the limitations of your Arduinio board,
to achieve the input and output. At this stage, you will begin to look what kind
of electrical or electronic parts you will need, such as resistors, sensors, etc.
Make a list of what you need, and research what you don ’ t know. You will also
need to select which pins you want (or must) use.
Prototype
The next step is to build a prototype of your circuit. You can do this directly on
the breadboard, or if you prefer you can use an online prototyping tool.
Algorithm
This is an often neglected aspect of program development. Before you dive into
writing sketch code, take some time to think through what you sketch needs to
do. When you open up the Arduino environment to create a new Sketch, this is
what you see:

The Sketch is divided into two parts: setup and loop. Consider this their first
guidelines on how to develop a working sketch.
The setup portion is where you put code that needs to run only once. This
includes things like setting certain pins to HIGH, specifying whether a pin
should be used as input or output, assigning certain values to variables, etc. This
code will run once each time the Arduino board is powered up. Decide what
commands need to run once, and plan to place them here.
The loop section is the main portion of the code that will keep running until you
power off the Arduino. This is the more challenging part of developing the
algorithm.
Sketch
Here is where you begin to type in the actual commands, being careful about
spelling and syntax.
Compile and Upload
In the example, we saw that we could verify and compile the code at the same
time. This is a step that takes place under the hood, so to speak. As long as we
have typed in the code in a way the computer can understand, then there
shouldn ’ t be any issues with compiling.
Next, the code must be uploaded to the Arduinio. It doesn ’ t do you any good
until it is uploaded.
Test and Debug
This is the most time consuming part of programming. When you run you test,
why doesn ’ t it work correctly? I would start first by checking the code again,
then checking the circuit.
Revisiting the Example
Let ’ s revisit the button example.
1. Specify: the goal is to light up an LED when the user pushes a button
1. Input: signal from the button if it is pushed
2. Output: LED light
3. Processing: the button produces a signal if it is pushed, and
that signal can be checked to determine if the button is
pushed; if it is pushed, then the LED light needs to be on
2. Design
1. Equipment: Need a button; Need an LED light, can use the
LED light built into the board at pin 13; Breadboard; Wires
2. Voltage source: 5V source pin
3. Ground: GND pin
4. Design a simple circuit on paper
3. Prototype: build your prototype circuit on a breadboard

4. Algorithm
1. Initialization: set constants to represent which pin serves as
input from the button, which pin will be used for the LED;
create a variable that sets the initial button status to off
2. Setup: before the main section of the Program runs, the
LED pin needs to be configured as output and the button
pin needs to be configured for input
3. Loop: read the current button status and if it is high, then
turn the LED on, otherwise don ’ t
5. Sketch:

The yellow represents the initial values that need to be set. The green
block is the setup block, and the red block is the loop block that keeps
running until you turn the Arduino off. Note that a carefully written
algorithm can easily be translated into an actual sketch.
6. Compile and Upload: we compiled the code originally, but needed to
make some adjustment before it could be upload
7. Test and Debug: make sure the circuit works as expected
Online Resources:
Fritzing: http://fritzing.org/home/
Autodesk 123d Circuits: https://123d.circuits.io/
Chapter 6: Pin Layout for the Uno
Now that you know the basics of how to develop an Arduino project, it’s time to
get down to some of the nuts and bolts. In this chapter we are going to look in
depth at the pin layout, and discuss some special purpose pins.
Basic Layout
There are 14 pins on the Uno that can be used as either input or output. The
figure below, taking from Fritzing app, shows a representation of the Uno board.
The pin groupings are divided into three groups: Power, Analog In and Digital.
The Power pins include a VIN pin for voltage input, 2 grounds (GND), a 5 V
voltage source. There are 6 analog input pins, numbered A0 – A5. There are 14
digital pins: 0 – 13. The pins with a ~ can also be used for PWM (as discussed
in just a moment). AREF, used to provide a reference voltage when using the
analog input pins, and Reset, which resets the microcontroller.

Special Purpose Pins


There are also pins with certain functions:
Serial, pins 0 and 1, which can be used to for serial communication; 0 is
for receiving and 1 is for transmitting
External Interrupts, pins 2 and 3, which can be setup to trigger an
action based on some external condition the system detects
PWM, pins 3, 5, 6, 9, 10, 11; used for output via 8-bit using pulse-width
modulation
SPI, pins 10, 11, 12, and 13
LED, pin 13 (which you used in the example from the previous chapter)
The pin numbers are they appear on the board as the same pin numbers you use
in creating sketches for your Arduino.
Online Resources:
Arduino Uno: https://www.arduino.cc/en/Main/ArduinoBoardUno
Chapter 7: Basic Arduino Command
Library
There are a set of basic commands needed to interact with the Arduino
board. In this chapter, we look at the most common digital and analog
I/O functions you would use in a sketch for the Arduino.
Digital I/O Functions
There are three functions for digital input and output: one to set the
mode of the pin (is it going to be an input pin or an output pin), one to
write to the pin (is it going to be set to HIGH or LOW), and one to
read the current status of the pin (is it set at HIGH or LOW). The
commands and their basic structure are shown below. The values that
are italicized are called parameters and are used to provide
information to the functions so that they can work properly.
pinMode(pin, mode)
The pin number must be an integer value
There are three possible modes: INPUT, OUTPUT,
INPUT_PULLUP
digitalWrite(pin, value)
The pin number must be an integer value
The values are either HIGH or LOW
digitalRead(pin)
The pin number must be an integer value
Will return a value of HIGH or LOW
Analog I/O
As discussed earlier, the Arduino boards include pins for performing analog
input and output. One command is used to set a reference voltage (the value
used as the maximum range of the input voltage), another is used to read the
analog voltage, and the last is used to write the analog voltage. Here are the
commands:
analogReference(type)
You can choose from 5 options
DEFAULT is going to be 5 volts (on 5V Arduino boards)
or 3.3 volts (on 3.3V Arduino boards)
INTERNAL is a built-in reference that varies with the type
of processor
INTERNAL1V1 is a built-in 1.1V reference, but is only
available on the Mega
INTERNAL2V56:is a built-in 2.56V reference that is also
available only on the Mega
EXTERNAL: this means that you will use whatever
voltage is applied to the AREF pin for the reference
voltage
analogRead(pin)
This reads whatever the analog voltage level is at pin
It returns an integer value representing the voltage reading
at the pin
analogWrite(pin, duty cycle)
This command writes a PWM value to the pin
The duty cycle is a value between 0, which means always
off, and 255, which means always on
This can be used for things like strobing a LED light
Online Resources:
Arduino General Code Library:
http://playground.arduino.cc/Main/GeneralCodeLibrary
Chapter 8: Programming Expressions
In a program (or sketch, as Arduino calls them), you will eventually need to
make use of expressions. Expressions are combinations of variables, constants,
mathematical operators, logical operators, etc. In this chapter, we are going to
look at what we can use to make up an expression.
Variables and Data Types
Variables allow you to associate certain values with a name, sort of like a label.
Before you use a variable in a sketch, you need to declare it. To declare it, you
need to assign it a name and a data type. The data type tells the program what
type of data to expect to find stored in the variable.
Here are the most commonly used data types:
boolean: true, false, 1, or 1
char: characters such as ‘ a ’ or ‘ A ’ , represented by integer numbers
from -128 to 127
int: integer numbers with values between -32768 to 32767
long: integer numbers with values between -2157483648 to 2157483647
float: -3.4028e+38 to 3.4028e+38
double: same as float
Here is how to declare a variable named ledPin as data type int with an initial
value of 5:
int ledPin = 5;
Operators
Operators are used to manipulate variables. There are four main types of
operators: assignment, mathematical, logical, and Boolean.
The assignment operator = (what we call an equal sign) calculates the final
value of whatever is on the right-hand side of the = and associates that value
with the variable name on the left-hand side of the equal sign.
The mathematical operators are pretty straightforward: +, -, * (multiple), /
(divide) and % (modulo).
Both The logical operators are == for equal to, != for not equal to, < for less
than, > for greater than, <= for less than or equal to, and >= for greater than or
equal to. The Boolean operators are && for and, || for or, and ! for not. The
operators only work on boolean data types, meaning true, false, 1, or 0.
There are also the increment and decrement operators: ++ and --. If you use ++
after a variable name, like x++, then it adds 1 to the current value of x. If you
use – after a variable name, then it subtracts 1 from the current value of x.
Expressions
Here is an example of very simple mathematical expression: a = 2*3-5. The
compiler, which is what translates the instructions you write sees the =
assignment operator, so it looks to the left to determine what operations are there
and the order they need to be processed. In this case, going to from left to right
and following the MDAS (multiply-divide-add-subtract) rule, it calculates a
value of 1. It then assigns that value of 1 to the variable a.
Logical expressions make use of Boolean and logical operators, and are used
quite often in your microcontroller sketches. Let ’ s say that you want a certain
thing to take place if pin1 is HIGH or pin2 is HIGH. To create a conditional
expression for that, you would have something like this: (pin1 == HIGH || pin2
== HIGH). The || is the logical or, which means if either the first or second
condition is true, the entire conditional expression is considered true. If both the
pins need to be HIGH, here is the conditional expression: (pin1 == HIGH &&
pin2 == HIGH).

Online Resources:
Arduino General Code Library:
http://playground.arduino.cc/Main/GeneralCodeLibrary
Chapter 9: Programming Structures
There are three basic programming structures: sequential, decision, and
repetition. Sequential structures are the easiest: the instructions are performed
in the exact order they appear it the program. Decision structures, also known as
branching structures, allow the computer to select which set of instructions to
run based on a condition. Repetition structures keep repeating the same block of
instructions until some stopping condition is met.
In this chapter, we are going to look at how these structures work, and the
correct way to use them in Arduino sketches.
Decision Structures
The most basic form a decision structure is the if statement, which you saw in
the example program:
if (buttonStatus == HIGH) {
digitalWrite(ledPin, HIGH);
}
else {
digitalWrite(ledPin, LOW);
}

The if blockextends from the word “ if ” all the way down to the last curly brace
}. The condition used to determine which set of instructions to run is this:
buttonStatus==HIGH. If this condition is true, then we set the ledPin to HIGH,
which made the LED light up. If the condition is not true, then it must be false.
If the condition is not true, then we set led Pin to LOW which turns the LED
light off. Pretty straightforward, right?
As a more simple example, consider this:
if (value < 10 ) {
digitalWrite(ledPin, HIGH);
}

In this example, if value is greater than or equal 10, nothing happens; if it is less than 10, then the ledPin is
set to HIGH.

Repetition Structures
Let ’ s say that as long as a pin 3 has a value of HIGH, we want the LED light to
be off.
while ( digitalRead(3) ==HIGH) {
digitalWrite(ledPin,LOW);
}
This is a while block, and it extends from the word while to the last curly brace }. Everything between the
curly braces is repeated until the value of pin 3 is no longer equal to HIGH.
Another type of repetition structure is the for loop. These are used when you can determine how many
times a certain segment of code needs to run. For example, if you need to blink some LED lights a certain
number of times.
Let ’ s say we want a certain block of code to be repeated 5 times.
for (int count = 1; count <= 5; count ++) { … }
We need a variable to keep track of how many times the loop has been run. In this case, we set that up as an
integer variable named count. Count starts out with a value of 1. All of this is handles in this snippet of
code: int count = 1;
Next, we need a condition so we can determine if the loop should keep going. In this example it is this:
count <= 5. As soon as count is greater than 5, the loop will stop. Now, what keeps count from always
staying at the initial value of 1? The command count ++, which adds one to count.
So, here is how the for loop works:
Creates a variable named count and gives it a data type of integer and an initial value of 1
It runs the instructions inside the body of the loop, or inside the curly braces.
It adds one to count using the count ++ command
It checks the new value of count versus the condition count <= 5
As long as count is still <=5, the body of the loop is run again
If it is not still <=5, the program exists out of the loop and continues on with whatever
instruction comes after the last curly brace

Online Resources:
Arduino General Code Library:
http://playground.arduino.cc/Main/GeneralCodeLibrary
Chapter 10: Advanced Example
In this chapter, we are going to work through an advanced example project on
the Arduino Uno using RGB LEDs to create varying shades of color using a
single LED.
Requirements
Here is what you will need to build this simple project:
A laptop or desktop computer upon which you can install the Arduino
development environment
Arduino board (this example uses a Uno board)
USB data cable
A 4-leg Common Cathode RGB LED
(3) 220 ohm resistors
A basic breadboard
Some wires (preferably red, blue, green, and black)
Using RGB LEDs
In this example, we will be making use of a 4-leg RGB LED. Remember that
LED stands for light-emitting diode, and RGB stands for Red-Green-Blue.
Using just the colors red, green, and blue, an incredible number of colors can be
generated. One leg is called the common cathode, and the other three legs are
associated with red, blue, and green. The common cathode is connected to
ground, or GND on your Arduino board. Each of the other legs will need a
220 Ω resistor in series with them. The legs will be tied to the PWM pins we
discussed earlier.

The colors are varied by sending different PWM (pulse-width modulated)


signals to the red, green, and blue leads of the LED.
Here is the circuit we are going to use:

The black wires go to GND. Notice this is the GND that is on the same side of
the board as the PWM pins. The RGB LED has four pins, and one of the pins is
much longer than the others. That is the cathode pin. That is the pin that
connects to ground.
Next, the red wire goes to pin 6, which we know is one of the PWM pins
because it has a ~ beside the number. Similarly, the green wire goes to pin 5 and
the blue wire goes to pin 3. The wire colors correspond to which color the lead
goes to.
Development Process
1. Specify: the goal is to use an RGB LED to create different colors
1. Input: none required
2. Output: PWM signasl used to vary the color of the RGB
LED
3. Processing: the type of signal will have be varied by the
Arduino board to produce the colors
2. Design
1. Equipment: common cathode RGB LED, (3)220 Ω
resistors
2. Voltage source: PWM pins
3. Ground: GND pin on the digital side of the Arduino board
4. Design a simple circuit on paper
3. Prototype: build your prototype circuit on a breadboard

4. Algorithm
1. Initialization: set constants to represent which pin is red,
which is blue, and which is green
2. Setup: setup the red, blue and green pins for PWM output
3. Loop: cycle through the colors by adjusting the PWM
output using repetition cycles
5. Sketch:
int redPin = 6;
int bluePin = 3;
int greenPin = 5;
const int maxVal = 255;
const int minVal = 0;

void setup() {
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(greenPin, OUTPUT);
}

void loop() {
for (int i = 255; i >0; i=i-5) {
for (int j = 255; j >0; j=j-5){
for (int k = 255; k>0; k=k-5){
analogWrite(redPin, i);
analogWrite(bluePin, j);
analogWrite(greenPin, k);
delay(100);
}
}
}
}
6. Compile and Upload: don ’ t forget to make sure that Tools … Port is
setup correctly.
7. Test and Debug: make sure the circuit works as expected … the LED
should slowly cycle through various colors.
Discussion about the Sketch
Let ’ s look at that code in the sketch again.
int redPin = 6;
int bluePin = 3;
int greenPin = 5;
const int maxVal = 255;
const int minVal = 0;

This declares and initializes some variables and constants. The word const
means that the variable that follows cannot change value while the programming
is running. maxVal is set to 255 because that is the maximum PWM analog
signal strength we can send to one of the LED pins. For example, if the redPin
is set to 255, the LED color will be red.

void setup() {
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(greenPin, OUTPUT);
}

This is the setup section of code, that only runs once each time the board is
turned on. It assigns digital pins connected to our red, blue, and green RGB
LED pins to be set for output.
void loop() {
for (int i = 255; i >0; i=i-5) {
for (int j = 255; j >0; j=j-5){
for (int k = 255; k>0; k=k-5){
analogWrite(redPin, i);
analogWrite(bluePin, j);
analogWrite(greenPin, k);
delay(100);
}
}
}
}
In a nutshell, this section of code cycles through the various colors. It use three
repetition structures – for loops – to cycle through various combinations of red,
blue and green. The delay command keeps the color steady for 100 ms.
Try experimenting with some of the values in the code to see what happens. Just
make sure to save your original copy so you can start over if you feel like you
messed up.
Other Projects
There are a ton of resources on the web with projects and ideas for using the
Arduino. Here are two links with high quality projects that should help stir your
imagination.
Instructables for Arduino: http://www.instructables.com/tag/type-id/category-
technology/channel-arduino/
Top 40 Arduino Projects on the Web: http://hacknmod.com/hack/top-40-arduino-
projects-of-the-web/
Conclusion
I hope this book was able to help you to start enjoying your Arduino board. The
next step is to start exploring new and more advanced projects as you build up
your skills!
Finally, if you enjoyed this book and found it useful, would you be kind enough
to leave a review for this book on Amazon? It’d be greatly appreciated!

Click Any Star to


Review the Book
If you liked this book, check out my other books.

You might also like