You are on page 1of 25

Arduino

What is Arduino?

Arduino is an open-source electronics platform based on easy-to-use hardware and


software. Arduino boards are able to read inputs - light on a sensor, a finger on a button, or a
Twitter message - and turn it into an output - activating a motor, turning on an LED,
publishing something online. You can tell your board what to do by sending a set of
instructions to the microcontroller on the board. To do so you use the Arduino
programming language (based on Wiring), and the Arduino Software (IDE), based
on Processing.

Over the years Arduino has been the brain of thousands of projects, from everyday objects to
complex scientific instruments. A worldwide community of makers - students, hobbyists,
artists, programmers, and professionals - has gathered around this open-source platform, their
contributions have added up to an incredible amount of accessible knowledge that can be of
great help to novices and experts alike.

Arduino was born at the Ivrea Interaction Design Institute as an easy tool for fast prototyping,
aimed at students without a background in electronics and programming. As soon as it
reached a wider community, the Arduino board started changing to adapt to new needs and
challenges, differentiating its offer from simple 8-bit boards to products for IoT applications,
wearable, 3D printing, and embedded environments. All Arduino boards are completely
open-source, empowering users to build them independently and eventually adapt them to
their particular needs. The software, too, is open-source, and it is growing through the
contributions of users worldwide.

An Arduino is an open-source microcontroller development board. In plain English, you can


use the Arduino to read sensors and control things like motors and lights. This allows you to
upload programs to this board which can then interact with things in the real world. With
this, you can make devices which respond and react to the world at large.

For instance, you can read a humidity sensor connected to a potted plant and turn on an
automatic watering system if it gets too dry. Or, you can make a stand-alone chat server
which is plugged into your internet router. Or, you can have it tweet every time your cat
passes through a pet door. Or, you can have it start a pot of coffee when your alarm goes off
in the morning.

Basically, if there is something that is in any way controlled by electricity, the Arduino can
interface with it in some manner. And even if it is not controlled by electricity, you can
probably still use things which are (like motors and electromagnets), to interface with it.

The possibilities of the Arduino are almost limitless. As such, there is no way that one single
tutorial can cover everything you might ever need to know. That said, I've done my best to
give a basic overview of the fundamental skills and knowledge that you need to get your
Arduino up and running. If nothing more, this should function as a springboard into further
experimentation and learning.

Why Arduino?

Thanks to its simple and accessible user experience, Arduino has been used in thousands of
different projects and applications. The Arduino software is easy-to-use for beginners, yet
flexible enough for advanced users. It runs on Mac, Windows, and Linux. Teachers and
students use it to build low cost scientific instruments, to prove chemistry and physics
principles, or to get started with programming and robotics. Designers and architects build
interactive prototypes, musicians and artists use it for installations and to experiment with
new musical instruments. Makers, of course, use it to build many of the projects exhibited at
the Maker Faire, for example. Arduino is a key tool to learn new things. Anyone - children,
hobbyists, artists, programmers - can start tinkering just following the step by step
instructions of a kit, or sharing ideas online with other members of the Arduino community.

There are many other microcontrollers and microcontroller platforms available for physical
computing. Parallax Basic Stamp, Netmedia's BX-24, Phidgets, MIT's Handyboard, and
many others offer similar functionality. All of these tools take the messy details of
microcontroller programming and wrap it up in an easy-to-use package. Arduino also
simplifies the process of working with microcontrollers, but it offers some advantage for
teachers, students, and interested amateurs over other systems:

 Inexpensive - Arduino boards are relatively inexpensive compared to other


microcontroller platforms. The least expensive version of the Arduino module can be
assembled by hand, and even the pre-assembled Arduino modules cost less than $50

 Cross-platform - The Arduino Software (IDE) runs on Windows, Macintosh OSX,


and Linux operating systems. Most microcontroller systems are limited to Windows.

 Simple, clear programming environment - The Arduino Software (IDE) is easy-to-


use for beginners, yet flexible enough for advanced users to take advantage of as well.
For teachers, it's conveniently based on the Processing programming environment, so
students learning to program in that environment will be familiar with how the
Arduino IDE works.

 Open source and extensible software - The Arduino software is published as open
source tools, available for extension by experienced programmers. The language can
be expanded through C++ libraries, and people wanting to understand the technical
details can make the leap from Arduino to the AVR C programming language on
which it's based. Similarly, you can add AVR-C code directly into your Arduino
programs if you want to.

 Open source and extensible hardware - The plans of the Arduino boards are
published under a Creative Commons license, so experienced circuit designers can
make their own version of the module, extending it and improving it. Even relatively
inexperienced users can build the breadboard version of the module in order to
understand how it works and save money.

Arduino Shields:

