Arduino The Practical Beginners Guide To - Steve Tudor
Arduino The Practical Beginners Guide To - Steve Tudor
STEVE TUDOR
TABLE OF CONTENTS
INTRODUCTION
WHAT YOU NEED TO KNOW AND WHAT YOU WILL LEARN IN THIS EXPERIMENT
THE BASIC PULSE TRAIN PATTERN
WHAT IS THE FLICKER RATE?
CHANGING THE APPARENT BRIGHTNESS
NEW FEATURES: INTRODUCING VARIABLES AND VARIABLE TYPES
NEW FEATURES: VARIABLE NAMES
ON-TIME, OFF-TIME, PERIOD AND DUTY CYCLE
MY SKETCH TO MODULATE THE LED WITH A PERIOD AND DUTY CYCLE
SUMMARY OF THE COMMANDS INTRODUCED SO FAR
CONCLUSIO N
Text Copyright ©
All rights reserved. No part of this guide may be reproduced in any form
without permission in writing from the publisher except in the case of brief
quotations embodied in critical articles or reviews.
Legal & Disclaimer
The information contained in this book and its contents is not designed to
replace or take the place of any form of medical or professional advice; and
is not meant to replace the need for independent medical, financial, legal or
other professional advice or services, as may be required. The content and
information in this book has been provided for educational and
entertainment purposes only.
The content and information contained in this book has been compiled from
sources deemed reliable, and it is accurate to the best of the Author's
knowledge, information and belief. However, the Author cannot guarantee
its accuracy and validity and cannot be held liable for any errors and/or
omissions. Further, changes are periodically made to this book as and when
needed. Where appropriate and/or necessary, you must consult a
professional (including but not limited to your doctor, attorney, financial
advisor or such other professional advisor) before using any of the
suggested remedies, techniques, or information in this book.
Upon using the contents and information contained in this book, you agree
to hold harmless the Author from and against any damages, costs, and
expenses, including any legal fees potentially resulting from the application
of any of the information provided by this book. This disclaimer applies to
any loss, damages or injury caused by the use and application, whether
directly or indirectly, of any advice or information presented, whether for
breach of contract, tort, negligence, personal injury, criminal intent, or
under any other cause of action.
You agree to accept all risks of using the information presented inside this
book.
You agree that by continuing to read this book, where appropriate and/or
necessary, you shall consult a professional (including but not limited to
your doctor, attorney, or financial advisor or such other advisor as needed)
before using any of the suggested remedies, techniques, or information in
this book.
Introduction
When it comes to creating some of your own robotics products, there are
many things that you can consider. You will need to decide what kind of
project you want to work on as well as the type of code that will help you to
get the work done. One of the best options that you can use is the Arduino
platform.
When we are talking about Arduino, we are talking about a software and
microcontroller that is programmable, open sourced, and will use the
ATMega chip. It is designed to be more of a prototyping platform, there is a
huge fan base for this software when it comes to building an electronic
project. When it comes to working with an electronic project, you will find
that the Arduino platform is good for using either as a temporary addition
while you work on the project or you can even embed it as a permanent part
of the robotic project when it is done.
The Arduino board is also programmable with the Arduino software, which
is pretty easy to use, even for those who are just getting started and have no
idea how to work with this kind of software. If you have happened to use
the C++ or Java programming languages, you will see that the Arduino
coding language is going to be fairly similar. The idea behind using this
software is meant to be really simple, but there is a lot of power there to,
making it perfect for those who have some experience and for those who
are just getting started out.
Arduino is also an open sourced platform, which means that anyone is able
to use it, for free, as well as make adjustments to the code to fit their needs.
This is a really cool addition for those who are just starting to use the
Arduino system because they will be able to access thousands of codes
from other programmers, or even make some changes to their own codes, in
order to make the program work perfectly.
In addition to finding that many of the codes that you would like to use are
already available and developed, beginners are going to enjoy that the
Arduino community is pretty large. You will be able to go online and look
through forums and communities to ask your personal questions related to
your own project, to find out new information, and even watch tutorials to
make working with Arduino easier than ever.
The Arduino platform may be pretty powerful to use, but it is also pretty
basic. You will find that this platform only comes with two main
components for you to use including:
The software: this would be the environment that you use with the board, or
the IDE, that is going to run right on your own computer. You will use the
IDE to help you to upload and write the programming codes that you would
like to be relayed over to the board. Once you write your programs on the
board and transfer them over, the Arduino board should act in the manner
that you requested.
These parts are able to come together to help you to get the project to work
well. You need to make sure that you have some hardware in place, such as
one of the Arduino board types, and then it needs to respond to what you
are able to send through with the software. We will spend some time talking
about the various things that you are able to do with the software in order to
get your project to work later on, but both of these will need to be set up to
ensure that the messages from the IDE are getting over to the board and
working properly.
With Arduino, you need to have the IDE in place before writing out any
code. The IDE for this program is free since it is open sourced, which
makes it easier to get ahold of a copy. When writing codes, you will use the
Arduino programming language, which will be easy to learn and works well
with all of the operating systems on your computer.
One thing to note with the IDE and the coding language with Arduino, if
you are working on a Windows 7 operating system or earlier, you will have
a few steps that you will need to take, in addition to the regular steps, to
make sure that the Arduino board will work with the operating system. It
does work with the older versions of Windows, you just need to take some
extra time to introduce the board to this system to get it to work.
Whether you are just getting started out with programming or want to use
some of your skills to make a great electronic or robotic project, the
Arduino platform will be able to help you get this done. It has all the power
that you need with a simplistic background that helps even the beginner
understand and accomplish what they want.
SPI: this stands for serial peripheral interface. It is in charge of keeping the
data communication protocol over small distances.
Getting started on one of your first projects in Arduino can be an exciting
experience. This is a great program to learn how to use whether you are
brand new to the world of coding or you are ready to take things to a new
level. This guidebook will show you how to download some of your own
projects and create them for the first time as well as some of the basics that
you need to get the boards to work.
Setting Up Your Arduino Platfor m
The Arduino platform is really popular and is always seeing a lot of
changes, which means that as a beginner, there are always new things that
you can learn about this platform in order to make it your own. We are
going to focus on the basics that come with using the Arduino platform, but
there are so many new projects that you can learn how to use with this
option that it is a good idea to try new things out, keep up with some of the
forums and communities, and see what is available for you to expand your
knowledge with.
At this time, we will stick with the basics of how to use the platform as well
as some of the projects that you are able to use. To get started, there are a
few essentials that you will need to get ahold of in order to make the
program work. These essentials include the Arduino board and the software
that will talk to the board.
What is the Arduino Board?
The Arduino board is necessary if you would like to get started on your first
project. There are a variety of options that you are able to choose from
though and each one works with a different kind of project. This is why it is
a good idea to understand some of the basics of the boards before you go
out and purchase one, or you may end up with one that isn’t what you want.
Each board is able to do slightly different things and they may even look a
bit different, but they should all have some of the same components in
common including:
Barrel Jack and USB: all of the boards that you can
purchase will need to have some means in order to connect
them to your power source, such as to the wall or to your
computer. Many of them will also have a USB connect so
that you are able to hook them to the computer and
download the codes to it. You can also use the barrel jack
which helps the board plug right into the wall.
Pins: the pins are basically the points where you will
create your circuits when you connect them with wires.
There are several types of pins that you are able to use
with the Arduino boards and each of them have a different
function. There are several types of pins that you can find
on your board including:
GND: THIS IS THE SHORT FOR GOURD.
THESE ARE GOING TO BE THE PINS THAT
ARE USED IN ORDER TO GROUND OUT THE
CIRCUIT YOU ARE CREATING.
5V AND 3.3V: THESE ARE THE PINS THAT
WILL GIVE THE RIGHT KIND OF VOLTAGE
THAT YOUR PROJECT NEEDS, EITHER THE
5 VOLTS OR THE 3.3 VOLTS.
ANALOG: THESE ARE BASICALLY THE PINS
THAT ARE SEEN RIGHT UNDER THE
ANALOG IN LABEL ON THE BOARD. THESE
CAN BE USED FOR READING ANY SIGNALS
THAT COME IN FROM THE ANALOG
SENSORS AND THEN THEY ARE TURNED
INTO A DIGITAL VALUE FOR YOU TO
READ.
AREF: THIS IS A SHORT FORM OF THE
ANALOG REFERENCE. THIS IS GOING TO
BE THE PIN THAT YOU WILL USE WHEN
YOU WANT TO SET A MAXIMUM OR AN
UPPER LIMIT FOR THE EXTERNAL
VOLTAGE THAT GOES TO THE ANALOG
PINS. YOU WILL USUALLY WANT TO PICK
A MAXIMUM OF 0 TO 5 VOLTS, BUT MOST
OF THE TIME YOU WON’T USE THESE AT
ALL.
PWM: THESE ARE FOUND IN MANY
ARDUINO BOARDS AND THIS LABEL IS
FOUND RIGHT NEXT TO THE DIGITAL PINS.
THESE PINS ARE USED FOR EITHER
NORMAL DIGITAL PINS OR FOR A SIGNAL
THAT IS CALLED PULSE-WIDTH
MODULATION.
DIGITAL: THESE ARE THE PINS THAT ARE
FUND RIGHT ACROSS FROM YOUR
ANALOG PINS AND WILL BE FOUND RIGHT
UNDER THE DIGITAL LABEL. THESE PINS
ARE USED TO SHOW THE INPUT AND THE
OUTPUT THAT IS PROVIDED BY THE
DIGITAL SIGNAL.
Reset button: this is the button that is going to allow the
pin to rest right on the ground and then will restart the
code that you already loaded onto your board. It is the one
that you will use when you want to test out your code a
few times. Keep in mind that it is not going to reset
everything on the board and it won’t be able to fix issues if
they are there.
Power LED indicator: this is going to be a small LED light
that should be right next to the label for ON right by it.
This should light up whenever you plug this board into a
new power source.
Voltage regulator: this is the part of the board that will be able to control
how much voltage you would like to get onto your board at a time. If there
is voltage that is above this set limit, it will be able to turn it away. It will
not be able to handle anything that is above 20 volts so make sure that your
power source is lower than this or you can have issues with destroying the
board.
Each of these pins can be important based on the project that you are using
your board for. You will need to pick out the board that has the right pins
for the project that you need. Many of the beginner projects are going to
have information on which board you are able to use and as you get more
familiar with how things work, you will be able to figure out which boards
are needed for your more advanced projects.
Hooking up the Arduino software
By this point, you will have the right hardware, or the right board, in order
to get started with your first project. It is now time to install the software,
also known as the IDE, to make sure that Arduino is going to work. The
IDE is basically the environment that you need to have in order to write
your code before sending it over to the board and to attach all of the circuit
components. Without having the right IDE in place, you would never get
the code over to the microcontroller and the board would just remain
lifeless.
To download the IDE that you would like to use, go to the website
www.arduino.cc in order to find the link for downloaded. Give the IDE
some time to download on your computer, and when it is done, you should
see a zip folder. Open up this file and then save it to the right location on
your computer; pick the one that you like the best to ensure that you are
able to find it later if needed.
When this is done, you can open up the Arduino.EXE file and then run it to
get the installation started. There will be a few command prompts that will
come up during the process so read through them and click in order to get it
all set up. Once the IDE is installed and the components are all in place, it is
time to start working on some of the projects in this guidebook in order to
see what all Arduino is able to do.
Getting Started with Arduino
Since this is a platform that is widely popular and is constantly expanding
and changing, it is important to keep in mind that you will have to continue
learning about the programming language as changes to it occur. To begin
with though, we are going to spend some time learning the basics that you
will need to know to get started with Arduino. To begin, there are two
essentials that you will need; the software to make this work, and the
Arduino board.
Understanding the Arduino board
Before you go out and purchase an Arduino board, you will need to
understand some of the basic features of these boards and their uses. There
are a few types of boards that are available, and each of them have different
capabilities and benefits. While they will differ in terms of what they are
able to do and how they look, most of the boards you come across will have
the following components in common:
Barrel Jack and USB - all the boards will have some
method for you to connect them to a power source. Most
of them will come with a USB connection so that you can
upload your codes onto them. You can also choose to
connect them with a barrel jack which will essentially let
you plug the board into the wall.
Pins - the pins are where you are going to construct your
circuits by connecting in the wires. There are a few types
of pins that you can use on the boards and they are each
used for a specific function. Some of the most common
pins that you will find include:
GND: this is short for Gourd. They are the pins
that you will use in order to ground your circuit.
5v and 3.3V: these are the pins that will supply
either 5 volts or 3.3 Volts of power.
Analog: these are the pins that will be seen under
the‘Analog In’ label. These are the ones that you
can use for reading signals from the analog
sensors, and then these signals are going to be
converted into a digital value.
Digital: these are going to be across from the
analog pins and will be under the‘Digital’ label.
These are the pins that are used for the input and
output of the digital signal.
PWM: in many of the Arduino boards, there will
be a (PWM~) label that is next to the Digital one.
This basically means that the pins are able to be
used as either normal digital pins, or for a signal
that is called Pulse-Width Modulation.
AREF: this is short form for Analog Reference.
This is the pin that you can use to set the upper
limit of the external voltage for the analog pins,
usually between 0 and 5 volts, though it is often
left alone.
Reset button - this button should be there to allow the pin
to rest to the ground, and to restart the code that is already
loaded on the board. It is a good way to test out code a few
times. It will not reset everything to a clean state,and
won’t fix any problems that exist in your code.
Power LED Indicator - this should be a tiny LED light that
should have the word“ON”right next to it. It is going to
light up when you plug your board into a power source.
Transmit and Receive LEDs - these are in place to give an
indication that the board is either receiving or transmitting
data. This is useful when you are trying to load up a new
program to the board and you want to see if it is being
received.
Main Integrated Circuit (IC) - this is a little black piece
that has metal legs that will attach to the board. Think of it
as the brains of the board. The IC will differ between
boards, but most are from the ATMEL company. Make
sure to know which kind of IC you are using before
loading up a new program though because this sometimes
does make a difference.
Pull Up Resistor s
The pull-up resistor is going to be useful when you need to steer the input
of a pin to a known state, but you do not have any data present. This is
going to be best when there is no input. All you need to do is add a pull-up
resistor that goes up to 5 volts, or you can choose a pull-down resistor for
the input. It is best that you use a 10k resistor that is going to be good for
pulling up or pulling down the resistor.
Using the Built-In Pull-Up Resistor with the Pins Configured to Input
In the Atmega chip, there are around 20,000 pull-up resistors that are built
into it that you are going to have access to in the software. These resistors
are going to be accessed through your pinmod () setting by inputting
input_pullup. Now you have inverted the behavior of your contribution
mode so that high will turn the sensor off and low will turn the sensor on.
The various values for the pull-up are going to depend on what kind of
microcontroller you are using. For many AVR panels, the value is going to
be between 20 and 50 k ohms. For the Arduino Due, you will find that it is
between 50k and 150 k ohms. To figure out what the exact value is, you
will need to look at the datasheet for the microcontroller that is installed on
your panel.
Whenever you connect sensors to the pins that are configured for input, you
need to ensure that the other end is grounded. This is done so that if the pin
is reading high, the switch is going to be opened and little means that the
switch is pressed. With pull-up resistors, you are going to be able to provide
enough current to light up the LED that is connected to the pin.
There are some registers that are going to tell the pin if it is on a high or low
while controlling the pull-up resistor. There are also pins that can be
configured to have the pull-up resistor turned on whenever the pin is in
input mode, which will mean that the pin is turned on to high. Should the
pin be switched over to output by use of the pinmode () function, then it is
going to work the opposite direction. So, if the pin is on output mode, the
high state is going to have the resistor set up to where if switched it will go
into input mode.
Example
pinmode (4, input) ; // the pin is set to input
pinmode (6, input_pullup) ;
Pins Configured To Output
Any pin capable of configuration will do so to output with pinmode ( ) and
will be the lower state of impedance. With that being said, they are going to
be able to provide a large amount of current to other circuits that are hooked
up to it. The Atmega pins are going to give you the positive current or the
negative current depending on how many milliamps of current the other
pieces of equipment are going to need. As long as it is 40 mA or under, you
will be able to have enough current to light up an LED brightly, but it is not
going to be enough to run any motors.
Whenever you attempt to run a device that is going to require a lot of
currents, the pins can become damaged or even destroyed. This can end up
destroying the entire Atmega chip which is going to result in a dead pin in
your microcontroller. However, the other pins are going to work still, but
they may work at a lesser power than they were before. That is why you
should hook your output pins up to another device that is either 470 ohms
or is a 1k resistor. The only time that you should not is if the current draw
that is coming from the pins is required to run a certain application.
Pinmode () function
Pin mode is going to be used whenever you are configuring a specific pin
so that it is going to behave as an input or an output pin. There is the
possibility that you can enable the internal pull-up resistor through the
input_pullup mode. It also makes it to where the input mode is going to
disable any internal pull-ups.
Syntax:
Void setup ( ) {
Pinmode (pin, mode) ;
}
LED Route A
GND
LED Route B
GND
SDA on
Other
ArduinoSCL on
Other Arduino
Computer Port
Digital
Processor
Chip
OutputAnalogPower
Power
Ground on
Other Arduino
5 V on Other Arduino
Transmitter Arduino with Two LEDs Indicating which Route is Selected
Servo 1 5 volt +5V
Ground GND Signal
GND
+5V 5 volt
Ground
Servo 2 Signal
LED
SDA on Other
Arduino SCL on Other
Arduino GND
Computer Port
Digital
4.7 K 4.7 K Processor Chip
Battery Power Sensor Power Analog
Ground on
Other
Arduino
Ground on
Servos
5 V on Other Arduino 5 V on
Servos
What you need to know and what you will learn in this
experiment
You should be comfortable using the following commands:
void setup ()
PINMODE (13, OUTPUT);
void loop () {
The generic structure of this ideal pulse train, identifying the figures of
This is exactly the structure of the Blink sketch. We can literally use it and
just adjust the on-time and the off-time. Here is how we would use it:
void setup () {
As written, the sketch in the last section will modulate the LED with the
same on and off time. Using this pattern, we can explore the questions of
how fast we can modulate the LED so that it appears to be continuously on.
As we decrease the off and on time, we reach a point where the LED looks
like it is no longer blinking, but on continuously. We call this rate the flicker
rate.
We already introduced one set of figures of merit that describe this pulse
train, the on and off times. We can describe this behavior with another set of
parameters or figures of merit.
This is a periodic behavior. The same pattern of on and off lights happens
over and over again. We call one complete pattern a cycle .
One term that describes a property of a cycle is the time it takes to
complete. This is called the period . If the on-time is 0.5 seconds and the
off-time is 0.5 seconds, the period is the total time for one cycle or 1 second
per cycle .
An alternative way of describing the properties of a cycle is its frequency ,
how many cycles are completed per second. The frequency of a periodic
event is also referred to as a rate or speed . These terms are a little
ambiguous. The frequency of the pattern is a better term to always use.
If we know the period per cycle, the frequency is how many cycles occur
per second. The frequency is the inverse of the period:
If the period uses units of seconds per cycle, the units of frequency are
cycles per second. For historical reasons, we call cycles per second, Hertz,
abbreviated Hz.
The flicker rate, or flicker frequency, is the lowest frequency at which the
LED appears to be on continuously. At a slightly lower frequency, the LED
will appear to noticeably flicker. A higher frequency than the flicker rate
and the LED will appear to be on continuously.
To calculate the flicker rate, first decrease the off and on time until the LED
appears to not be blinking. The total time, the off-time + the on-time = the
period of the pulse train. The flicker frequency is
For example, when I adjusted the on and off time, I found that when the on
and off time was each 20 msec, the LED appeared to be on continuously.
The period was 40 msec = 0.04 sec and the flicker frequency was 1/0.04 sec
= 25 Hz.
This is close to the value of 24 frames per second (fps), which is the frame
rate used in movies. Why 24 fps? A slower rate and there is perception of
individual frames. A faster rate and you use up more film. To reduce the
cost of the film, the absolutely lowest rate that is still flicker free was
selected. For historical reason, 24 fps was adopted. You can read about it
here .
Here is my sketch to drive the on-board LED at 25 Hz:
void setup () {
The apparent brightness is really related to the fraction of the whole time
interval in which the LED is on. The larger the fraction of time the LED is
on in one cycle, the brighter it will look.
We call the fraction of time the LED is on, the duty cycle . When the duty
cycle is 100%, the LED will be the brightest. When the duty cycle is 50%,
it will be dimmer, and when the duty cycle is 2.5%, with the on-time 1 msec
out of a total interval of 40 msec, (1/40 = 2.5%), it will be dimmest, before
it is finally off .
Try different duty cycles and see if you can calibrate your sensation of
brightness with duty cycle.
In the Blink sketch, pin 13 is the pin to which the on-board LED is
connected. We hard-coded the number 13 by typing it explicitly in the
DIGITALWRITE command. We could have given the on-board pin
number a variable name, or memory location label, such as the made-up
name, pinLED.
We tell the sketch pinLED is a variable and create the variable location
by declaring it at the very beginning of the sketch using a special syntax.
At the same time we declare the variable, which creates it, we can also
place in its memory location the number 13.
At any future time, we could refer to the pin number by this variable
name and write the command, for example, as
DIGITALWRITE (pinLED, HIGH) ;
In every command in which we need to address pin 13, we could use its
variable name, pinLED. Whatever command sees the variable name
pinLED will look up in its memory location the value stored there and use
this value. If we later decide to use pin 12 instead, we just change the value
of the number stored in the pinLED variable name location and pin 12 is
used everywhere.
Every variable has three elements:
a type
a name
a value
The name and value we described above. There are multiple types of
variables based on what sort of data is stored in its location, such as: int,
long, float, Boolean, string, char, and arrays.
In most of the sketches we will write, we will use two types of numbers:
integers (a whole number with a plus or minus sign) like 448, 12, -94 or
-5, and numbers with a decimal point, we call floating point numbers,
like 4.81 or -2456.12.
The difference between an integer and a floating point number is that a
floating point number has a decimal point, but an integer does not.
When we create a variable we want to use to represent a number, we
have to decide, when we create it, if we want the number to be an integer
or a floating-point number. The number type influences the sort of math
we do with it and how the variable can be used.
For example, if we want to use the variable as a pin number, it must be an
integer type. We create integer type numbers using the simple command
int pinLED;
Some functions, like delay() will only use integers. However, if you type a
delay of 145.57 inside the (), the delay function will turn it into an integer
by truncating everything after the decimal point.
If we want to use the variable in a delay function as a delay of some
number of milliseconds, it is a good habit to use a number that is an
integer type. This way, we know exactly what delay value will be used.
The value of a number created from reading an analog pin is an integer
type.
An integer type number has no decimal point. It is only a whole number.
If we try to assign a number like 15.3 to a variable we created as an
integer variable, only the whole part of the number, 15, will be stored in
the variable location.
This means that when we do some algebra like 5/2 and assign the value to a
variable that is an integer type, only the integer part of the answer will be
stored .
Sometimes, this is a useful feature, such as when we want an answer as a
whole number. Sometimes this results in a number we did not want, like
when we are taking an average and the average is less than 1. If assigned
to an integer variable, its value would be 0.
There are some limitations to the variable type "int". A variable defined
as an int can only have a value between -32,768 to 32,767.
This is not a very large range. If we use an int variable to count
milliseconds, the longest amount of time we can count is only 32.7
seconds.
If the value of our variable is already 32,767 and we add 1 to it, it rolls
over to -32768 and counts up from there. This could be very inconvenient
if we don't plan for it.
There will be many situations in which we want larger integer values. In
this case, there is a different type of integer we can create, called a long .
Instead of using the int command to declare an integer, we use the long
command and declare a long integer. The command looks like:
long iCount;
A long variable can be between -2,147,483,648 to 2,147,483,647. If we use
a long type variable to count milliseconds, we could count as many as 2
million seconds, which is about 1 ½ months.
You can never go wrong creating all your integer variable types as long. It
will take up a little bit more memory space, but if memory is ever a
problem, there are other microcontrollers you can switch over to where
memory is not a limitation. They will not be the lowest cost, but they will
still be low cost, and higher performance.
We create a variable in the beginning of a sketch before the void setup()
function. The syntax is the type of variable and the variable name. We can
include an initial value if we want. Here are a few examples:
int iCounter=0;
long iTime_msec=17;
float V_tempSensor_V;
Remember, you can print a variable’s value to the serial monitor using
just a few lines of code, like:
int i1=3456;
void setup () {
Serial . begin (2000000);
}
void loop () {
Serial . println ( i1 );
}
Floating-point type numbers are numbers with a decimal point. A floating-
point type variable cannot be used as a counter in an if statement or as
a pin number or in the delay function .
However, the floating-point type number is incredibly useful when
describing a voltage, or a temperature.
Generally, if there is no compelling reason why a number should be an
integer, or we think that when we use the variable, it may represent a
number with a decimal point, the variable type should be assigned float.
To use a variable, we have to first create it, or in computer jargon, declare
it, by defining what type of number we want it to be, integer or floating
point . It’s a good habit to declare the variable at the beginning of the
sketch before the setup () function. The command lines to create an
integer or a floating-point variable, labeled as pinLED and sensorVoltage
are:
int pinLED;
float sensorVoltage;
The command to declare an integer variable is int.
This command allocates a little space in memory, labeled pinLED, that
will store an integer type number. At some point in the sketch we need to
fill this memory location with the value of the number we want. We can
both declare the variable and assign it a value all in the same line, such as
with
int pinLED = 13;
In most cases, we place these lines of code which declare the variable and
allocate the memory space, at the beginning of the sketch, before the
void
setup ()function. We can change the value of the variable
anywhere in the code that is appropriate.
A floating-point type number can have a value from 3.4028235E+38 to as
low as -3.4028235E+38. Each float has 6 or 7 digits and an exponent.
Hopefully, you will not encounter a sketch where you need a bigger
number.
Try these experiments (think about what you expect to see before you do
it and see if it comes out the way you expect):
a
a5
LED_pin
b4
In the olden days, with very limited memory in a computer, variable names
were restricted to a single letter and a number. It was always a challenge
trying to remember was the temperature sensor value variable name T3 or
S2?
But these days, even in an Arduino, variable names can be 64 characters
long or longer. So how do we design a good variable name ?
As a Best Design Practice , the goal in selecting a variable name is to
keep it short yet encode valuable information so it is self-documenting.
Some of the information we could encode in the variable name are:
Good variable names encode the most useful information so that you can
remember what they mean a month later, or someone new to the code can
decipher what the variable might contain.
If you use a consistent naming approach, your variables will be easy to
decipher without having to check in the comment line, easy to remember,
and easy to figure out if you don't want to find where it is declared. We
want to establish good variable naming habits that are self-documenting .
Everyone has a different style when naming variables . This makes trying
to figure out what is a variable and what type it is, just from the name,
can be very confusing when reading someone else’s sketch.
Here are two very good descriptions of variable naming conventions:
http://codebuild.blogspot.com/2012/02/15-best-practices-of-variable-
method.htm l
https://dev.to/mohitrajput987/coding-best-practices-part-1-naming-
conventions--class-designing-principles
Generally, I like to use variable names that describe the type of variable, in
what general and specific context it is used and include the units of the
number contained in the variable location.
To describe an integer, I like to start with the letter “i” or “n”, like
iCounter, or nptsAve_volts.
The rest of the name describes what the variable is used for and ends with
the units. Here are some examples:
nCountCycles
iTimeStart_msec
iTimeStop_usec
sensorTemp1_volts
sensorTemp1_degC
iSensorTemp1_ADU
SensorTemp1_ADU
pinTemp1_hi
pinTemp1_l o
Any variable that refers to a pin name is unambiguously an integer, so
starting with the word "pin" is ok.
The last part of any variable name is the units of the variable. To
highlight the units, I set them off with an underscore, _, at the end of the
variable name. If it is a time, the units might be _sec, or _msec, or _usec.
If it is a voltage, it might be _volts or just _V or _mV.
In the special case of the levels from an analog pin , there are no units.
The value is dimensionless. However, to help me keep track that the
variable is a number from an analog pin, I use the units of Analog to
Digital Units or _ADU. I always place the characters "ADU" at the end
of a variable name that will store the value read from an analog channel.
Even though a number in units of ADU, the number read from an ADC
(Analog to Digital Converter), is an integer, sometimes we will make
these float type numbers so we can do more accurate math, like when
taking averages.
If the variable is used as a simple index number inside of a loop or in an
array, which has meaning only as an index number, I would just use the
letter i or i1 or i2 or i3.
There are no hard and fast rules. The Best Design Practice is to use variable
names that help to describe what the variable refers to so anyone reading
your code would have a clear idea. The second-best approach is to be
consistent .
It's important to develop good habits early on so that each sketch is an
opportunity to practice and so that all of your projects become self-
documenting .
You can never add too many comments to further clarify each variable.
Let's practice some of these variable principles.
I like using the period and duty cycle to control the LED. This is a more
intuitive set of figures of merit. To modulate the LED, and use the
principles of the BLINK code, we will need to translate the period and
duty cycle into the on and off times.
This is very simple. The on-time and off-time are:
onTime_sec = Period_sec x dutyCycle
offTime_sec = Period_sec x (1-dutyCycle)
The duty cycle controls the apparent brightness of the LED. A duty cycle
of 90% means the LED is on for most of the period and it will look bright
to us. A duty cycle of only 10% means the LED is on for only a small
fraction of the period and it will look dim to our eye.
We will modulate the LED with a period that is short enough so that our
eye can't tell the LED is pulsing off and on .
To make the LED flash fast enough so we can't see it flashing, we want
the period to be shorter than about 40 msec, or the flash frequency to be
faster than 1/40 msec = 25 Hz.
This means we can adjust the on-time from 0 msec to 40 msec. We use
delay() commands to adjust the on and off times.
A modified BLINK is all we need to drive the LED with a pulse train.
We'll start with a period of 0.040 seconds (40 msec) and adjust the duty
cycle from 0% to 100%.
Try this experiment: How would you write the code to set the period and
duty cycle for the LED using variables? Use a period of 1 second and
adjust the duty cycle. This way you can see the fraction of the time the
LED is on.
Make the period shorter and shorter until it is shorter than the flicker rate
and watch the LED transition from flashing to appearing on continuously.
If you get stuck, watch this video and I will walk you
through setting up this experiment .
OUTPUT
These are very good at powering LED’s because they are in a low-
impedance state, meaning they let the energy flow freely through them
without much resistance. Output pins take their directions from the
microcontroller once it has processed the information given by the input
pins, and the output pins power whatever mechanism will perform the
intended task.
INPUT_PULLUP
This is what mode you will want to use when connected to a button or a
switch. There is a lot of resistance involved in the INPUT_PULLUP state.
This means that it is best used for Boolean-like situations, such as a switch
either being on or off. When there are only two states and not much in
between, use INPUT_PULLUP.
LED_BUILTTIN
true
In a Boolean sense, any integer that is not zero is true. One is true, 200 is
true, -3 is true, etc. This would be the case when a statement matches
reality. One of your pins might be testing a value, and the statement is
trying to match y != 35 , so if the pin receives information that the value of
y is 25, then the statement 25 != 35 is true.
fals e
This is part of a Boolean Constant, meaning that a statement is false, or that
its logic does not match reality. For example, you could have a statement, x
> 7 and the value the microcontroller receives for x is 3. This would make
the statement false . It would then be defined as 0 (zero).
integer constants
These are constants that are used by the sketch directly and are in base 10
form, or integer form. You can change the form that the integer constants
are written in by preceding the integer with a special notation signifying
binary notation (base 2), the octal notation (base 8), or hexadecimal
notation (base 16), for example.
floating point constants
These save space in the program by creating a shorthand for a long number
in scientific notation. Each time the floating-point constant appears, it is
evaluated at the value that you dictate in your code.
DATA TYPES
Data types refer to the type of data received in each of the programming
setups you apply. Data received by Arduino are sent to your program of
choice to determine various outcomes. Some examples are listed below.
Void
This is used in a function declaration to tell the microcontroller that no
information is expected to be returned with this function. For example, you
would use it with the setup() or loop() functions .
Boolean
Boolean data holds one of two values: true or false. This could be true of
any of the arithmetic operator functions or of other functions. You will use
&& if you want two conditions to be true simultaneously for the Boolean to
be true, || if you want one of two conditions to be met, either one setting off
the output response, and ! for not true, meaning that if the operator is not
true, then the Boolean is true.
Char
This is a character, such as a letter. It also has a numeric value, such that
you can perform arithmetic functions on letters and characters. If you want
to use characters literally, you will use a single quote for a single character,
‘A’ and a double quote for multiple characters, “ABC” such that all
characters are enclosed in quotes. This means the microcontroller will
output these characters verbatim if the given conditions are met. The
numbers -128 to 127 are used to signify various signed characters.
Unsigned Char
This is the same as a character but uses the numbers 0 to 255 to signify
characters instead of the “signed” characters which include negatives. This
is the same as the byte datatype.
Byt e
This type of data stores a number from 0 to 255 in an 8-bit system of binary
numbers. For example, B10010 is the number 18, because this uses a base 2
system.
Int
Integers are how you will store numbers for the most part. Because most
Arduinos have a 16-bit system, the minimum value is -32,768 and the
maximum value of an integer is 32,767. The Arduino Due and a few other
boards work on a 32-bit system, and thus can carry integers ranging from
-2,147,483,648 to 2,147,483,647. Remember these numbers when you are
attempting arithmetic with your program, as any numbers higher or lower
than these values will cause errors in your code.
Unsigned Int
This yields the ability to store numbers from 0 to 65,535 on the 8-bit boards
with which you will likely be working. If you have higher values than the
signed integers will allow, you can switch to unsigned integers and achieve
the same amount of range but all in the positive realm, such that you have a
higher absolute value of the range.
Word
A word stores a 16-bit unsigned number on the Uno and on other boards
with which you will likely be working. In using the Due and the Zero, you
will be storing 32-bit numbers using words. Word is essentially the means
by which integers and numbers are stored .
Long
If you need to store longer numbers, you can access 4-byte storage, or 32-
bit storage in other words, using the long variable. You simply follow an
integer in your coded math with the capital letter L. This will achieve
numbers from -2,147,483,648 to 2,147,483,647.
Unsigned Long
The way to achieve the largest numbers possible and store the largest
integers possible is to direct the microcontroller using the unsigned long
variables. This also gives you 32 bits or 4 bytes to work with, but being
unassigned the 32nd bit is freed from indicating the positive or negative
sign in order to give you access to numbers from 0 to 4,294,967,295.
Short
This is simply another way of indicating a 16-bit datatype. On every type of
Arduino, you can use short to indicate you are expecting or using integers
from -32,768 to 32,767. This helps free up space on your Due or Zero by
not wasting space on 0’s for a small number and by halving the number of
bits used to store that number.
Float
A float number is a single digit followed by 6 to 7 decimal places,
multiplied by 10 to a power up to 38. This can be used to store more precise
numbers or just larger numbers. Float numbers take a lot more processing
power to calculate and work with, and they only have 6 to 7 decimals of
precision, so they are not useful in all cases. Many programmers actually
try to convert as much float math to integer math as possible to speed up the
processing. In addition, these take 32 bits to store versus the normal 16 bits,
so if you’re running low on storage, try converting your float numbers to
integers.
Double
This is only truly relevant to the Due, in which doubling allows for double
the precision of a float number. For all other Arduino boards, the floating-
point number always takes up 32 bits, so floating does nothing to increase
precision or accuracy.
Chapter 5 Ultrasonic Sensor
This sensor is going to be able to determine how far an object is by using a
system that is similar to the system that bats use. It is going to give you a
great no contact range detection that is highly accurate and going to
produce stable readings.
This operation is not going to be affected by things like sunlight or black
material, but soft materials such as cloth are going to b somewhat difficult
for the sensor to pick up. It is going to be complete with an ultrasonic
transmitter and receiver module.
Tech Specifications