Você está na página 1de 37

CHAPTER 1

INTRODUCTION TO ARDUINO

1.1 INTRODUCTION

Arduino is an open-source platform used for building electronics projects. Arduino


consists of a physical programmable circuit board (often referred to as a microcontroller) and
a piece of software, or IDE (Integrated Development Environment) that runs on your
computer, used to write and upload computer code to the physical board.

The Arduino platform has become quite popular with people just starting out with electronics,
and for good reason. Unlike most previous programmable circuit boards, the Arduino does
not need a separate piece of hardware (called a programmer) in order to load new code onto
the board – you can simply use a USB cable. Additionally, the Arduino IDE uses a simplified
version of C/C++, making it easier to learn the program. Finally, Arduino provides a standard
form factor that breaks out the functions of the micro-controller into a more accessible
package.

Arduino is a popular programmable board used to create projects. It consists of a


simple hardware platform as well as a free source code editor which has a “one click compile
or upload” feature. Hence it is designed in way that one can use it without necessarily being
an expert programmer. Arduino offers an open-source electronic prototyping platform that is
easy to use and flexible for both the software and hardware. Arduino is able to sense the
environment through receiving input from several sensors. It is also able to control its
surrounding through controlling motors, lights and other actuators. The Arduino
programming language that is based on the wiring and the Arduino development environment
which is based on the processing used to program the microcontroller found on the board.
Due to its open-source environment, one is able to easily write and upload codes to the I/O
board. It is also worth to note that Arduino can be run on Linux, Mac OSX and Windows as
its environment is written in Java.

All Arduino boards have one thing in common: they are programmed through
the Arduino IDE. This is the software that allows one to write and upload code. Beyond that,
there can be a lot of differences. The number of inputs and outputs ( a number of sensors,
LEDs, and switches can be used on a single board). Speed, operating voltage, and form
factor are just a few of the variables.

1.2 HISTORY

Arduino was released in 2005 by students from the Interaction Design Institute Ivrea
(IDII) as a modest tool for Mac OSX and Windows. It Was in the IDII that a hardware thesis
was contributed. The title of the thesis was “Arduino- The Revolution of open hardware”.
yes, it sounded a little different from the usual thesis but none would have imagined that it
would carve a niche in the field of electronics. A team of five developers worked on this and
they worked to make it much lighter, less expensive, and available to the open source
community. Since then, Arduino has been able to initiate an international-do-it yourself
revolution at the electronics industry. The open source microcontroller hardware has been
designed in a way that it can easily interface with various sensors (registering user inputs)
and driving the behaviors and responses of the external components such as speakers, motors,
and LED (responding to the user inputs). The most important feature of Arduino is the ease
of programmability hence users with little expertise are able to use it. This aspect has made
Arduino one of the most popular tools of choice for designers and artists in creating
interactive spaces and objects.

1.2.1 DEVELOPMENT

While discussing the development of Arduino, it is worth introducing a brief history


of microcontrollers. A revolutionary leap in the computing industry was seen in the 1960s
following the development of solid state computers, that used transistors to process its
operations and a magnetic core memory for its storage (instead of vacuum tubes), and these
enabled an increase in the compactness of the computer hardware. In addition, Jack Kilby’s
invention of integrated circuits in 1959 enabled circuits and transistors to be fused into tiny
chips of semiconducting materials (like silicon) as well as further miniaturization of the
computer component. The other crucial development made in the same decade was the high
level computer programming languages, written in symbolic languages such as plain English,
and this made computer codes somehow easy to learn and read than the earlier machine
languages that consisted of letters and numbers only. This development enabled individuals
with few years of expertise to carry out the basic operations on a computer. FORTRAN (for
the scientific calculators) and COBOL (for business application) were the two main
languages that were introduced in that period. The microprocessor was one of the greatest
innovations in the history of the modern computer in the 1970’s. Initially, the microprocessor
miniaturized all the hardware components of CPU to fit into one, tiny, integrated circuit,
popularly known as the microchip. The microchip became the major driving component of
the microcontrollers including Arduino which is made up of a microchip, input/output
hardware and memory storage hardware for sensors. The microprocessor, due to the small
form factor, was incorporated into a plethora of electronic devices ranging from personal
computers to calculators and are still used up to date. More programming languages were
also developed in the 1970s and 80s including C, C++ and Java for applications in science
and business.

1.2.2 EVOLUTION
Having looked at the evolution of microcontrollers, there have been recent
incarnations of the microcontrollers that have been designed in a way to fulfill the needs of
hobbyists and casual users who happen to have a limited technical knowledge. In other
words, the microcontrollers have moved from the more complex requirements in the
scientific, business or commercial fields. Before the invention of Arduino, the PIC
microcontroller board that was introduced by general instruments in 1985 was one of the
most used tools for the electronic enthusiasts. The reasons as to why the PIC microcontroller
board was preferred were the speed and ease of its programming through simple languages
including PBASIC. An additional reason was that it was able to store programs on a flash
memory chip that enabled the instructions on the board to be reprogrammed or erased at will
with an infinite number of possibilities. It also supported output devices such as LEDs and
motors as well as input sensors. There are other popular boards for the hobbyists including
BASIC Stamp and wiring which are some of the microcontroller boards that were designed
for tangible media explorations and electronic art. The two boards share the advantages of
ease of rapid prototyping and simplicity of programming.
It was in 2005 when the Arduino team was formed in Italy and it consisted of Barragan
Massimo, David Cuartielles, Gianluca Marino, Dave Mellis and Nicholas Zambetti. The
main goal of this team was to develop an electronic prototyping platform that would simplify
the wiring platform and make it accessible to the non-technical users especially in the
creative fields. The Arduino, therefore, incorporated several characteristics including a
programming environment that is based on the processing language that was conceived by
Casey Reas and Ben Fry and other artists and designers. Arduino also incorporated the ability
to program its board using a standard USB connection with a low price point.

1.2.3 PAST AND PRESENT