Shields are boards that can be plugged on top of the Arduino PCB extending its capabilities.
The different shields follow the same philosophy as the original toolkit: they are easy to
mount, and cheap to produce. Arduino shields are modular circuit boards that piggyback onto
your Arduino to install it with extra functionality. Shields are often supplied with either an
example sketch, or a library. So, not only do they just simply plug into your Arduino, but all
you need to do to make them work is upload up some example code to the Arduino.

Shield Form Factor:


Every Arduino shield must have the same form-factor as the standard Arduino. Power and
ground pins on one eight (previously six) pin header, and analog pins on a six-pin header next
to that. Digital pins cover the other edge on the other side, an eight-pin header separated from
a 10-pin by that weird 0.5" spacing. Some shields also require a connection to the Arduino’s
ICSP header (the 2x3 programming header on the end).

Some shields use every pin on the Arduino, while others only use a couple. When stacking
shields, it’s important to make sure they don’t use overlapping pins. Some shields
communicate with the Arduino via SPI, I2C, or Serial, and others use the Arduino’s interrupts
or analog inputs.

There’s a great variety of Arduino shields out there – too many to ever include in this tutorial.
On the next page we’ll go over a handful of the more popular and unique shields.

Shieldstravaganza
Here’s a list of SparkFun’s more popular and unique shields. This isn’t an exhaustive list of
all Arduino shields (for that, check out shieldlist.org), but it’s a good collection. They’re
sorted into semi-logical categories.
If you’re more visually inclined, check out our ShieldStravaganza Video Series (Part 1, Part
2, and Part 3). These three exciting videos are filled to the brim with shields, shields, shields,
oh…and more shields.

Prototyping (And Then Some)


Prototyping shields don’t add much functionality to the Arduino, but they do help in other
ways. These shields might do something as simple as breaking out the Arduino pins to screw
terminals. In general they make wiring to the Arduino easier.

 ProtoShield Kit - The self-titled star of this category. This shield is basically a big
prototyping area. You can stick a mini-breadboard on top, or just solder directly to the
shield’s prototyping area.
 ProtoScrew Shield - Like the ProtoShield, but each pin is also broken out to a screw
terminal. Handy for connecting to external motors or heavy-duty sensors.
 Go-Between Shield - The intention of this shield is to sit in between two shields. It
swaps the pins of the top shield, so they don’t interfere with each other.
 LiPower Shield - This shield allows you to power your Arduino with a Lithium
Polymer battery.

 Danger Shield - The most awesomest shield evar! This shield is a crazy
conglomeration of displays, potentiometers, and other sensors. Great for learning the
ins and outs of Arduino or incorporating into audio mixing projects.
 Joystick Shield Kit - This makes your Arduino a bare-bones controller. With a
joystick and four buttons, this makes for a great robot controller.
 microSD Shield - The Arduino has limited storage space, but this easy-to-use shield
(along with the SD library) allow for plenty of extra storage.

Ethernet, WiFi, Wireless, GPS, Etc.

 Arduino Ethernet Shield - This is one of the more classic shields. The Ethernet Shield
supplies your Arduino with an ability to connect to the world wide web. There’s a
great library to support it as well.

 WiFly Shield - SparkFun’s WiFi Shield mainstay, this shield equips your Arduino
with the ability to connect to 802.11b/g wireless networks. Then it can act as either a
web server, client, or both.
 Arduino Wi-Fi Shield - This is the Arduino Ethernet Shield sans wires. This shield
can get your Arduino connected to a WiFi router, so it can host webpages and scour
the Internet.
 Electric Imp Shield - Electric Imp is a unique WiFi module, which looks like an SD
card, but it packs a powerful cloud-based WiFi controller. This is probably the least
expensive WiFi-enabling Arduino shield.
 XBee Shield - XBee’s won’t get you connected to the Internet, but they do provide a
solid, cheap means for communicating wirelessly. You could use an XBee to
wirelessly trigger coffee machines, sprinklers, lights, or other household appliances.
 Cellular Shield w/ SM5100B - Turn your Arduino into a cellular phone! Send SMS
text messages, or hook up a microphone and speaker and use it to replace your
iPhone.
 GPS Shield - GPS isn’t as complicated as you might think. With a GPS Shield, your
Arduino will always know where it is.

Music and Sound

 MP3 Player Shield - Turn your Arduino into an MP3 player. Just plug in a µSD card,
add some speakers, upload the example code, and you can make your very own MP3
Playing Music Box

 Music Instrument Shield - Use the MIDI protocol to turn your Arduino into a bank of
musical instruments. It can make drums, piano, woodwinds, brass, and all sorts of
other sound effects.
 Spectrum Shield - The Spectrum Shield listens to audio, and sorts it into bins of
different frequencies. Use it to make a nifty graphic equalizer display.
 VoiceBox Shield - Give your Arduino a mechanical, robotic voice.

Displays and Cameras

 Color LCD Shield - Equip your Arduino with a unique 128x128 cellular phone color
LCD.

 EL Escudo - Electroluminescent wire is awesome! Use this shield to add up to eight


strands of EL wire to your project. You can finally make that Arduino-powered Tron
costume.
 CMUcam - This camera module adds vision to your Arduino. You can use it to track
blobs, so your robot doesn’t hit any traffic cones.

Motor Drivers

 Ardumoto Motor Driver Shield - This classic motor driver shield can control two DC
motors.

 Monster Moto Shield - If you need to drive beefier motors than the Ardumoto Shield
can handle, this is the next step up.
 PWM Shield - Usually when you think pulse-width modulation (PWM), you might
think “dimming LEDs”, but PWM is also used to drive servo motors. This shield can
be used to drive your crazy 12-servo hexapod.

Arduino Libraries:
The Arduino environment can be extended through the use of libraries, just like most
programming platforms. Libraries provide extra functionality for use in sketches, e.g.
working with hardware or manipulating data. To use a library in a sketch, select it
from Sketch>Import Library. A number of libraries come installed with the IDE, but you can
also download or create your own.

Standard Libraries

 EEPROM - reading and writing to "permanent" storage


 Ethernet / Ethernet 2 - for connecting to the internet using the Arduino Ethernet
Shield, Arduino Ethernet Shield 2 and Arduino Leonardo ETH

 Firmata - for communicating with applications on the computer using a standard serial
protocol.

 GSM - for connecting to a GSM/GRPS network with the GSM shield.

 LiquidCrystal - for controlling liquid crystal displays (LCDs)

 SD - for reading and writing SD cards

 Servo - for controlling servo motors

 SPI - for communicating with devices using the Serial Peripheral Interface (SPI) Bus

 SoftwareSerial - for serial communication on any digital pins. Version 1.0 and later of
Arduino incorporate Mikal Hart's NewSoftSerial library as SoftwareSerial.

 Stepper - for controlling stepper motors

 TFT - for drawing text , images, and shapes on the Arduino TFT screen

 WiFi - for connecting to the internet using the Arduino WiFi shield

 Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over a net of
devices or sensors.

The Matrix and Sprite libraries are no longer part of the core distribution.

Different Types of Arduino:

There are a number of different types of Arduinos to choose from. This is a brief overview of
some of the more common types of Arduino boards you may encounter. For a full listing of
currently support Arduino boards, check out the Arduino hardware page.

Arduino Uno

The most common version of Arduino is the Arduino Uno. This board is what most people
are talking about when they refer to an Arduino. In the next step, there is a more complete
rundown of its features.

Arduino NG, Diecimila, and the Duemilanove (Legacy Versions)


Legacy versions of the Arduino Uno product line consist of the NG, Diecimila, and the
Duemilanove. The important thing to note about legacy boards is that they lack particular
feature of the Arduino Uno. Some key differences:

 The Diecimila and NG use an ATMEGA168 chips (as opposed to the more powerful
ATMEGA328),
 Both the Diecimila and NG have a jumper next to the USB port and require manual
selection of either USB or battery power.
 The Arduino NG requires that you hold the rest button on the board for a few seconds
prior to uploading a program.

Arduino Mega 2560

The Mega is the second most commonly encountered version of the Arduino family. The
Arduino Mega is like the Arduino Uno's beefier older brother. It boasts 256 KB of memory (8
times more than the Uno). It also had 54 input and output pins, 16 of which are analog pins,
and 14 of which can do PWM. However, all of the added functionality comes at the cost of a
slightly larger circuit board. It may make your project more powerful, but it will also make
your project larger. Check out the official Arduino Mega 2560 page for more details.

Arduino Mega ADK

This specialized version of the Arduino is basically an Arduino Mega that has been
specifically designed for interfacing with Android smartphones.

Arduino LilyPad
The LilyPad was designed for wearable and e-textile applications. It is intended to be sewn to
fabric and connected to other sewable components using conductive thread. This board
requires the use of a special FTDI-USB TTL serial programming cable. For more
information, the Arduino LilyPad page is a decent starting point.
Arduino Uno Features

Some people think of the entire Arduino board as a microcontroller, but this is inaccurate.
The Arduino board actually is a specially designed circuit board for programming and
prototyping with Atmel microcontrollers.

The nice thing about the Arduino board is that it is relatively cheap, plugs straight into a
computer's USB port, and it is dead-simple to setup and use (compared to other development
boards).

Some of the key features of the Arduino Uno include:

 An open source design. The advantage of it being open source is that it has a large
community of people using and troubleshooting it. This makes it easy to find someone to
help you debug your projects.

 An easy USB interface . The chip on the board plugs straight into your USB port and