Within its first 2 years of existence, Arduino achieved rapid success where more than
50, 000 boards were sold. By 2009, Arduino had more than 13 different incarnations with
each having a specialized application. For instance, Arduino Mini was a miniature to be used
in small interactive objectives, Arduino BT was built with Bluetooth capabilities, and
Arduino Lilypad for wearable technologies projects. Today, the Arduino microcontroller is a
popular prototyping platform across the world and it is a good example of how software and
hardware technologies that were originally created for business, military or scientific
applications have been repurposed so as to serve the needs of people developing projects in
new media and arts & design. The following list includes the present and past Arduino
boards: Arduino shields, Arduino USB, Arduino single-sided serial, Arduino serial, Arduino
Mega, Lilypad Arduino, Arduino Fio, Arduino BT, Mini USB adapter and Arduino Mini. In
the development of Arduino, the following silverware times have been developed: in 2005, a
project was started to develop a device that would control the student-built interactive design
projects which was cheaper compared to other prototyping systems that were available at the
time. The founders of the project, David Cuartielles and Massimo Banzi, named the project
Arduin of Ivrea. They then began producing boards at a small factory in Ivrea in the
Northwestern Italy. In September 2006, they released Arduino Mini and later in October
2008, Arduino Duemilanove was developed and was earlier based on Atmel ATmega 168
and later, on ATmega328. Arduino Mega was then released in March 2009 and was based on
Atmel ATmega 1280. More than 300,000 units or Arduino in May 2011 were in use across
the world. Arduino Leonardo was later released in July 2012 and is based on Atmel
SAM3X8E that has an ARM Cortex-M3 core. Arduino Micro was released in November
2012 and is based on Atmel ATMega32u4. Arduino Uno has been named to mark the new
Arduino 1.0 where version 1 and Uno will be the reference model for the Arduino platform.
For the purpose of comparing with the previous versions, Arduino UNO is used in this
project.

The types of Arduino boards available are:

 Arduino Uno
 Arduino Leonardo
 Arduino mega
 Arduino Galileo
 Lily pad Arduino
 Arduino nano
 Arduino Due (ARM-based)

1.3 ARDUINO –UNO

In this project ,we are making use of Arduino-uno .The Arduino Uno is a
microcontroller board based on the ATmega328 (datasheet). "Uno" means one in Italian and
is named to mark the upcoming release of Arduino 1.0. The Uno and version 1.0 will be the
reference versions of Arduino, moving forward. The Uno is the latest in a series of USB
Arduino boards, and the reference model for the Arduino platform.

It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog
inputs, a 16 MHz ceramic resonator, a USB connection, a power jack, an ICSP header, and a
reset button. It contains everything needed to support the microcontroller; simply connect it
to a computer with a USB cable or power it with a AC-to-DC adapter or battery to get started.
The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial
driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed
as a USB-to-serialconverter.

1.3.1 FEATURES OF ARDUINO UNO

Microcontroller - ATmega328
Operating Voltage - 5V
Input Voltage (recommended) - 7-12V
Input Voltage (limits) - 6-20V
Digital I/O Pins - 14 (of which 6
provide PWM
output)
Analog Input Pins - 6
DC Current per I/O Pin - 40 Ma
DC Current for 3.3V Pin - 50 Ma
Flash Memory - 32KB
(ATmega328) of
which 0.5 KB
used by boot
loader
SRAM - 2KB
(ATmega328)
EEPROM - 1 KB
(ATmega328)
Clock Speed - 16 MHz

The Arduino Uno can be powered via the USB connection or with an external power
supply. The power source is selected automatically. External (non-USB) power can come
either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by
plugging a 2.1mm center-positive plug into the board's power jack. Leads from a battery can
be inserted in the Gnd and Vin pin headers of the POWER connector.
The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V,
however, the 5V pin may supply less than five volts and the board may be unstable. If using
more than 12V, the voltage regulator may overheat and damage the board. The recommended
range is 7 to 12 volts.

1.3.2 HARDWARE

An Arduino board consist of an Atmel 8-bit AVR microcontroller with


complementary components to facilitate programming and incorporation into other circuits.
An important aspect of the Arduino is the standard way that connectors are exposed, allowing
the CPU board to be connected to a variety of interchangeable add-on modules known as
shields. Some shields communicate with the Arduino board directly over various pins, but
many shields are individually addressable via an I2C serial bus, allowing many shields to be
stacked and used in parallel. Official Arduino have used the mega AVR series of chips,
specifically the Atmega8, Atmega168, Atmega328, Atmega1280, Atmega2560. A handful of
other processors have been used by Arduino compatibles. Most boards include a 5volt linear
regulator and a 16 MHz crystal oscillator. An Arduino’s microcontroller is also pre-
programmed with a boot loader that simplifies uploading of programs to the on-chips flash
memory, compared with other devices that typically need an external programmer. At a
conceptual level, when using the Arduino software stack, all boards are programmed over an
RS-232 serial connection, but the way this is implemented varies by hardware version. Serial
Arduino boards contain a simple level shifter circuit to convert between RS0232-level and
TTL level signals. The Arduino board exposes most of the microcontroller’s I/O pins for use
by other circuits. The diecimila, duemilanove, and current UNO provide 14 digital I/O pins,
six of which can produce pulse-width modulated signals, and six analog inputs. These pins
are on the top of the board, via female 0.1 inch headers. Several plug-in application shields
are also commercially available. The Arduino Nano, and Arduino-compatible Bare Bones
Board and Boarduino boards may provide male header pins on the underside of the board to
be plugged into solderless breadboards.

1.3.3 SOFTWARE

The Arduino integrated development environment(IDE) is a cross platform


applications written in Java, and is derived from the IDE for the processing programming
language and the Wiring projects. It is designed to introduce programming to artists and other
newcomers unfamiliar with software development. It includes a cod editor with features such
as syntax highlighting, brace matching, and automatic indentation, and is also capable of
compiling and uploading programs to the board with a single click. There is typically no need
to edit makefiles or run programs on a command-line interface.

Arduino programs are written in C or C++. The Arduino IDE comes with a software library
called “Wiring” from the original Wiring project, which makes many common input/output
operations much easier. User only need to define two functions to make a runnable cyclic
executive program:

 Setup( ) : a function run once at the start of a program that can initialize settings
 Loop( ) : a function called repeatedly until the board powers off