registers on your computer as a virtual serial port. This allows you to interface with it as
through it were a serial device. The benefit of this setup is that serial communication is an
extremely easy (and time-tested) protocol, and USB makes connecting it to modern
computers really convenient.

 Very convenient power management and built-in voltage regulation. You can connect an
external power source of up to 12v and it will regulate it to both 5v and 3.3v. It also can
be powered directly off of a USB port without any external power.

 An easy-to-find, and dirt cheap, microcontroller "brain." The ATmega328 chip retails for
about $2.88 on Digikey. It has countless number of nice hardware features like timers,
PWM pins, external and internal interrupts, and multiple sleep modes. Check out the
official datasheet for more details.

 A 16mhz clock. This makes it not the speediest microcontroller around, but fast enough
for most applications.

 32 KB of flash memory for storing your code.

 13 digital pins and 6 analog pins. These pins allow you to connect external hardware to
your Arduino. These pins are key for extending the computing capability of the Arduino
into the real world. Simply plug your devices and sensors into the sockets that correspond
to each of these pins and you are good to go.

 An ICSP connector for bypassing the USB port and interfacing the Arduino directly as a
serial device. This port is necessary to re-bootload your chip if it corrupts and can no
longer talk to your computer.

 An on-board LED attached to digital pin 13 for fast an easy debugging of code.

 And last, but not least, a button to reset the program on the chip.

Serial Monitor:
The serial monitor allows your computer to connect serially with the Arduino. This is
important because it takes data that your Arduino is receiving from sensors and other devices
and displays it in real-time on your computer. Having this ability is invaluable to debug your
code and understand what number values the chip is actually receiving.

For instance, connect centre sweep (middle pin) of a potentiometer to A0, and the outer pins,
respectively, to 5v and ground. Next upload the sketch shown below:

File --> Examples --> 1.Basics --> AnalogReadSerial


Click the button to engage the serial monitor which looks like a magnifying glass. You can
now see the numbers being read by the analog pin in the serial monitor. When you turn the
knob the numbers will increase and decrease.

The numbers will be between the range of 0 and 1023. The reason for this is that the analog
pin is converting a voltage between 0 and 5V to a discreet number.

Digital In:

The Arduino has two different types of input pins, those being analog and digital.
To begin with, lets look at the digital input pins.
Digital input pins only have two possible states, which are on or off. These two on and off
states are also referred to as:

 HIGH or LOW
 1 or 0
 5V or 0V.

This input is commonly used to sense the presence of voltage when a switch is opened or
closed.
Digital inputs can also be used as the basis for countless digital communication protocols. By
creating a 5V (HIGH) pulse or 0V (LOW) pulse, you can create a binary signal, the basis of
all computing. This is useful for talking to digital sensors like a PING ultrasonic sensor, or
communicating with other devices.

Digital Out:

A digital out pin can be set to be HIGH (5v) or LOW (0v). This allows you to turn things on
and off.
Aside from turning things on and off (and making LEDs blink), this form of output is
convenient for a number of applications.
Most notably, it allows you to communicate digitally. By turning the pin on and off rapidly,
you are creating binary states (0 and 1), which is recognized by countless other electronic
devices as a binary signal. By using this method, you can communicate using a number of
different protocols.

Analog In:

Aside from the digital input pins, the Arduino also boasts a number of analog input pins.
Analog input pins take an analog signal and perform a 10-bit analog-to-digital (ADC)
conversion to turn it into a number between 0 and 1023 (4.9mV steps).
This type of input is good for reading resistive sensors. These are basically sensors which
provide resistance to the circuit. They are also good for reading a varying voltage signal
between 0 and 5V. This is useful when interfacing with various types of analog circuitry.
Analog Out:

As mentioned earlier, the Arduino has a number of built in special functions. One of these
special functions is pulse width modulation, which is the way an Arduino is able to create an
analog-like output.
Pulse width modulation - or PWM for short - works by rapidly turning the PWM pin high
(5V) and low (0V) to simulate an analog signal. For instance, if you were to blink an LED on
and off rapidly enough (about five milliseconds each), it would seem to average the
brightness and only appear to be receiving half the power. Alternately, if it were to blink on
for 1 millisecond and then blink off for 9 millisecond, the LED would appear to be 1/10 as
bright and only be receiving 1/10 the voltage.
PWM is key for a number of applications including making sound, controlling the brightness
of lights, and controlling the speed of motors.

Write Your Own Code:

To write your own code, you will need to learn some basic programming language syntax. In
other words, you have to learn how to properly form the code for the programmer to
understand it. You can think of this kind of like understanding grammar and punctuation.
You can write an entire book without proper grammar and punctuation, but no one will be
abler to understand it, even if it is in English.

Some important things to keep in mind when writing your own code:

 An Arduino program is called a sketch.

 All code in an Arduino sketch is processed from top to bottom.

 Arduino sketches are typically broken into five parts.

1. The sketch usually starts with a header that explains what the sketch is doing, and
who wrote it.
2. Next, it usually defines global variables. Often, this is where constant names are given
to the different Arduino pins.
3. After the initial variables are set, the Arduino begins the setup routine. In the setup
function, we set initial conditions of variables when necessary, and run any
preliminary code that we only want to run once. This is where serial communication
is initiated, which is required for running the serial monitor.
4. From the setup function, we go to the loop routine. This is the main routine of the
sketch. This is not only where your main code goes, but it will be executed over and
over, so long as the sketch continues to run.
5. Below the loop routine, there is often other functions listed. These functions are user-
defined and only activated when called in the setup and loop routine. When these
functions are called, the Arduino processes all of the code in the function from top to
bottom and then goes back to the next line in the sketch where it left off when the
function was called. Functions are good because they allow you to run standard
routines - over and over - without having to write the same lines of code over and
over. You can simply call upon a function multiple times, and this will free up
memory on the chip because the function routine is only written once. It also makes
code easier to read. To learn how to form your own functions, check out this page.
 All of that said, the only two parts of the sketch which are mandatory are the Setup
and Loop routines.

 Code must be written in the Arduino Language, which is roughly based on C.

 Almost all statements written in the Arduino language must end with a ;

 Conditionals (such as if statements and for loops) do not need a ;

 Conditionals have their own rules and can be found under "Control Structures" on
the Arduino Language page

 Variables are storage compartments for numbers. You can pass values into and out of
variables. Variables must be defined (stated in the code) before they can be used and
need to have a data type associated with it.

Different Arduino Functions:

1. pinMode() :

Description
Configures the specified pin to behave either as an input or an output. See the description of
(digital pins) for details on the functionality of the pins.
As of Arduino 1.0.1, it is possible to enable the internal pullup resistors with the mode
INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pullups.
Syntax pinMode(pin, mode)
Parameters
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP. (see the (digital pins) page for a more
complete description of the functionality.)
Returns Nothing

2. digitalRead():
Description
Reads the value from a specified digital pin, either HIGH or LOW.
Syntax digitalRead(pin)
Parameters pin: the number of the digital pin you want to read
Returns HIGH or LOW

3. digitalWrite():

Description
Write a HIGH or a LOW value to a digital pin.

If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set
to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground)
for LOW.
If the pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable
(LOW) the internal pullup on the input pin. It is recommended to set
the pinMode() to INPUT_PULLUP to enable the internal pull-up resistor. See the
digital pins tutorial for more information.

If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when
calling digitalWrite(HIGH), the LED may appear dim. Without explicitly
setting pinMode(), digitalWrite() will have enabled the internal pull-up resistor, which
acts like a large current-limiting resistor.

Syntax digitalWrite(pin, value)


Parameters pin : the pin number
value: HIGH or LOW

Returns Nothing

4. analogWrite()

Description
Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying
brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin
will generate a steady square wave of the specified duty c ycle until the next call
to analogWrite() (or a call to digitalRead() or digitalWrite()) on the same pin. The
frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and
similar boards, pins 5 and 6 have a frequency of approximately 98 0 Hz.

On most Arduino boards (those with the ATmega168 or ATmega328P), this function
works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and
44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins
9, 10, and 11.
The Arduino DUE supports analogWrite() on pins 2 through 13, plus pins DAC0 and
DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to Analog converters, and
act as true analog outputs.
You do not need to call pinMode() to set the pin as an output before
calling analogWrite().
The analogWrite function has nothing to do with the analog pins or
the analogRead function.

Syntax analogWrite(pin, value)


Parameters
pin: the pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255 (always on). Allowed data
types: int

Returns Nothing

5. analogRead()

Description
Reads the value from the specified analog pin. The Arduino board contains a 6
channel (8 channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital
converter. This means that it will map input voltages between 0 and 5 volts into
integer values between 0 and 1023. This yields a resolution between readings of: 5
volts / 1024 units or, .0049 volts (4.9 mV) per unit. The input range and resolution can
be changed using analogReference().

It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum
reading rate is about 10,000 times a second.

Syntax analogRead(pin)
Parameters
pin: the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on
the Mini and Nano, 0 to 15 on the Mega)

Returns int(0 to 1023)

6. analogReference()
Description
Configures the reference voltage used for analog input (i.e. the value used as the top
of the input range). The options are:

 DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3
volts (on 3.3V Arduino boards)
 INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or
ATmega328P and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
 INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
 INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
 EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the
reference.
Syntax analogReference(type)
Parameters
type: which type of reference to use (DEFAULT, INTERNAL, INTERNAL1V1,
INTERNAL2V56, or EXTERNAL).

Returns Nothing