It is a feature of most Arduino boards that they have an LED and load resister connected
between pin 13 and ground, a convenient feature for many simple tests. The previous code
would not be seen by a standard C++ compiler as a valid program, so when the user clicks
the “Upload to I/O board” button in the IDE, a copy of the code is written to a temporary file
with an extra include header at the top and a very simple main( ) function at the bottom, to
make it a valid C++ program. The Arduino IDE uses the GNU toolchain and AVRLib to
compile programs, and uses avrdude to upload programs to the board. As the Arduino
platform uses Atmel microcontrollers, Atmel’s development environment, AVR studio or the
newer Atmel studio, may also be used to develop software for the Arduino.

1.3.4 ATMEGA328-OVERVIEW

The Arduino Uno is a microcontroller board based on the ATmega328. It has 14


digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16
MHz ceramic resonator, a USB connection, a power jack, an ICSP header, and a reset button.
It contains everything needed to support the microcontroller; simply connect it to a computer
with a USB cable or power it with a AC-to-DC adapter or battery to get started.

The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial
driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed
as a USB-to-serial converter.

Board has the following new features:

 1.0 pin out: added SDA and SCL pins that are near to the AREF pin and two other
new pins placed near to the RESET pin, the IOREF that allow the shields to adapt to
the voltage provided from the board. In future, shields will be compatible with both
the board that uses the AVR, which operates with 5V and with the Arduino Due that
operates with 3.3V. The second one is a not connected pin, that is reserved for future
purposes.
 Stronger RESET circuit.
 Atmega 16U2 replace the 8U2.
"Uno" means one in Italian and is named to mark the upcoming release of Arduino 1.0. The
Uno and version 1.0 will be the reference versions of Arduino, moving forward. The Uno is
the latest in a series of USB Arduino boards, and the reference model for the Arduino
platform; for a comparison with previous versions, see the index of Arduino boards.

Note: The Arduino reference design can use an Atmega8, 168, or 328, Current models use an
ATmega328, but an Atmega8 is shown in the schematic for reference. The pin configuration
is identical on all three processors.

1.3.3 POWER

The Arduino Uno can be powered via the USB connection or with an external power
supply. The power source is selected automatically. External (non-USB) power can come
either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by
plugging a 2.1mm center-positive plug into the board's power jack. Leads from a battery can
be inserted in the Gnd and Vin pin headers of the POWER connector.The board can operate
on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may
supply less than five volts and the board may be unstable. If using more than 12V, the voltage
regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

1.3.4 THE POWER PINS ARE AS FOLLOWS:

 VIN. The input voltage to the Arduino board when it's using an external power source
(as opposed to 5 volts from the USB connection or other regulated power source).
You can supply voltage through this pin, or, if supplying voltage via the power jack,
access it through this pin.
 5V.This pin outputs a regulated 5V from the regulator on the board. The board can be
supplied with power either from the DC power jack (7 - 12V), the USB connector
(5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins
bypasses the regulator, and can damage your board. We don't advise it.
 3V3. A 3.3 volt supply generated by the on-board regulator. Maximum current draw
is 50 mA.
 GND. Short for ‘Ground’. There are several GND pins on the Arduino, any of which
can be used to ground your circuit.
 IOREF. This pin on the Arduino board provides the voltage reference with which the
microcontroller operates. A properly configured shield can read the IOREF pin
voltage and select the appropriate power source or enable voltage translators on the
outputs for working with the 5V or 3.3V.

1.3.5 MEMORY

The ATmega328 has 32 KB (with 0.5 KB used for the boot loader). It also has 2 KB
of SRAM and 1 KB of EEPROM (which can be read and written with the EEPROM library).

1.3.6 INPUT AND OUTPUT

Each of the 14 digital pins on the Uno can be used as an input or output, using
pinMode(), digitalWrite(), and digitalRead() functions. They operate at 5 volts. Each pin can
provide or receive a maximum of 40 mA and has an internal pull-up resistor (disconnected by
default) of 20-50 kohms. In addition, some pins have specialized functions:

 Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data.
These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL
Serial chip.
 External Interrupts: 2 and 3. These pins can be configured to trigger an interrupt on a
low value, a rising or falling edge, or a change in value. See the attachInterrupt()
function for details.
 PWM: 3, 5, 6, 9, 10, and 11. Provide 8-bit PWM output with the analogWrite()
function.
 SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI
communication using the SPI library.
 LED: 13. There is a built-in LED connected to digital pin 13. When the pin is HIGH
value, the LED is on, when the pin is LOW, it's off.

The Uno has 6 analog inputs, labelled A0 through A5, each of which provide 10 bits of
resolution (i.e. 1024 different values). By default they measure from ground to 5 volts,
though is it possible to change the upper end of their range using the AREF pin and the
analogReference() function. Additionally, some pins have specialized functionality:

 TWI: A4 or SDA pin and A5 or SCL pin. Support TWI communication using the
Wire library.

There are a couple of other pins on the board:

 AREF. Reference voltage for the analog inputs. Used with analogReference().
 Reset. Bring this line LOW to reset the microcontroller. Typically used to add a reset
button to shields which block the one on the board.

See also the mapping between Arduino pins and ATmega328 ports. The mapping for the
Atmega8, 168, and 328 is identical.

1.3.7 RESET BUTTON

The Arduino has a reset button (10). Pushing it will temporarily connect the reset pin
to ground and restart any code that is loaded on the Arduino. This can be very useful if your
code doesn’t repeat, but you want to test it multiple times. Unlike the original Nintendo
however, blowing on the Arduino doesn’t usually fix any problems.

1.4 COMMUNICATION

The Arduino Uno has a number of facilities for communicating with a computer,
another Arduino, or other microcontrollers. The ATmega328 provides UART TTL (5V)
serial communication, which is available on digital pins 0 (RX) and 1 (TX). An
ATmega16U2 on the board channels this serial communication over USB and appears as a
virtual com port to software on the computer. The '16U2 firmware uses the standard USB
COM drivers, and no external driver is needed. However, on Windows, a .inf file is required.
The Arduino software includes a serial monitor which allows simple textual data to be sent to
and from the Arduino board. The RX and TX LEDs on the board will flash when data is
being transmitted via the USB-to-serial chip and USB connection to the computer (but not for
serial communication on pins 0 and 1). A Software Serial library allows for serial
communication on any of the Uno's digital pins.

The ATmega328 also supports I2C (TWI) and SPI communication. The Arduino software
includes a Wire library to simplify use of the I2C bus; see the documentation for details. For
SPI communication, use the SPI library.

1.5 PROGRAMMING

The Arduino Uno can be programmed with the Arduino software (download). Select
"Arduino Uno from the Tools > Board menu (according to the microcontroller on your
board). For details, see the reference and tutorials. The ATmega328 on the Arduino Uno
comes pre burned with a boot loader that allows you to upload new code to it without the use
of an external hardware programmer. It communicates using the original STK500 protocol
(reference, C header files). You can also bypass the boot loader and program the
microcontroller through the ICSP (In-Circuit Serial Programming) header; see these
instructions for details. The ATmega16U2 (or 8U2 in the rev1 and rev2 boards) firmware
source code is available. The ATmega16U2/8U2 is loaded with a DFU boot loader, which
can be activated by:

 On Rev1 boards: connecting the solder jumper on the back of the board (near the map
of Italy) and then resetting the 8U2.
 On Rev2 or later boards: there is a resistor that pulling the 8U2/16U2 HWB line to