Serial Functions:
Used for communication between the Arduino board and a computer or other devices.
All Arduino boards have at least one serial port (also known as a UART or USART):
Serial. It communicates on digital pins 0 (RX) and 1 (TX) as well as with the
computer via USB. Thus, if you use these functions, you cannot also use pins 0 and 1
for digital input or output.You can use the Arduino environment’s built-in serial
monitor to communicate with an Arduino board. Click the serial monitor button in the
toolbar and select the same baud rate used in the call to begin().

Serial communication on pins TX/RX uses TTL logic levels (5V or 3.3V depending on
the board). Don’t connect these pins directly to an RS232 serial port; they operate at
+/- 12V and can damage your Arduino board.

The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18
(TX), Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX). To
use these pins to communicate with your personal computer, you will need an
additional USB-to-serial adaptor, as they are not connected to the Mega’s USB-to-
serial adaptor. To use them to communicate with an external TTL serial device,
connect the TX pin to your device’s RX pin, the RX to your device’ s TX pin, and the
ground of your Mega to your device’s ground.

The Arduino DUE has three additional 3.3V TTL serial ports: Serial1 on pins 19
(RX) and 18 (TX); Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and
14 (TX). Pins 0 and 1 are also connected to the corresponding pins of the
ATmega16U2 USB-to-TTL Serial chip, which is connected to the USB debug port.
Additionally, there is a native USB-serial port on the SAM3X chip, SerialUSB'.

The Arduino Leonardo board uses Serial1 to communicate via TTL (5V) serial on
pins 0 (RX) and 1 (TX). Serial is reserved for USB CDC communication. For more
information, refer to the Leonardo getting started page and hardware page.

1.Serial.available():

Description
Get the number of bytes (characters) available for reading from the serial port.
This is data that’s already arrived and stored in the serial receive buffer (which
holds 64 bytes). available() inherits from the Stream utility class.

Syntax Serial.available()
Parameter Nothing

Returns The number of bytes available to read .

2.Serial.available():

Description

Sets the data rate in bits per second (baud) for serial data transmission. For
communicating with the computer, use one of these rates: 300, 600, 1200, 2400,
4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200. You can, however,
specify other rates - for example, to communicate over pins 0 and 1 with a
component that requires a particular baud rate.
An optional second argument configures the data, parity, and stop bits. The defa ult
is 8 data bits, no parity, one stop bit.

Syntax

Serial.begin(speed) Serial.begin(speed, config)

Parameters

speed: in bits per second (baud) - long


config: sets data, parity, and stop bits. Valid values are

3.Serial.read():

Description

Reads incoming serial data. read() inherits from the Stream utility class.

Syntax Serial.read()

Parameters Nothing

Returns

The first byte of incoming serial data available (or -1 if no data is available) - int.

4.Serial.flush()

Description

Waits for the transmission of outgoing serial data to complete. (Prior to Arduino
1.0, this instead removed any buffered incoming serial data.)

flush() inherits from the Stream utility class.

Syntax Serial.flush()
Parameters Nothing

Returns Nothing

5.Serial.write()

Description

Writes binary data to the serial port. This data is sent as a byte or series of bytes;
to send the characters representing the digits of a number use the print() function
instead.

Syntax

Serial.write(val)
Serial.write(str)
Serial.write(buf, len)

6.Serial.print()

Description

Prints data to the serial port as human-readable ASCII text. This command can
take many forms. Numbers are printed using an ASCII character for each digit.
Floats are similarly printed as ASCII digits, defaulting to two decimal places.
Bytes are sent as a single character. Characters and strings are sent as is. For
example-

 Serial.print(78) gives "78"


 Serial.print(1.23456) gives "1.23"
 Serial.print('N') gives "N"
 `Serial.print("Hello world.") gives "Hello world." `

An optional second parameter specifies the base (format) to use; permitted


values are BIN(binary, or base 2), OCT(octal, or base 8), DEC(decimal, or base
10), HEX(hexadecimal, or base 16). For floating point numbers, this parameter
specifies the number of decimal places to use. For example-

 Serial.print(78, BIN) gives "1001110"


 Serial.print(78, OCT) gives "116"
 Serial.print(78, DEC) gives "78"
 Serial.print(78, HEX) gives "4E"
 Serial.println(1.23456, 0) gives "1"
 Serial.println(1.23456, 2) gives "1.23"
 Serial.println(1.23456, 4) gives "1.2346"

You can pass flash-memory based strings to Serial.print() by wrapping them


with F(). For example:

Serial.print(F(“Hello World”))
To send a single byte, use Serial.write().

Syntax

Serial.print(val)
Serial.print(val, format)

Parameters val: the value to print - any data type

Returns size_t: print() returns the number of bytes written, though reading
that number is optional.

7.Serial.peek()

Description

Returns the next byte (character) of incoming serial data without removing it from
the internal serial buffer. That is, successive calls to peek() will return the same
character, as will the next call to read(). peek() inherits from the Stream utility class.

Syntax Serial.peek()

Arduino advance I/O functions:

1.noTone()

Description

Stops the generation of a square wave triggered by tone(). Has no effect if no tone is
being generated.

Syntax noTone(pin)

Parameters

pin: the pin on which to stop generating the tone

Returns Nothing

2.pulseIn()

Description
Reads a pulse (either HIGH or LOW) on a pin. For example,
if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for
the pin to go LOW and stops timing. Returns the length of the pulse in microseconds.
Gives up and returns 0 if no pulse starts within a specified time out.
The timing of this function has been determined empirically and will probably show
errors in longer pulses. Works on pulses from 10 microseconds to 3 minutes in length.
Syntax
pulseIn(pin, value)
pulseIn(pin, value, timeout)
Parameters
pin: the number of the pin on which you want to read the pulse. (int)
value: type of pulse to read: either HIGH or LOW. (int)
timeout (optional): the number of microseconds to wait for the pulse to start; default is
one second (unsigned long)
Returns
the length of the pulse (in microseconds) or 0 if no pulse started before the timeout
(unsigned long)
Example Code

The example calculated the time duration of a pulse on pin 7.

int pin = 7;
unsigned long duration;

void setup()
{
pinMode(pin, INPUT);
}

void loop()
{
duration = pulseIn(pin, HIGH);
}

3. pulseInLong()
Description

Reads a pulse (either HIGH or LOW) on a pin. For example, if value is


HIGH, pulseInLong() waits for the pin to go HIGH, starts timing, then waits for the
pin to go LOW and stops timing. Returns the length of the pulse in microseconds or 0
if no complete pulse was received within the timeout.

The timing of this function has been determined empirically and will probably show
errors in shorter pulses. Works on pulses from 10 microseconds to 3 minutes in length.
Please also note that if the pin is already high when the function is called, it will wait
for the pin to go LOW and then HIGH before it starts counting. This routine ca n be
used only if interrupts are activated. Furthermore the highest resolution is obtained
with large intervals.

Syntax

pulseInLong(pin, value)
pulseInLong(pin, value, timeout)

Parameters
pin: the number of the pin on which you want to read the pulse. (int)

value: type of pulse to read: either HIGH or LOW. (int)

timeout (optional): the number of microseconds to wait for the pulse to start; default is
one second (unsigned long)

Returns
the length of the pulse (in microseconds) or 0 if no pulse started before the timeout
(unsigned long)

Example Code
The example calculated the time duration of a pulse on pin 7.

int pin = 7;
unsigned long duration;

void setup() {
pinMode(pin, INPUT);
}

void loop() {
duration = pulseInLong(pin, HIGH);
}

4.shiftIn()

Description

Shifts in a byte of data one bit at a time. Starts from either the most (i.e. the leftmost)
or least (rightmost) significant bit. For each bit, the clock pin is pulled high, the next
bit is read from the data line, and then the clock pin is taken low.

If you’re interfacing with a device that’s clocked by rising edges, you’ll need to make
sure that the clock pin is low before the first call to shiftIn(), e.g. with a call
to digitalWrite(clockPin, LOW).

Note: this is a software implementation; Arduino also provides an SPI library that uses
the hardware implementation, which is faster but only works on specific pins.

Syntax

byte incoming = shiftIn(dataPin, clockPin, bitOrder)


Parameters

dataPin: the pin on which to input each bit (int)

clockPin: the pin to toggle to signal a read from dataPin

bitOrder: which order to shift in the bits; either MSBFIRST or LSBFIRST. (Most
Significant Bit First, or, Least Significant Bit First)

Returns the value read (byte)

5.shiftOut()

Description

Shifts out a byte of data one bit at a time. Starts from either the most (i.e. the leftmost)
or least (rightmost) significant bit. Each bit is written in turn to a data pin, after which
a clock pin is pulsed (taken high, then low) to indicate that the bit is available.

Note- if you’re interfacing with a device that’s clocked by rising edges, you’ll need to
make sure that the clock pin is low before the call to shiftOut(), e.g. with a call
to digitalWrite(clockPin, LOW).

Syntax

shiftOut(dataPin, clockPin, bitOrder, value)

Parameters

dataPin: the pin on which to output each bit (int)

clockPin: the pin to toggle once the dataPin has been set to the correct value (int)

bitOrder: which order to shift out the bits; either MSBFIRST or LSBFIRST. (Most
Significant Bit First, or, Least Significant Bit First)

value: the data to shift out. (byte)

Returns Nothing

6.tone()

Description

Generates a square wave of the specified frequency (and 50% duty cycle) on a pin. A
duration can be specified, otherwise the wave continues until a call to noTone(). The
pin can be connected to a piezo buzzer or other speaker to play tones.
Only one tone can be generated at a time. If a tone is already playing on a different
pin, the call to tone() will have no effect. If the tone is playing on the same pin, the
call will set its frequency.

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards
other than the Mega).