ground, making it easier to put into DFU mode.

You can then use Atmel's FLIP software (Windows) or the DFU programmer (Mac OS X and
Linux) to load a new firmware. Or you can use the ISP header with an external programmer
(overwriting the DFU boot loader). See this user-contributed tutorial for more information.
1.6 AUTOMATIC (SOFTWARE) RESET

Rather than requiring a physical press of the reset button before an upload, the
Arduino Uno is designed in a way that allows it to be reset by software running on a
connected computer. One of the hardware flow control lines (DTR) of the ATmega8U2/16U2
is connected to the reset line of the ATmega328 via a 100 nano farad capacitor. When this
line is asserted (taken low), the reset line drops long enough to reset the chip. The Arduino
software uses this capability to allow you to upload code by simply pressing the upload
button in the Arduino environment. This means that the boot loader can have a shorter
timeout, as the lowering of DTR can be well-coordinated with the start of the upload.

This setup has other implications. When the Uno is connected to either a computer running
Mac OS X or Linux, it resets each time a connection is made to it from software (via USB).
For the following half-second or so, the boot loader is running on the Uno. While it is
programmed to ignore malformed data (i.e. anything besides an upload of new code), it will
intercept the first few bytes of data sent to the board after a connection is opened. If a sketch
running on the board receives one-time configuration or other data when it first starts, make
sure that the software with which it communicates waits a second after opening the
connection and before sending this data.

The Uno contains a trace that can be cut to disable the auto-reset. The pads on either
side of the trace can be soldered together to re-enable it. It's labelled "RESET-EN". You may
also be able to disable the auto-reset by connecting a 110 ohm resistor from 5V to the reset
line; see this forum thread for details.

1.7 USB OVER CURRENT PROTECTION

The Arduino Uno has a resettable poly fuse that protects your computer's USB ports
from shorts and over current. Although most computers provide their own internal protection,
the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB
port, the fuse will automatically break the connection until the short or overload is removed.

1.8 PHYSICAL CHARACTERISTICS