It is not possible to generate tones lower than 31Hz. For technical details, see Brett
Hagman’s notes.

Syntax

tone(pin, frequency)

tone(pin, frequency, duration)

Parameters

pin: the pin on which to generate the tone

frequency: the frequency of the tone in hertz - unsigned int

duration: the duration of the tone in milliseconds (optional) - unsigned long

Returns Nothing

Array
Description

An array is a collection of variables that are accessed with an index number. Arrays in
the C programming language, on which Arduino is based, can be complicated, but
using simple arrays is relatively straightforward. === Creating (Declaring) a n Array

All of the methods below are valid ways to create (declare) an array.

int myInts[6];
int myPins[] = {2, 4, 8, 3, 6};
int mySensVals[6] = {2, 4, -8, 3, 2};
char message[6] = "hello";

You can declare an array without initializing it as in myInts.


In myPins we declare an array without explicitly choosing a size. The compiler counts
the elements and creates an array of the appropriate size.
Finally you can both initialize and size your array, as in mySensVals. Note that when
declaring an array of type char, one more element than your initialization is required,
to hold the required null character.

Accessing an Array

Arrays are zero indexed, that is, referring to the array initialization above, the first
element of the array is at index 0, hence

mySensVals[0] == 2, mySensVals[1] == 4, and so forth.

It also means that in an array with ten elements, index nine is the last element. Hence:

int myArray[10]={9,3,2,4,3,2,7,8,9,11};
// myArray[9] contains 11
// myArray[10] is invalid and contains random information (other memory address)

For this reason you should be careful in accessing arrays. Accessing past the end of an
array (using an index number greater than your declared array size - 1) is reading from
memory that is in use for other purposes. Reading from these locations is probably not
going to do much except yield invalid data. Writing to random memory locations is
definitely a bad idea and can often lead to unhappy results such as crashes or program
malfunction. This can also be a difficult bug to track down.

Unlike BASIC or JAVA, the C compiler does no checking to see if array access is
within legal bounds of the array size that you have declared.

To assign a value to an array: mySensVals[0] = 10;

To retrieve a value from an array: x = mySensVals[4];

Arrays and FOR Loops

Arrays are often manipulated inside for loops, where the loop counter is used as the
index for each array element. For example, to print the elements of an array over the
serial port, you could do something like this:

int i;
for (i = 0; i < 5; i = i + 1) {
Serial.println(myPins[i]);
}
Arduino Loops

for
Description

The for statement is used to repeat a block of statements enclosed in curly braces. An
increment counter is usually used to increment and terminate the loop.
The for statement is useful for any repetitive operation, and is often used in
combination with arrays to operate on collections of data/pins.

Syntax

for (initialization; condition; increment) {


//statement(s);
}

The initialization happens first and exactly once. Each time through the loop,
the condition is tested; if it’s true, the statement block, and the increment is
executed, then the condition is tested again. When the condition becomes false, the
loop ends.

While

Description

A while loop 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.

Syntax

while(condition){
// statement(s)
}

The condition is a boolean expression that evaluates to true or false.


do...While
Description

The do…while loop 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.

Syntax

do
{
// statement block
} while (condition);

The condition is a boolean expression that evaluates to true or false.

if..else

Description
The if…else allows greater control over the flow of code than the basic if statement,
by allowing multiple tests to be grouped together. An else clause (if at all exists) will
be executed if the condition in the if statement results in false. The else can proceed
another if test, so that multiple, mutually exclusive tests can be run at the same time.
Each test will proceed to the next one until a true test is encountered. When a true test
is found, its associated block of code is run, and the program then skips to the line
following the entire if/else construction. If no test proves to be true, the
default else block is executed, if one is present, and sets the default behavior.
Note that an else if block may be used with or without a terminating else block and
vice versa. An unlimited number of such else if branches is allowed.
Syntax
if (condition1)
{
// do Thing A
}
else if (condition2)
{
// do Thing B
}
else
{
// do Thing C
}
switchCase
Description

Like if statements, switch case controls the flow of programs by allowing


programmers to specify different code that should be executed in various conditions.
In particular, a switch statement compares the value of a variable to the values
specified in case statements. When a case statement is found whose value matches that
of the variable, the code in that case statement is run.

The break keyword exits the switch statement, and is typically used at the end of each
case. Without a break statement, the switch statement will continue executing the
following expressions ("falling-through") until a break, or the end of the switch
statement is reached.

Syntax

switch (var) {
case label1:
// statements
break;
case label2:
// statements
break;
default:
// statements
}
Parameters
var: a variable whose value to compare with various cases. Allowed data types: int,
char
label1, label2: constants. Allowed data types: int, char

Returns Nothing

You might also like