The maximum length and width of the Uno PCB are 2.7 and 2.1 inches respectively,
with the USB connector and power jack extending beyond the former dimension. Four screw
holes allow the board to be attached to a surface or case. Note that the distance between
digital pins 7 and 8 is 160 mil (0.16"), not an even multiple of the 100 mil spacing of the
other pins.

The Serial Peripheral Interface or SPI bus is a synchronous serial data link, a de
facto standard, named by Motorola, that operates in full duplex mode. It is used for short
distance, single master communication, for example in embedded systems, sensors,
and SD cards.

Devices communicate in master/slave mode where the master device initiates the data
frame. Multiple slave devices are allowed with individual slave select lines. Sometimes SPI is
called a four-wire serial bus, contrasting with three-,two-, and one-wire serial buses. SPI is
often referred to as SSI (Synchronous Serial Interface).
CHAPTER 2

PROGRAMMING ARDUINO

2.1 INTRODUCTION
A program is text that you write using a programming language that contains
Behaviours that you need a processor to acquire. It basically creates a way of handling inputs
and producing outputs according to these behaviours.
“Programming is the process of designing, writing, testing, debugging and
Maintaining the source code of computer programs”.
Designing a program is the fact you have to think about first, before you begin coding
it. It generally involves writing, drawing, and making schematics of all the actions
you want your processor to make for you.

2.2 PROGRAMMING LANGUAGE: C AND C++

Dennis Ritchie at Bell Labs developed the C programming language from 1969 to
1973. It is often defined as a general-purpose programming language and is indeed one of the
most used languages of all times. It had been used initially to design the Unix operating
system that had numerous requirements, especially high performance.
C is to both imperative and structured. It is very appropriate for both 8-bit and 64-
bit processors, for systems having not only several bytes of memory but also terabytes too,
and also for huge projects involving huge teams, to the smallest of projects with a single
developer.
C++ can be considered as a superset of C. It means C++ brings new concepts and
elements to C. Basically, C++ can be defined as C with object-oriented implementation,
which is a higher-level feature. This is a very nice feature that brings and provides new ways
of design.

2.2.1 ARDUINO IS PROGRAMMED WITH EMBEDDED C AND C++


Arduino supports C++ core language features and the common C libraries, such as
math.h, but NOT the standard C++ libraries. So while you can use objects and other core
C++ language features, you can’t draw from the C++ library.

High level program

English and logic

Compiler or translator

Hex code

Microcontroller

2.3 PROGRAMMING the BASICS

2.3.1 Variables
A variable is a way of naming and storing a numerical value for later use by the
program. As their namesake suggests, variable are numbers that can be continually changed
as opposed to constants whose value never changes. A variable needs to be declared and
optionally assigned to the value needing to be stored. The following code declares a variable
called input variable and then assigns it the value obtained on analog input pin 2:
int inputvariable = 0; // declares a variable and assigns value of 0
inputvariable = analogread(2); //set variable to value of analog pin 2
‘inputvariable’ is the variable itself. The first line declares that it will contain an int, short for
integer. The second line sets the variable to the value to the value at analog pin 2.This makes
the value of pin 2 accessible elsewhere in the code.
Once a variable has been assigned, or re-assigned, you can test its value to see if it meets
certain conditions, or you can use its value directly. As an example to illustrate three useful
operations with variables, the following code tests whether the inputvariable is less than 100,
if true it assigns the value 100 to inputvariable, and then sets a delay based on inputvariable
which is now a minimum of 100:
if (inputvariable < 100) // tests variable if less than 100
{
Inputvariable = 100; // if true assigns value of 100
}
Delay (inputvariable); // uses variables as delay
2.3.2 Variable declaration
All variables have to be declared before they can be used. Declaring a variable means
defining its value type , as in int, long, float, etc., setting a specified name, and optionally
assigning an initial value. This only needs to be done once in a program but the value can be
changed at any time using arithmetic and various assignments.
The following examples declares that inputvariable is an int, or integer type, and that its
initial value equals zero. This is called a simple assignment.
int inputvariable = 0;
A variable can be declared in a number of locations throughout the program and can the
variable.
2.3.3 Variable scope
A variable can be declared at the beginning of the program before void setup( ),
locally inside of functions, and sometimes within a statement block such as for loops. Where
the variable is declared determines the variable scope, or the ability of certain parts of the
program to make use of the variable.
A global variable is one that can be seen and used by every function and statement in
a program. This variable is declared at the beginning of the program, before the setup( )
function.
A local variable is one that is defined inside a function or as part of a loop. It is only
visible and can only be used inside the function in which it was declared. It is therefore
possible to have two or more variables of the same name in different parts of the same
program that contain different values. Ensuring that only one function has access to its
variables simplifies the program and reduces the potential for programming errors.
The following example shows how to declare a few different types of variables and
demonstrates each variable’s visibility:
int value; // ‘value’ is visible to any function
void setup ( )
{
// no setup needed
}
Void loop( )
{
for (int i=0; i<20; ) // ‘I’ is only visible inside the for-loop
{
i++;
}
float f; // ‘f’ is only visible inside loop
}
2.3.4 Int
Integers are the primary data type for storage of numbers without decimal points and
store a 16- bit value with a range of 2,147,483,647 to -2,147,483,648.
Long somevariable = 90000 ; //declares ‘somevariable’
// as a long type
2.3.5 Curly braces {}
Curly braces (also referred to as just “braces” or “curly brackets”) define the beginning
and end of function blocks and statement blocks such as the void loop() function and the for
and if statements.
Type function( )
{
Statements;
}
An opening curly brace { must always be followed by a closing curly brace}. This is
often referred to as the braces being balanced. Unbalanced braces can often lead to cryptic,
impenetrable complier errors that can sometimes be hard to track down in a large program.
The Arduino environment includes a convenient feature to check the balance of curly braces.
Just select a brace, or even click the insertion point immediately following a brace, and its
logical companion will be highlighted.
2.3.6 Semicolon ;
A semicolon must be used to end a statement and separate elements of the program. A
semicolon is also used to separate elements in a for loop.
int x = 13; // declares variable ‘x’ as the integer 13

2.3.7 Block comments /*….*/


Block comments, or multi-line comments, are areas of text ignored by the program
and are used for large text descriptions of code or comments that help others understand parts
of the program. They begin with /* and end with */ and can span multiple lines.
/* this is an enclosed block comment
Don’t forget the closing comment-
They have to be balanced!
*/
Because comments are ignored by the program and take no memory space they should be
used generously and can also be used to “comment out” blocks of code for debugging
purposes.
2.3.8 Line comments //
Single line comments begin with // and end with the nest line of code. Like block
comments, they are ignored by the program and take no memory space.
// this is a single line comment
Single line comments are often used after a valid statement to provide more information
about what the statement accomplishes or to provide a future remainder.
2.3.9 if… else
if… else allow for ‘either-or’ decisions to be made. For example, if you wanted to
test a digital input, and do one thing if the input went HIGH or instead do another thing if the
input was LOW,you would write that this way:
if (input pin == HIGH)
{
do ThingA;
}
else
{
do ThingB;
}
else can also precede another if test, so that multiple, mutually exclusive tests can be run the
same time.it is even possible to have an unlimited number of these else branches.Remember
though, only one set of statements will be run depending on the condition tests:
if (input Pin < 500)
{
doThingA;
}
else if (inputPin >= 1000)
{
doThingB ;
}
else
{
doThingC ;
}
2.3.10 For
The for statement is used to repeat a block of statements enclosed in curly braces a
specified number of times. An increment counter is often used to increment and terminate
the loop. There are three parts, separated by semicolons (;), to the for loop header:
for (initialization; condition; expression)
{
dosomething;
}
The initialization of a local variable, or increment counter, happens first and only once.
Each time through the loop, the following condition is tested. If the condition remains true,
the following statements and expression are executed and the condition is tested again. When
the condition becomes false, the loop ends. The following example starts the integer i at 0,
tests to see if i see still less than 20 and it true, increments i true, increments i by 1
and executes the enclosed statements:
for (int i=0; i<20; i++) // declares i, tests if less
{ // than 20 , increments i by 1
digital write(13, HIGH); //turns pin 13 on
delay(250); // pauses for ¼ second
digitalwrite(13, LOW); // turns pin 13 off
delay(250); // pauses for ¼ second
}

2.3.11 Structure
The basic structure of the Arduino programming language is fairly simple and runs in
at least two parts. These two required parts, or functions, enclose blocks of statements.
Void setup ( )
{
Statements;
}
Void loop ( )
{
Statements;
}
Where setup( ) is the preparation, loop() is the execution. Both functions are required for
the program to work.The setup function should follow the declaration of any variables at the
very beginning of the program. It is the first function to run in the program, is run only once,
and is used to set pin mode or initialize serial communication.The loop function follows next
and includes the code to be executed continuously- reading inputs, triggering outputs, etc.
This function is the core of all arduino programs and does the bulk of the work.
2.3.12 Setup( )
The setup( ) function is called once when your programs starts. Use it to initialize pin
modes, or begin serial. It must be included in a program even if there are no statements to
run.
Void setup ( )
{
pinMode (pin, OUTPUT); // sets the ‘pin’ as output
}
2.3.13 Loop( )
After calling the setup( ) function, the loop( ) function does precisely what its name
suggests and loop consecutively, allowing the program to change, respond, and control the
Arduino board.
Void loop ( )
{
digital Write (pin, HIGH); // turns ‘ pin’ on
delay (1000); // pauses for one second
digital Write (pin, LOW); // turns ‘pin’ off
delay (1000); // pauses for one second

2.3.14 Functions
A function is a block of code that has a name and a block of statements that are
executed when the function is called. The functions void setup() and void loop() have already
been discussed and other built-in functions wiil be discussed later. Custom functions can be
written to perform repetitive tasks and reduce clutter in a program. Functions are declared by
first declaring the function type. If no value is to be returned by the function type would be
void. After type, declare the name given to the function and in parenthesis any parameters
being passed to the function.
type functionName(parameters)
{
Statements;
}
The following integer type function delayVal( ) is used to set a delay value in a program
by reading the value of a potentiometer. It first declare the local variable v, sets v to the value
of the potentiometer which gives a number between 0-1023, then divides the value by 4 for a
final value between 0-255, and finally returns the value back to the main program.
int delayVal( )
{
int v; // create temporary variable ‘v’
v= analogRead(pot); // read potentiometer value
v /=4; // converts 0-1023 to 0-255
return v; // return final value
}
2.3.15 While:
While loops will loop continuously and infinitely,until the expression inside the
Parenthesis becomes false. Something must change the tested variable or the while loop will
never exit.this could be in your code such as an incremented variable or an external condition
such as testing a sensor.
While (some Variable ?? value)
{
doSomething ;
}

The following example tests whether ‘someVariable’ is less than 200 and true executes
the statements inside the brackets and will continue looping until ‘someVariable’ is no longer
less than 200.

While (someVariable <200) // tests if less than 200


{
doSomething;
someVariable++;
}
2.3.16 do…. While
The do loop is a bottom driven loop that works in the same manner as the while loop,
with the exception that the condition is tested at the end of the loop, so the do loop will
always run at least once.
do
{
doSomething;
} while (someVariable ?? value );
The following example assigns readSensors() to the variable ‘X’, pauses for
50 milliseconds, then loops indefinitely until ‘X’ is no longer less than 100:
do
{
X= readSensors ( ); //assings the value of readSensors ( )
to x
delay (50); // pauses 50 milliseconds
while (x < 100); // loops if x is less than 100
}

2.3.17 pinMode(pin,mode)
Used in void setup( )to configure a specified pin to behave either as an INPUT or an
OUTPUT.
pinMode (pin, OUTPUT) ; // sets ‘pin’ to output

Arduino digital pins default to inputs, so they do0n’t need to be explicity declared as
inputs with pinMode( ).Pins configured as INPUT are said to be in a high-impedance state.
There are also convenient 20KΩ pullup resistors built into the Atmega chip that can be
accessed from software. These built-in pullup resistors are accessed in the following manner:
pinMode (pin, INPUT); // set ‘pin’ to input
digitalWrite(pin, HIGH); // turn on pullup resistors

Pullup resistors would normally be used for connecting inputs like switches.Pins
configured as OUTPUT are said to be in a low-impedance state and can provide
40mA(milliamps) of current to other devices/circuits. This is enough current to run most
relays, solenoids, or motors.Short circuits on Arduino pins and excessive can damage or
destroy the output pin, or damage the entire Atmega chip. It is often a good idea to
connect an OUTPUT pin to an external device in series with a 470Ω or 1KΩ resistor.
2.3.18 DigitalRead(pin)
Reads the value from a specified digital pin with the result either HIGH or LOW.The
pin can be specified as either a variable or constant (0-13).
Value = digitalRead(pin); // sets ‘ value’ equal to the input pin
2.3.19 DigitalWrite(pin, value)
Outputs either logic level HIGH or LOW a specified digital pin. The pin can be
Specified as either a variable or constant(0-13).
DigitalWrite (pin, High); // sets ‘pin’ to high
The following example reads a pushbutton connected to digital input and turns on an
LED connected to a digital output when the button is pressed.
int led =13; // connect LED to pin 13
int pin = 7; // connect pushbutton to pin 7
int value = 0; // variable to store the read value
void setup( )
{
pinMode (led, OUTPUT); //sets pin 13 as output
pinMode (pin, INPUT); // sets pin 7 as input
}
Void loop( )
{
Value = digitalRead (pin); // sets ‘ value ’ equal to the input pin
digitalWrite (led, value); // sets ‘ led ’to the button’s value
}
2.3.20 analogRead(pin)
Reads the value from a specified analog pin with a 10-bit resolution. This function only
works on the analog in pins(0-5). The resulting integer values range from 0 to 1023.
Value = analogRead(pin); // sets ‘value’ equal to ‘pin’
2.3.21 analogWrite(pin,value)
Writes a pseudo-analog value using hardware enabled pulse width modulation (PWM)
to an output pin marked PWM. On newer arduinos with the ATmega168 chip, this function
works on pins 3, 5, 6, 9,10 and 11. Older Arduinos with an ATmega8 only support pins
9,10,11.the value can be Specified as a variable or constant with a value from 0-255.
analogWrite (pin,value); // writes ‘value’ to analog ‘pin’
A value of 0 generates a steady 0 volts output at the specified pin; a value of 255
generates a steady 5 volts output at the specified pin. For values in between 0 and 255, the pin
rapidly alternates between 0 and 5 volts – the higher the value ,the more often the pin is
HIGH(5 volts).
2.3.22 delay(ms)
Pauses your program for the amount of time as specified in milliseconds, where 1000 equals
1 second.
delay(1000); // waits for one second
2.3.23 Serial.begin(rate)
Opens serial port and sets the baud rate for serial data transmission. The typical baud
rate for communicating with the computer is 9600 although other speeds are supported.
void setup( )
{
Serial.begin(9600); //opens serial sets data rate to 9600 bps
}
CHAPTER 3

VISITING COUNTER USING ARDUINO

3.1 INTRODUCTION TO VISITOR COUNTER

It is a device used to increase or decrease the count of the people entering through
the in-gate or exiting through the exit-gate . It is designed to count the number of visitors
present in an auditorium, hall, room, offices, malls, sports venue, etc. Depending upon the
interrupt received from the sensors, the system identifies the entry or the exit of a visitor. It
counts when someone enters incrementing the count or decrementing the count when any one
leaves the hall. On the successful implementation of the system, the total number of persons
inside the room is displayed on the seven segment display or the LCD screen. This system
can be economically implemented in all the places where the visitors have to be counted and
the maximum capacity of the hall has to be maintained and controlled.

3.2 BLOCK DIAGRAM

IR SOURCE 1 IR
IN
DETECTOR
GATE
1

ARDUINO AT LCD
MEGA 328 DISPLAY
MODULE

OUT IR SOURCE 2 IR
GATE DETECTOR
2

3.3 PARTS EXPLANATION

 Infrared sensor (IR source and IR detector)


 Arduino AT MEGA 328
 Liquid crystal display (LCD)
3.3.1 INFRARED SENSOR

An infrared sensor is an electronic instrument which is used to sense the presence of


someone in the surroundings by emitting and detecting the infrared radiation. Infrared sensors
are also capable of measuring the heat being emitted by any object and detect its motion.
Infrared radiation is the portion of electromagnetic spectrum having wavelengths
longer than visible light wavelengths, but smaller than microwaves, i.e., the region is roughly
from 0.75µm to 1000 µm. Infrared waves are invisible to human eyes. The wavelength region
of 0.75µm to 3 µm is called near infrared, the region from 3 µm to 6 µm is called mid
infrared and the region higher than 6 µm is called far infrared. Infrared technology finds
applications in many everyday products. Televisions use an infrared detector to interpret the
signals sent from a remote control. The key benefits of infrared sensors include their low
power requirements, their simple circuitry and their portable features.

ELEMENTS OF INFRARED DETECTION SYSTEM

A typical system for detecting infrared radiation is given in the following block diagram:

INFRARED TRANSMISSION OPTICAL DETECTOR SIGNAL


SOURCE MEDIUM COMPONENT PROCESSING

1. Infrared Source
All objects above 0 K radiate infrared energy and hence are infrared sources. Infrared
sources also include blackbody radiators, tungsten lamps, silicon carbide, and various others.
For active IR sensors, infrared Lasers and LEDs of specific IR wavelengths are used as IR
sources.
2. Transmission Medium
Three main types of transmission medium used for Infrared transmission are
vacuum, the atmosphere, and optical fibers.
The transmission of IR – radiation is affected by presence of CO2, water vapour and other
elements in the atmosphere. Due to absorption by molecules of water carbon dioxide, ozone,
etc. the atmosphere highly attenuates most IR wavelengths leaving some important IR
windows in the electromagnetic spectrum; these are primarily utilized by thermal imaging/
remote sensing applications.
• Medium wave IR (MWIR:3-5 µm)
• Long wave IR (LWIR:8-14 µm)
Choice of IR band or a specific wavelength is dictated by the technical requirements
of a specific application.
3. Optical Components.
Often optical components are required to converge or focus infrared
radiations, to limit spectral response, etc. To converge/focus radiations, optical lenses made
of quartz, CaF2, Ge and Si, polyethylene Fresnel lenses, and mirrors made of Al, Au or a
similar material are used. For limiting spectral responses, bandpass filters are used. Choppers
are used to pass/ interrupt the IR beams.
4. Infrared detectors.
Various types of detectors are used in IR sensors. Important specifications of detectors are:
• Photosensitivity or Responsivity
Responsivity is the Output Voltage/Current per watt of incident energy.
• Noise Equivalent Power (NEP)
NEP represents detection ability of a detector and is the amount of incident light
equal to intrinsic noise level of a detector.
• Detectivity(D*: D-star)
D* is the photosensitivity per unit area of a detector. It is a measure of S/N ratio of a
detector. D* is inversely proportional to NEP. Larger D* indicates better sensing element.
In addition, wavelength region or temperature to be measured, response time,
cooling mechanism, active area, no of elements, package, linearity, stability, temperature
characteristics, etc. are important parameters which need attention while selecting IR
detectors.
5. Signal Processing
Since detector outputs are typically very small, preamplifiers with associated
circuitry are used to further process the received signals.

The Types of Infrared Sensors:

Infrared sensors are broadly classified into two main types:


 Thermal infrared sensors – use infrared energy as heat. Their photo sensitivity is
independent of the wavelength being detected. Thermal detectors do not require cooling
but do have slow response times and low detection capabilities.

 Quantum infrared sensors – provide higher detection performance and faster response
speed. Their photo sensitivity is dependent on wavelength. Quantum detectors have to be
cooled in order to obtain accurate measurements.

In this project the quantum infrared sensors are used.

3.3.2 LIQUID CRYSTAL DISPLAY (LCD)

A liquid crystal display or LCD is combination of two states of matter, the solid and the
liquid. LCD uses a liquid crystal to produce a visible image. It is the intermediary substance
between a liquid and solid state of matter. (e.g. soapy water) when a light passes through
liquid crystal it changes by an electrical charge. Liquid crystal display is composed of several
layers which include two polarized panel filters and electrodes. Light is projected from a lens
on a layer of liquid crystal. This combination of colored light with the grayscale image of the
crystal (formed as electric current flows through the crystal) forms the colored image. This
image is then displayed on the screen. Liquid crystal displays are super-thin technology
display screen that are generally used in laptop computer screen, TVs, cell phones and
portable video games. LCD’s technologies allow displays to be much thinner when compared
to cathode ray tube (CRT) technology. LCDs consume much less power than LED.
Construction of LCD:

To construct the LCD we need to take two polarized glass pieces filter in the making
of the liquid crystal. The glass which does not have a polarized film on the surface of it must
be rubbed with a special polymer which will create microscopic grooves on the surface of the
polarized glass filter. The grooves must be in the same direction of the polarized film. Now
we have to add a coating of pneumatic liquid phase crystal on one of the polarized filter of
the polarized glass. The microscopic channel cause the first layer molecule to align with filter
orientation. When the right angle appears at the first layer piece, we should add a second
piece of glass with the polarized film. The first filter will be naturally polarized as the light
strikes it at the starting stage.

Thus the light travels through each layer and guided on the next with the help of
molecule. The molecule tends to change its plane of vibration of the light in order to match
their angle. When the light reaches to the far end of the liquid crystal substance, it vibrates at
the same angle as that of the final layer of the molecule vibrates. The light is allowed to enter
into the device only if the second layer of the polarized glass matches with the final layer of
the molecule.

Working of LCD:
When an electrical current is applied to the liquid crystal molecule, the molecule
tends to untwist. This causes the angle of light which is passing through the molecule of the
polarized glass and also cause a change in the angle of the top polarizing filter. As a result a
little light is allowed to pass the polarized glass through a particular area of the LCD. Thus
that particular area will become dark compared to other. The LCD works on the principle of
blocking light. While constructing the LCD’s, a reflected mirror is arranged at the back. An
electrode plane is made of indium-tin oxide which is kept on top and a polarized glass with a
polarizing film is also added on the bottom of the device. The complete region of the LCD
has to be enclosed by a common electrode and above it should be the liquid crystal matter.

Next comes to the second piece of glass with an electrode in the form of the
rectangle on the bottom and, on top, another polarizing film. It must be considered that both
the pieces are kept at right angles. When there is no current, the light passes through the front
of the LCD it will be reflected by the mirror and bounced back. As the electrode is connected
to a battery the current from it will cause the liquid crystals between the common-plane
electrode and the electrode shaped like a rectangle to untwist. Thus the light is blocked from
passing through. That particular rectangular area appears blank.

Advantages of an LCD’s:

 LCD’s consumes less amount of power compared to CRT and LED


 LCD’s are consist of some microwatts for display in comparison to some mill watts
for LED’s
 LCDs are of low cost
 Provides excellent contrast
 LCD’s are thinner and lighter when compared to cathode ray tube and LED

Applications of Liquid Crystal Display

 Liquid crystal technology has major applications in the field of science and
engineering as well on electronic devices.
 Liquid crystal thermometer
 Optical imaging
 The liquid crystal display technique is also applicable in visualization of the radio
frequency waves in the waveguide.
 Used in the medical applications

ARDUINO IN LCD

The LiquidCrystal library allows us to control LCD displays that are compatible
with the Hitachi HD44780 driver. The LCDs have a parallel interface that is the
microcontroller has to manipulate several interface pins at once to control the display.
The interface consists of the following pins:

 A register select (RS) pin that controls where in the LCD's memory to write the data.
We can select either the data register, which holds what goes on the screen, or an
instruction register, which is where the LCD's controller looks for instructions on
what to do next.
 A Read/Write (R/W) pin that selects reading mode or writing mode.
 An Enable pin that enables writing to the registers.
 8 data pins (D0 -D7), The states of these pins (high or low) are the bits that to write a
register when we write, or to read the values when we read.
 There's also a display constrast pin (Vo), power supply pins (+5V and Gnd) that use
to power the LCD.
CHAPTER 4

4.2 CIRCUIT EXPLANATION

In this project we have implemented two IR transmitters and two IR detectors using
Infrared LEDS and an embedded microcontroller IC ARDUINO AT Mega 328 chip to count
the number of persons inside the hall. The IR transmitter 1 (IR source1) and IR detector 1 are
placed at the entrance of the IN-gate and the IR transmitter 2 & IR detector 2 are placed at the
Exit-gate.

As any person enters the IN gate the IR rays are absorbed and a trigger is produced
which is detected by the AT mega 328 chip at pin D8. Then the count is incremented by one
and the same is displayed on the LCD module which is connected to the AT mega 328 chip’s
out put pins 12,11,5,4,3,2. Similarly, when a person leaves the hall through the Exit-gate the
IR rays are absorbed and the trigger is produced which is detected by the AT mega 328 chip
at pin D9. The count is decremented by one and the same is displayed on the LCD module.
This process is repeated as the visitors enter or exit the hall. The count of the persons inside
the hall is displayed on the LCD module.

4.3 PROGRAM

#include <LiquidCrystal.h> // include the library code:

LiquidCrystal lcd (12, 11, 5, 4, 3, 2); // initialize the library with the numbers

of the interface pins.


int counter=0;

int buttonState;

int lastButtonState;

int buttonState1;

int lastButtonState1;

void setup()

lcd.begin(16, 2); // set up the LCD's number of columns

and rows:
pinMode(8, INPUT);

pinMode(9, INPUT);

Serial.begin(9600); // initialize the serial communications:

void loop()

buttonState = digitalRead(8);

if (buttonState = lastButtonState)

if (buttonState == HIGH)

counter++;

lastButtonState ! = buttonState;

buttonState1 = digitalRead(9);

if (buttonState1 != lastButtonState1)

if (buttonState1 == HIGH)

counter--;

lastButtonState1 = buttonState1;

if (counter<=0)
{

counter=0;

lcd.setCursor(0,0); // set the cursor to (0,0):

lcd.print("No.of people");

if (counter<10)

lcd.setCursor(0, 1); // set the cursor to (0,1):

lcd.print(counter);

lcd.setCursor(1,1); // set the cursor to (1,1):

lcd.print(" ");

else

lcd.setCursor(0, 1); // set the cursor to (0,1):

lcd.print(counter);

Serial.println(counter);

}
CHAPTER 5

CONCULSION

In this project ‘Visiting counter using Arduino’, I have implemented AtMega328 embedded
microcontroller to count the number of persons entering or exiting the hall. This counter will
display the actual number of persons inside the hall.

This can be used in banks, malls, theatres, seminar hall ctc. Also this can be installed in the
CAR parking areas (at the entry & the exit gates) where the parking capacity is limited and
indicate when the maximum capacity is reached.

This project can be further improved in future by sending this data to a remote location using
mobile or internet wireless connections.

An automatic voice alarm system can also be added to indicate that the room is full and no
more person can enter the hall.

Você também pode gostar