0% found this document useful (0 votes)
54 views137 pages

Basic Arduino Course Overview

The document outlines a Basic Arduino Course delivered remotely from April 18 to May 29, 2016, led by Juan Carlos López Gordillo. It includes objectives, content planning, and comparisons between official and unofficial Arduino boards, along with detailed descriptions of various Arduino models and their specifications. The course aims to equip participants with foundational knowledge of Arduino systems, programming, and practical applications in a structured six-week format.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views137 pages

Basic Arduino Course Overview

The document outlines a Basic Arduino Course delivered remotely from April 18 to May 29, 2016, led by Juan Carlos López Gordillo. It includes objectives, content planning, and comparisons between official and unofficial Arduino boards, along with detailed descriptions of various Arduino models and their specifications. The course aims to equip participants with foundational knowledge of Arduino systems, programming, and practical applications in a structured six-week format.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SPECIFIC CEFIRE OF F.P.

TEACHER TRAINING SERVICE

PROFESSIONAL FAMILY ELECTRICITY - ELECTRONICS


Vocational Training

BASIC COURSE
Delivered remotely
18 / 04 / 2016 -- 29 / 05 / 2016 ( 30 HORAS )

Speaker: Juan Carlos López Gordillo


Coordinadora : María Asunción León Blasco

CHAIR 2016
INDEX OF CONTENTS

Objectives 1

Content planning 2

Comparison between Official and Unofficial Arduino Boards. 4

Arduino Shields. 22

Introduction to Arduino. The Arduino UNO and the Arduino Mega 2560. 23

The official Arduino IDE. Installation, setup, and first steps. 31

Software related to Arduino. 41

The Arduino programming language. 51

Libraries for Arduino. 69

Engine Management. 74

How to use the EEPROM memory of Arduino 86

Sensors I: Light (LDR) and Ultrasonics (HC-SR04) 94

Sensors II: Infrared (IR) 103

Bounces 105

Strings in Arduino 110

Operation of a 16x2 LCD 112

Transmitter and receiver module for data at 433.92 MHz 115

Sensors III: Humidity and Temperature (DTH11, LM35 and DS18B20) 121

Introduction to the HTML language. The Ethernet Shield board. 126

Final comments 133

Bibliography 134

Index of Practices 135


Basic Arduino Course

Objectives

Know the existing Arduino boards and shields.


Obtain teaching resources for use in the classroom.
Conocer los fundamentos básicos de los sistemas basados en Arduino para poder
determine the capabilities and needs of a design.
Carry out the basic programming of an Arduino using the IDE and the language.
to have the foundation that allows for the development of simple control algorithms.
Resolve any syntax and programming errors that may occur.
Develop low to medium complexity applications based on Arduino that work for
autonomous mode or by connecting to a PC.
Conduct practices with the Ethernet shield board, creating very simple web pages and
communicate with Arduino.

Juan Carlos López Gordillo Page 1


Basic Arduino Course

Content Planning

I recommend dividing the contents as follows:

First week (From Monday 04/18/2016 to Friday 04/22/2016):

Comparison between Official Arduino Boards and Compatible Ones.


Arduino Shields.
Introduction to Arduino. The Arduino UNO and Arduino Mega 2560.
The official Arduino IDE. Installation, configuration, and first steps.

Second week (From Monday 04/25/2016 to Friday 04/29/2016):

Software related to Arduino.


The Arduino programming language.
Practice 1.
Libraries for Arduino.

Third week: (From Tuesday 05/03/2016 to Friday 05/06/2016):

Engine Management.
How to use the EEPROM memory of Arduino.
Practice 2.
Sensors I: Light (LDR) and ultrasound (HC-SR04).
Practice 3.

Fourth week (From Monday 05/09/2016 to Friday 05/13/2016):

Sensors II: Infrared (IR)


Rebounds.
Practice 4.
Strings in Arduino.
Control of a 16x2 LCD.
TX and RX Module by Radiofrequency (433.92 MHz).
Practice 5.

Fifth week (From Monday 16/05/2016 to Friday 20/05/2016):

Sensors III: Humidity and Temperature (DHT11, LM35, and DS18B20).


Practice 6.

Juan Carlos López Gordillo Página 2


Basic Arduino Course

Sixth week (From Monday 05/23/2016 to Friday 05/27/2016):

Introduction to the HTML language. The Ethernet Shield board.


Practice 7.
Submission of overdue assignments.
Extra practices or free project.

The Moodle platform will be used to facilitate communication among the attendees.
course and the speaker.

All assignments must be submitted (uploaded) before the deadline set.


the speaker will indicate on the Moodle platform.

Juan Carlos López Gordillo Page 3


Basic Arduino course

Comparison between official and unofficial Arduino boards

As with Linux distributions, Arduino also has a multitude of


editions, each designed for a specific audience or for a series of specific tasks.
There is such a variety of official, unofficial, and compatible models that it is normal for the
people do not know how to differentiate accurately the characteristics of each of these wonderful
plates.

Let's detail all the official models existing today, as well as present
some of the interesting unofficial and compatible ones. We must keep in mind that the
official Arduino models rise to more than 16 at the moment and there may be
hundreds if we add the compatible ones and the unofficial ones.

Official and unofficial or compatible Arduinos

We will make a distinction between official, unofficial, and compatible, since they are not the same.
same. Let's look at the differences between these groups of plates:

Officials: they are those official plates manufactured by the Italian company Smart.
Projects and some have been designed by the American company SparkFun.
Electronics (SFE) or by the also American Gravitech. Arduino Pro, Pro Mini and
LilyPad is manufactured by SFE and Arduino Nano by Gravitech, the rest is
they are created in Italy. These plates are the officially recognized ones, include the logo and are the
only those that can carry the registered trademark of Arduino.

Juan Carlos López Gordillo Page 4


Basic Arduino Course

Unofficial or compatible: these are boards compatible with Arduino but cannot be
registered under the name of Arduino. Of course, they are designed and manufactured by
other external companies. These developments do not contribute anything to the own development of
Arduino, but rather they are derivatives that have emerged to meet other needs. These
they often use a name that includes the suffix "duino" to identify them,
for example, Freeduino, which we will talk about later.

We can create our own plack compatible with Arduino.


measure and in this case it would become an unofficial plate. And the name under which we register
our invention cannot contain the
Arduino word. It may even be that
our design is sufficiently
attractive and eye-catching than the
members of the community of
Arduino development includes it.
like an official plaque. They are
waiting with open arms for
receive better and based plates
in other types of architectures (for
example, different from ARM and ATmega
AVR, like x86, PIC, ...).

Even in the Tools menu of Arduino IDE there is an option called Record
boot sequence. This option can be used to record the bootloader sequence
(bootloader) on the official Arduino microcontroller that for some reason has
it has become misconfigured or the microcontroller chip has been replaced by another. But it is also
A practical tool for programming a new microcontroller that we have introduced.
in our own plate 'duino'.

Not all are compatible to the same level.

For example, there are compatible boards at the development environment level, that is,
only software level (being able to use Arduino IDE to program them). Others are
compatible at the hardware and electrical level in order to use the shields and modules
existing for Arduino without problem.

When selecting the license for our project, we need to keep this in mind very
present so we don't get surprises. We might be interested in a compatible board for certain
hardware qualities that Arduino lacks or due to licensing issues and yet
want it to be compatible with the Arduino IDE development environment. At other times it may
that simply seeks compatibility regarding the shields but has the need to
use another compiler (AVR Studio, Makefiles, ...).

Juan Carlos López Gordillo Page 5


Basic Arduino course

General characteristics

The main thing we need to know is what type of projects we are going to implement. With
This gives us an idea of the number of analog and digital pins (normal and PWM type).
pulse width modulated to simulate an analog output) that we need for
our work. This first scrutiny allows us to discard some simpler plates that
not have enough pins or, on the contrary, discard those with the highest number of them to
reduce costs since we are satisfied with fewer pins.

We can also deduce the size of the code we are going to generate for our
sketchs. A very long program, with many constants and variables will demand an amount
larger flash memory for storage, so a board must be chosen
suitable so we don't fall short.

In the official Arduinos, we can distinguish between two fundamental types of


microcontrollers, the 8 and 32 bit ones based on ATmega AVR and the SMART ones based on ARM
of 32 bits and with superior performance, both created by the company Atmel.

Finally, regarding the voltage, they do not matter much at an electronic level, except
in some cases, to take into account the amount of stress that the plate can handle for
assemble our circuits.

The best-selling board that is most recommended for the majority of projects,
Everything if you are starting out, is the Arduino UNO. It's enough for most projects, it has
a good price and has balanced parameters.

Official plates

Among the official plates, you can find numerous models. All especially
designed for a purpose, compatible with official shields and modules, as well as with Arduino
IDE. We will try to detail their main features in order to differentiate them from each other:

Arduino UNO: it is the most widespread platform and the first one that came to market, for
Hello, we can base ourselves on this to make the
comparison with the rest of the boards. All the
characteristics of this board will be
implemented in almost all boards
remaining, except for a few that already
We will see. It is based on a microcontroller.
Atmel ATmega320 8-bit at 16MHz that
it works at 5v. 32KB corresponds to the
flash memory (0.5KB reserved for the
bootloader), 2KB of SRAM and 1KB of EEPROM.
In terms of memory, it is one of the most limited boards, but that doesn't make it less so.
insufficient for almost all projects that circulate the network. The outputs can
work at higher voltages, between 6 and 20v but a voltage of
operates between 7 and 12v. It contains 14 digital pins, 6 of which can be used.
as PWM. Regarding analog pins, there are up to 6. These pins can
work with current up to 40mA.

Juan Carlos López Gordillo Page 6


Basic Arduino Course

Arduino Zero: in appearance, it is similar to Arduino UNO, but this board hides
surprises regarding the UNO platform.
Instead of the Atmel ATmega microcontroller
based on 8-bit AVR architecture, the Zero
it contains a powerful Atmel SAMD21 MCU of
48MHz with a 32-bit ARM Cortex M0 core.
With 256 KB of flash memory, 32 KB of SRAM and
an EEPROM of more than 16KB by emulation. The
the operating voltage is 3.3V/5V (7mA) and
it contains 14 digital I/O pins, of which 12
they are PWM and UART. In the analog field, it
it has 6 inputs for a 12-bit ADC channel and an analog output for DAC
10 bits. Ultimately, this board is intended for those whose Arduino UNO is insufficient.
short and need a bit more processing power.

Arduino Yun: it is based on the ATmega32u4 microcontroller and an Atheros chip.


AR9331 (which controls the USB host, the micro-SD port, and the Ethernet/WiFi network),
both communicated through a bridge. The
Atheros processor supports the Linux distribution
based on OpenWrt called OpenWrt-Yun. It
it's about a board similar to Arduino UNO but
with native capabilities for Ethernet connection,
WiFi, USB and micro-SD without the need to add or
buy shields separately. Contains 20 pins
digital, 7 can be used in PWM mode and
12 as analogs. The microcontroller
The ATmega32u4 at 16MHz operates at 5V and contains only 32KB of memory (4KB)
reserved for the bootloader), only 2.5KB of SRAM and 1KB of EEPROM. As we can see, in
this sense falls short. However, it is complemented by the AR9331 at 400MHz
based on MIPS and operating at 3v3. This chip also contains 64MB DDR2 RAM and
16MB flash for an embedded Linux system.

Arduino Leonardo: is a board based on a low-power ATmega32u4 microcontroller.


consumption and operates at 16MHz. The flash memory has a capacity of 32KB (4KB
for the bootloader) and 2.5KB of SRAM. The
EEPROM is 1KB, also very similar to
Arduino UNO in terms of capabilities of
storage. At the electronic level and of
voltages is equal to ONE. But this
microcontroller can handle 20 pins
digital (7 of them can be managed as
PWM) and 12 analog pins. As we can see,
it contains the same pins as Yun, only that
it does without network functionalities. The
the volume occupied by Leonardo is less than that of ONE, as it lacks the
pin insertions and instead has perforations with connection pads in the
own board. In addition, the dimensions of the USB connector on the board are much smaller,
since it uses a mini-USB instead of a USB connection to save space.
that is ideal for projects where some space savings are required, but everything
at the same price as ONE.

Juan Carlos López Gordillo Page 7


Basic Arduino Course

Arduino Due: is a board with an Atmel SAM3X8E ARM Cortex-M3 microcontroller


32-bit. This chip operates at 84 MHz.
(3,3v) provides a considerable computing power
superior to the previous microcontrollers
seen. That is why it is ideal for all those
that need a project with high
processing capacity. By having a core
32 bits allows performing operations with
4 bytes of data in a single clock cycle.
In addition, the SRAM memory is 96KB, higher than the other boards seen.
previously and incorporates a DMA controller for direct memory access that
intensifies the memory access that the CPU can do. For storage, it
it has 512KB of flash, a very large amount of memory for any
programming code. In terms of voltage support under intensities, it is identical to
ONE, only that the current of the pins extends up to 130-800mA (for 3v3 and
5V respectively). The system has 54 digital I/O pins, 12 of them
they can be used as PWM. It also has 12 analogs, 4 UARTs (serial, against
the two of UNO), USB OTG connection capabilities, two DAC connections (conversion
from digital to analog), 2 TWI, a power jack, SPI, and JTAG. As we see regarding the interface
The wiring is very complete and allows for a multitude of possibilities.

Arduino Mega: its name comes from the microcontroller that manages it, a
ATmega2560. This chip operates at 16MHz and with a voltage of 5V. Its capabilities are
higher than the ATmega320 of the Arduino UNO,
although not as superior as the solutions
based on ARM. This 8-bit microcontroller
works together with an 8KB SRAM,
4KB of EEPROM and 256KB of flash (8KB for the
bootloader). As you can see, the
the features of this board are similar to the Due,
but based on AVR architecture instead of
ARM. In terms of electronic features, it is quite similar to the previous ones,
especially to the ONE. But as can be seen at a glance, the number of pins is
similar to the Arduino Due: 54 digital pins (15 of them PWM) and 16 pins
analogous. This board is ideal for those who need more pins and power than
it contributes ONE, but the necessary performance does not require resorting to ARM-based.

Arduino Ethernet: It is an Arduino UNO and an integrated Ethernet shield. This board is
quite similar to the UN, even in the
aspect, but it has networking capabilities. Its
the microcontroller is an ATmega328 that
operates at 16MHz (5V). It is accompanied by 2KB
of SRAM, 1KB of EEPROM and 32KB of flash. The
the rest of the electronic characteristics are like
the ones from UNO only that adds capacity to
Ethernet connection thanks to a controller
W5100 embedded TCP/IP and possibility of
conectar tarjetas de memoria microSD. Los
The available pins are 14 digital (4 PWM) and 6 analog. It should be taken into account that
that Arduino reserves pins 10-13 to be used for SPI, pin 4 for the SD card and the
2 for the W5100 switch.

Juan Carlos López Gordillo Page 8


Basic Arduino Course

Arduino Fio: It is an Arduino board reduced to its minimum expression. Due to its size, it is
especially considered for projects
wireless phones or to be inserted into
reduced spaces. Works with a
ATmega328P microcontroller, a version
similar to that of Ethernet but works at a
lower frequency, 8MHz. Being so reduced
lacks certain comforts, for example,
To upload the sketches, you need to use an FTDI cable or an additional adapter board.
Sparkfun. Likewise, the voltages used are reduced to the
3.35-12v maximum. 14 digital pins (6 PWM) and 8 analog pins will be the only ones.
available on this board. It also doesn't help that it has 2KB of SRAM, 32KB of flash, and 1KB of
EEPROM, all of this will greatly limit the size of the sketches and the circuit of the
project.

Arduino Nano: They started by incorporating an ATMega328 like the one in other boards.
previously seen, but after the 2.x review it was replaced by a 16MHz ATmega168.
Its dimensions are even smaller than
those of Fio, measuring only 18.5×43.2mm. Its
reduced size does not take away the possibility of
to be a complete plate, but it does need
of a mini-USB cable and does not have a connector of
external feeding. This version was
designed and produced by the company
Gravitech, specially designed for
low-cost applications where size matters. At an electrical level
It behaves like a UNO, with 14 digital pins (6 PWM) and 8 analog ones. But its
capacities have decreased with the new revisions in favor of lower consumption.
Therefore, it has changed from 32 to 16KB of flash (2 reserved for the bootloader), from
2 KB of SRAM and from 1 KB to 512 bytes of EEPROM.

Arduino LilyPad: Specially designed to be integrated into garments and textiles, that is, it is a
"available" version of Arduino. It was developed
by Leah Buechley and SparkFun Electronics for
to be employed for the same purposes as others
Arduino's only with certain limitations to
change in their integration capabilities and their
base flexible. It is based on two versions of
different microcontrollers, both low
consumption referred to as Atmega168V and
ATmega328V, this second one is more powerful.
Both work at 8MHz, but the first one
It works at only 2.7v and at second at 5.5v. It has
of 14 digital pins (6 PWM) and 6 analog to
along its perimeter. It also integrates 16KB
of flash memory for the program code, 1KB of SRAM, and 512 bytes of EEPROM.

Juan Carlos López Gordillo Page 9


Basic Arduino Course

Arduino Pro: Contains an ATmega168 or Atmega328 microcontroller, with


versions of 3.3V and 8MHz or 5V for 16MHz.
It contains 14 digital I/O pins (6 of them are
PWM) and 6 analog pins. This board is designed
and built by SparkFun Electronics integrates
between 32KB and 16KB of flash according to the
microcontroller it is based on (2KB
reserved for the boot manager). What is certain is
it is common for all models is the KB of
SRAM and the 512 bytes of EEPROM. Despite its
name, the Pro version is not one of the most
powerful as we can see. But it has
designed for advanced users who
they need flexibility and low prices.

Arduino Pro Mini: It is the smaller sister of the version


Pro. In addition to flexibility and low prices, there is a need to
to add its reduced size. To reduce cost and size
has the minimum components (without USB connector
Integrated with pin connectors). The rest of the features
they are very similar to the Pro version.

Arduino Mega ADK: Board based on an ATmega2560 like the Mega version.
previously. But its main advantage
Does it have a prepared interface?
to be connected via USB to
mobile devices based on Android,
thanks to its IC MAX3421e. This allows
to have all the capabilities of a
Arduino Mega board (the same regarding the
remaining characteristics) plus the
joint development opportunities with
an Android platform.

Arduino Esplora: It differs from the other boards, apart from its small size and
due to its shape, it has a series of onboard sensors. It is good for the
people who begin to give their
first steps in the world of
electronics and they are learning, hence their
name. Includes some sensors
(accelerometer, temperature, light)
buzzers, buttons, joystick, microphone and
a socket to connect a screen to
TFT LCD color. It works with a microcontroller ATmega32u4 that operates at 16MHz and
5v, with 2.5KB of SRAM and 1KB of EEPROM. The flash reaches 32KB with 4KB reserved.
the bootloader. The biggest problem is its connectivity capability, which is almost nonexistent, since
everything is integrated for beginners.

Juan Carlos López Gordillo Page 10


Basic Arduino Course

Arduino Micro: Designed by Adafruit and aimed at high autonomy and with
a small size. Its price is
low compared to other models.
However, it has
similar characteristics to others
designs, like a microcontroller
ATmega32u4 at 16Mhz, 20 pins
digital (7 of them PWM) and 12
analogous. In many ways it is similar to Leonardo, but with the ability to
built-in USB communication, eliminating the need for a second processor.

Arduino BT: it is an Arduino board with a module


Built-in Bluetooth that allows
wireless communication without the need for
buy an independent shield. The module
the built-in Bluetooth is a Bluegiga WT11. The
the rest of the characteristics are similar to Arduino
UNO, with ATmega168 or 328 microcontroller
16MHz.

Arduino Duemilanove: It appeared in 2009, with microcontroller ATmega168 or 368, 14


digital pins (6 with PWM capability) and 6
analog. It has a USB connection, input of
nutrition, an ISCP header, button of
reset,... everything quite similar to UNO since
it is a previous version that was
replaced by ONE currently.

Arduino Diecimila: Another old board based on


DIP chip ATmega168 at 16Mhz, with 14 pins
digital (6 PWM) and 6 analog. The rest of
characteristics are similar to the more modern UNO
what has been released to replace these
more primitive designs. The model "Diecimila"
it gets its name from 'ten thousand' in Italian, way in
the one who celebrated having sold more
of 10,000 Arduino boards at the time when
released for sale. It was one of the oldest records.
from Arduino, taken in 2007.

Juan Carlos López Gordillo Page 11


Basic Arduino Course

Unofficial (compatible) plates

We will only analyze the most famous ones since, as I mentioned, there are hundreds of them.
They and probably every day more of these plates are born. It is indeed true that the majority
we must pay attention to the official models for support and
developer community that may seem obvious, but it must be acknowledged that some boards
compatibles are certainly interesting:

[Link] U+: SlicMicro is the creator of this compatible board, both in hardware as well
in software, with Arduino UNO Rev3. This
open source hardware platform adds
characteristics in front of the official. To pass the code
from Arduino IDE we must select the option
Arduino UNO Rev3 as if it were ours
license plate and the code will load without issues. The
additional features that integrates (SlicBus
Port, an additional LED, potentiometer, button.
The rest is the same as the Arduino, including its ATmega328
that shares with some official versions. This
the board is interesting for those looking for the combined features of Arduino
UNO and Esplora, although more limited in onboard gadgets than the latter. What is certain is
one advantage is its SlicBus port which allows connecting special modules manufactured by
SlicMicro.

SainSmart UNO and Mega: they are two SainSmart boards fully compatible with Arduino.
UNO and with Arduino Mega that have followed the official branch
step by step, even in the reviews (see SainSmart UNO
Rev3). Even in terms of physical appearance and color, they are quite
identical to the official ones, not to mention in their characteristics
techniques, using even the same microcontroller. The
The price of Mega is around 15 euros and the UNO version is 8.
euros. We can verify that the great advantage of these plates is
its price compared to the official ones. Some characteristics are the
use of an ATmega8u2 chip programmed to control
the USB and convert it to serial instead of the method used
previously with controller chip. The
encapsulation of the chips, which in these boards is more advanced than the primitive DIP of
UNO official.

Braduino: it is based on UNO with rearranged LEDs, mini-USB connector, alteration of the
pin 13 of the circuit to restart the LED and a
resistance that does not interfere with the function of the pin
when it acts as an input. It was designed with
free software like KiCAD and is distributed under
GPLv2 license. For the rest of the features, it is
identical to the official and fully compatible with
this. It has been created by the Brazilians of
Holoscope for students, designers and
apprentices of the world of electronics. But
keep in mind that your availability is more

Juan Carlos López Gordillo Page 12


Basic Arduino course

limited than the stock of the officials.

ChibiDuino2: created by the Japanese from TiisaiDipJp. It is compatible with UNO and includes two
mini-USB B, a port for a 1602 LCD and a breadboard area.
For the rest, it is similar in characteristics to the official, except in
its size, which is more reduced, due to its distribution and its
the price is quite economical.

Diavolino: Created by Evil Mad Scientist Laboratories, it is a compatible version of the


layout (that is, the pins are located in the same place and
therefore it is compatible with the official shields) from Arduino
UNO and designed for the use of a USB-TTL serial cable. Its
the design is attractive because it breaks with the colorful
conventional. The design arises from the need of a hacker
from San Francisco to have a low-cost plate for the
teaching.

Freeduino: It is one of the most famous among the


not official created by Solarbotics, it is a board
totally free for open source lovers. It
sells in SB, NANO, and Mega versions, among others, and
100% compatible with their respective versions
officials. In the image we can see Freeduino SB
(compatible with Duemilanove), with a very design
rudimentary that almost gives a homemade feeling. But I don't know
They must not be deceived by appearances, their possibilities are the same as those of the
officials.

Rascal: Compatible with official Arduino shields, but it is programmed in language of


Python programming. This makes it
interesting for those new to the world of
programming, since Python may be the
best language to start programming,
simple and straightforward. This contrasts with the
advanced possibilities that allows
implement. Rascal Micro has created this board
with an ARM-based microcontroller, the
AT91SAM9G20. This board was born in Massachusetts, in 2011 and although its price is high
(about 175 dollars), can offer possibilities that no official one has. One could say
what is a mix between a mini-PC with the ability to run Linux, with network ports and
SD slot for storage, and an Arduino board compatible with its shields.
It also includes software to create a web server with it. From the system itself,
You can program using a very simple and practical web-based editor.

Juan Carlos López Gordillo Page 13


Basic Arduino Course

Romeo 2012: DFRobot has created this board specifically designed for enthusiasts.
from robotics or mechatronics. It is totally
compatible with Arduino UNO Rev3 pin to pin and
its electronic and characteristics of
Programming is similar. The interesting thing is
that includes a series of features
onboard that the officials do not have,
highlighting, for example, the controller of
motors (in two directions and up to 2A). Another
features is a Xbee socket that allows
start the project immediately, without
need for a motor controller
additional or Wireless shields. It also works with an Atmega32u4 microcontroller,
accompanied by a multitude of programmable buttons and a socket for a module
APC220 and Bluetooth.

Roboduino is a derivative of Arduino UNO designed


for robotics creed by Curious Inventor. It is
compatible with the official, with a price of about 30
euros. As you can see in the photograph, it has a
series of parallel pins to connect sensors and
servomotors in an easier way, just like
includes power and communication connections
additional serials.

Seeeduino: SeeedStudio has created this compatible board, both physically and
software level, with official Arduino Diecimila.
Therefore, there will be no problem using
Arduino IDE and the official shields. In its version
first had an ATmega168, being able to choose
by an ATMega328 starting from v2.21. Certain
parts have been remodeled to provide
greater flexibility and a good experience of
user.

Twenty Ten: Freetronics created this compatible board and


based on Duemilanove with a prototyping area
included, LEDs, mini-USB connector and a modified pin 13
so that the LED and resistor do not interfere with the
function of the pin when it is activated as an input.

Juan Carlos López Gordillo Page 14


Basic Arduino Course

Zigduino: Logos Electromechanical has created this kit that is more than just a simple board. It integrates
an ATmega128RFA1 microcontroller, a ZigBee for
connections to wireless network (IEEE 802.15.4). Also
includes an external RPSMA jack and is fully
compatible with Arduino Duemilanove. When implementing
these network functionalities without the need for shields
externally, the price of the plate exceeds 50 euros.

Faraduino: it is a board developed by Middlesex University Teaching Resources. It is


compatible with official shields, with a
integrated H-bridge circuit, with terminals
to assemble direct current motors
integrated (3 servos), etc. By the way, for the
more curious, its name is due to the famous
Michael Faraday. Everything is offered in a kit that
we can acquire along with some accessories
for Faraduino specially designed for
education in schools and learning robotics.

Motoduino: Guibot has been responsible for creating this board with an ATMega328 and a
L293D with double H bridge for control
of motors without the need for elements
additional externals. For the rest of
features, this Chinese board is compatible
with Arduino. This board is interesting
to create vehicles with electric motors and
the use of motors in small robots.

FlyDuino Mega: designed by Paul Bake to be


totally compatible with Arduino Mega but with
special features to be used for the
design of autopiloted and autonomous vehicles with
multirotor for aircraft. It is interesting if you are a
passionate about home-built airplanes or those of
fashion drones. Their size is small, like
You will understand that it is very important for this type of vehicles where volume and weight
they are critical.

Banguino: it is a board designed by Dimitech and based on an ATmega328.


The board is compatible at the software level, but not at the physical level.
It is a small-sized board. As for
Features are similar to Arduino UNO, only improved.
in a standard PLCC68 socket to be integrated into projects
of reduced size.

Juan Carlos López Gordillo Page 15


Basic Arduino Course

Boarduino: it is a board created by Adafruit and compatible at the software level with
Arduino, but not at a physical level. So no.
it can be used with the official shields. Its
characteristics are similar to an Arduino
Ten thousand, but its size is smaller and
It's quite a bit cheaper. It is
specially designed to be inserted in
a breadboard type plate.

Femtoduino: ultra small board measuring just 20.7×15.2mm, barely larger than a
coin. This plate was designed by Fabio
Varesano for very small projects.
Integrates an ATMega3298P-MU and is compatible.
at the software level with Arduino.

JeeNode:JeeLabs has created a low-cost board,


reduced size, software compatible with
Arduino and with an integrated Hope RF RFM12B for
wireless communication.

Moteino: LowPowerLab has created a mini board the size of an SD card with
wireless communication possibilities thanks to the RFM12B or RFM69W/HW/CW chip
from HoperRF. It is compatible at the software level,
so you can program with Arduino IDE
using an FTDI adapter or directly
via USB interface in the Moteino version
USB.

PicoDuino: Peter Misenko created this tiny


board compatible with Arduino IDE, although it
I recommend programming with Digispark IDE. It is based on
in a tiny microcontroller called
ATTiny85. It is only 22x12mm in size.
It has an RGB LED, a reset button, and is ideal
for small-scale projects.

Juan Carlos López Gordillo Page 16


Basic Arduino Course

Sanguino: compatible with Arduino at the software level and based on an ATmega644.
despite its small size, it integrates 64KB of
flash, 4KB SRAM and 32 general-purpose pins
general. It was developed together with the
RepRap 3D printer project.

SODAQ: with the size of a Raspberry Pi board,


SODAQ is a board built by Solar Powered
Data Acquisition. It has a series of sockets for
additional connections for Xbee modules, Rfbee,
Bluetoothbee and GPRSbee for communications. It has
a power supply with Li-Po battery of
3.7v or via microUSB. The battery can be charged through
solar panels and has a panel for it
2.5w, in addition to a battery monitor that indicates its
It includes a power on and off switch, a DS3231 RTC, and a sensor of
temperature for battery control, and an ICSP programming header.

TinyDuino: TinyCircuits has implemented an Arduino-compatible board.


software and with the same functionalities as Arduino
UNO, but with a reduced size. It has the shape of
button and can be expanded with various shields
appropriate.

TinyLily: from the same manufacturer as TinyDuino, this version arrives.


what aims to replace the official LilyPad or at least compete in the
same sector. It is very small and designed for e-design
textiles. It contains some tabs for communication and
programming.

Versalino Uno: Virtualbotix creates this compact and compatible design at the level of
software with Arduino. Its main
characteristic is the distribution of its
components, which has allowed to make a
very compact and smaller size plate, like this
such as the placement of its connection pins
that are not arranged transversely to
the board, but in parallel to save space.

Juan Carlos López Gordillo Page 17


Basic Arduino Course

Leaflabs Maple: almost all models are based on Atmega AVR chips or chips from
Atmel based on ARM. But this board breaks.
with that scheme and integrate an ARM STM32 (ARM
32-bit Cortex-M3 at 72MHz) manufactured by
STMicroelectronics. Leaflabs has created this board.
with a compact design that is compatible with the
shields, despite their architecture. The
programming can be done using Open
Maple IDE that implements the language
Arduino to avoid having to relearn another one.
programming language, as well as libraries
low-level native.

Bambino 210: this board accepts the shields of


Arduino, but it is not compatible with Arduino IDE
Why do they use very different microcontrollers?
to those seen previously. Microint USA has equipped
to this NXP LPC4330 processor board, a
dual-core ARM Cortex M4/M0 with 264KB SRAM,
4MB flash, Ethernet, 8MB flash, microSD and socket
for Xbee add-ons. That is, a very board
powerful for large projects.

Parallax Propeller(buy it on eBay)the famous


Parallax company, known for BASIC Stamp boards among others, has wanted to join
this initiative creating a Propeller plate
compatible with Arduino shields, but not
at the software level (programming is done with a
free tool called Propeller Tool or
an IDE Tool alternative). It contains a chip
Parallax P8X32A Propeller, with architecture
multicore with 32-bit RISC CPUs. Its
programming is done in language
assembler or in Spin language (designed by
Chip Gracey and engineer Jeff Martin from
Parallax). This board, with its 32KB of RAM and
32KB of ROM, along with the rest of the features, makes it ideal for the most
professionals. The biggest problem is that it is not an open-source board.

TheUno: designed by MyFreescaleWebPage, contains a Freescale microcontroller


(old Motorola factories) S08DZ60 of 8
bits and can support Arduino shields. In
as for programming, it is not compatible with
Arduino and it has to be programmed by an IDE
CodeWarrior from Freescale (based on Eclipse).
The languages used are C and assembly.
two powerful languages to optimize for
maximize the performance of this board. For the
interesados, también existe una placa llamada
BigBrother from the same creators as
TheUno integrates a more powerful Freescale MCF51AC256 (Coldfire) than its
little brother. For the rest of the characteristics, it is similar to TheUno.

Juan Carlos López Gordillo Page 18


Basic Arduino Course

Goldilocks: Thin Layer Embedded designed this board based on an FPGA (Altera Cyclone
IV, with DDR2 RAM, SRAM, flash, oscillator and a
Atmel ATSHA204 Authentication IC/EEPROM
to offer extreme flexibility. It is
compatible with Arduino shields, but in
in this case you will not only be able to program it at the level of

software, but also at the hardware level


thanks to its FPGA. This same company also
it has another very similar model called
Breadstick with some male pins especially
designed to be inserted into a breadboard.

Pinguino: it is an open-source development board type 'duino' with a microcontroller


PIC. The brain that commands this board is a
Microchip's PIC18F2550 chip. To
to have an integrated USB module in the
microcontroller, does not need an interface
UART/USB, as in the case of Arduino, for
communicate with the PC. Its hardware is simple and
it has an integrated development environment (IDE)
similar to Arduino IDE, but it is not compatible
with this. The code can be written in language
of Python programming, an extremely simple language. Great board for
the initiated and those interested in mastering system programming based on
PICxxx.

pcDuino: it is a miniPC like the Raspberry Pi, only that it combines the features of
a development board like Arduino. It has an HDMI port to connect it to
a screen or your TV to use it as a monitor
of the system, in addition to other USB ports and slot
for microSD memory cards So you can
connect peripherals as in the case of the Raspi,
including those that add network functionalities.
It can boot operating systems like Ubuntu.
Android ICS, among other Linux distributions.
To move these systems comfortably available
1GB of RAM, 2GB of onboard flash, processor
ARM Cortex A8 (based on ARM11) at 1GHz and a
GPU Mali 400 (the same that are integrated in Samsung)
Galaxy S3). All of this makes it the perfect companion for the most advanced users.
who want an all-in-one (duino platform + miniPC) with superior hardware
to the Raspberry Pi.

Netduino Plus 2: is a development board very similar


an Arduino, but with a very striking peculiarity,
uses the .NET Micro Framework for its
programming using the Visual C# Express IDE
Edition. It has a 32-bit ATmel ARM at 120MHz,
compatible with most Arduino shields.

Juan Carlos López Gordillo Page 19


Basic Arduino course

Freaduino: Arduino compatible board


official created by Elecfreaks. Very similar
also to the Sparkfun RedBoard and whose
creators have taken Arduino as a base
UNO for its creation. Its hardware and
the features are similar to those of Arduino, but
its price drops to $18.60. 100% compatible
at the electronic and software level with Arduino
UNO.

Teensy: it is a development board based on a microcontroller, like all of them, but


is presented on a small plaque. It
connect to the PC using a mini USB cable.
It can be acquired in different versions that
vary in their specifications and size. Their
the price does not vary much depending on the version,
since in all cases it is maintained by
below $24. Version 2.0 is based on
an AVR microcontroller (an ATMega from Atmel)
like those of Arduino), while the version
3.x is based on an ARM chip. The software to program it is not compatible with it.
Arduino IDE but there is an add-on called Teensyduino for it. Other options for
Software used to employ the WinARV C compiler and others.

Funduino: it is a copy of the official board. This


clon has various editions such as the official one,
as ONE, TWO THOUSAND NINE, NANO, MEGA,
etc..., but its technical characteristics and
programming is identical to the official one. Moreover, neither
they would have bothered to change the color.

Ruggeduino: is a board compatible with Arduino UNO (including at the software level) and
similar in almost all aspects to the official one. As such
we only found some very variations
interesting for electronics, such as the
integration of electronic protection against ESD
in its pins and electrical connections, thing of the
which the official UNO lacks. Its price amounts to
$39.95

More and more Arduino-based boards are appearing, especially unofficial ones. But
how to check what to look for when acquiring a board is if
we want hardware compatibility, software compatibility, or both.
Next, we will see if the board we want to purchase has the hardware that
we want to use. However, as of today, for education and due to the price difference,
I recommend acquiring either the Arduino UNO or the Arduino Mega 2560 with more.
benefits.

Juan Carlos López Gordillo Page 20


Basic Arduino Course

Let's take a comparative table between some Arduino boards:

Juan Carlos López Gordillo Page 21


Basic Arduino course

The Arduino Shields

Unshields a printed circuit board that can be connected at the top of


Laplace Arduino to expand its capabilities, being able to be stacked on top of each other.
another.

It is possible to stack various shields although the upper image is already a case.
extreme not advisable.

The shields have quite designs.


simple and generally open source, the
designs are usually published freely.
We can find shields a little more
sophisticated, including a unit of measurement
inertial with a structure in six gyroscopes
DOF for its use as part of a pilot
automatic in a model airplane.

As you can imagine, there are many Shields designed by various


manufacturers, others designed by collaborating individuals and others that are designed by
individuals with specific needs. There is a list of shields with the details of
its connections and the basic specification here on this website :

[Link]

I suggest to the reader to check out that website and analyze the information from different sources.
shields, we in this course will use the Ethernet shield, which will allow us to perform
applications that can be controlled and/or monitored via the web.

Juan Carlos López Gordillo Page 22


Basic Arduino Course

Introduction to Arduino
Arduino is a development platform for physical computing.
open source, based on a board with a simple microcontroller and an environment of
development to create software (programs) for the board.

We can use Arduino to create interactive objects, reading data from a large
variety of switches and sensors and control a multitude of types of lights, motors, and others
physical actuators. Projects with Arduino can be autonomous or communicate with a
program (software) that runs on a computer.

The board and the development software are open and we can download them for free from the
[Link]/en/Arduino can be powered through the USB connection or
with an external power supply. The power supply is selected
automatically.

Hardware and USB cable

Technical specifications

Juan Carlos López Gordillo Page 23


Basic Arduino Course

The Arduino UNO


The constitution of the Arduino UNO board is as follows:

1.- ATmega328 microcontroller


It is a microcontroller from the company .
Characteristics
Operating Voltage: 5V
Flash Memory: 32 KB of which 512 bytes
they are used by the bootloader.
SRAM 2 KB, EEPROM 1 KB, Velocidad del Reloj
16 MHz, pre-installed bootloader.

2.- Reset Button: Supply a value


LOW(0V) to reset the microcontroller.

3.- ICSP: Connector for ICSP (In Circuit Serial Programming, or Programming
Serial in circuit). The ICSP is the system used to program the devices without
need to remove the chip from the circuit of which it is a part.
4, 5, 6 and 7: Digital Input/Output Pins:

Each of the 14 digital pins can be used


like an input or an output.

They can provide or receive a maximum of 40


mA and they have a pull-up resistor
(disconnected by default) from 20 to 50 KΩ.

Some pins have specialized functions such as:

Pin 0 (RX) and 1 (TX). It is used to receive (RX) and transmit (TX) TTL serial data.
Pins 2 and 3. External interrupts. These are pins responsible for interrupting the
sequential program established by the user. They can be configured to
activate an interrupt on a low value, a rising or falling edge, or
a change in value.
Pines 3, 5, 6, 9, 10 and 11. PWM (pulse width modulation)
width modulation).
They consist of 6 PWM output bits with the analogWrite() function.
Pin 13. LED. There is an SMD LED with its current limiting resistor connected to this.
pin. It is also the only pin that contains an integrated limiting resistor in the
Arduino board in series with the pin. Being able to connect an external LED between this pin and
GND directly.
SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins serve as support for the
SPI communication with the SPI library. The SPI Bus (from English Serial Peripheral
Interface) is a communications standard, primarily used for the
information transfer between integrated circuits in electronic equipment.

Juan Carlos López Gordillo Page 24


Basic Arduino Course

8.- GND: Ground pins.

9.- AREF: Reference tension for the


analog inputs. It is used with
analogReference ()

10.- USB: Arduino Uno has a series of


facilities to communicate with a
computer using the channels of
communication of this series via USB and
appears as a virtual COM port on the
computer. It uses the standard USB COM drivers and does not require any driver.
external. However, in Windows a .inf file is necessary. The RX and TX LED of the board
They blink when data is transmitted through the USB to the serial chip and vice versa.

11.- Power connector: 2.1mm female plug for the power connection in the
plate.

12, 13, 14, 15 and 16. - Power Pins

If we power the Arduino through the connection


USB or via an external power source (from 7 to 12V),
we are going to have some continuous voltage outputs
due to some voltage regulators and
stabilization capacitors that it has.

These pins are:

VIN: Input pin for an external voltage source that will serve to
power the Arduino.
5V: Output pin, regulated voltage source of 5V, this voltage can
either come from the VIN pin, the USB connector, or another 5V source
regulated.
3.3V: Output pin, 3.3-volt source generated by the FTDI chip
integrated with a maximum current consumption of 50mA.
GND: ground pins.
Reset: A LOW (0V) value can be applied to reset the
microcontroller. Typically used to add a reset button to the
shields that do not allow access to this button on the board.

Juan Carlos López Gordillo Page 25


Basic Arduino Course

17.- Analog In: Arduino UNO has 6 inputs


analogous, and each of them provides
a resolution of 10 bits (1024 values). For
the defect is measured from ground to 5 volts, although
Is it possible to change the upper limit of this?
range using the AREF pin (9 in the diagram) and the
analogReference() function.

18.- Crystal: A 16MHz oscillator crystal.

Here we can see the LEDs it has.


integrated the Arduino UNO board, as well as the
current limiting resistor in series with pin 13.

The ATMEGA328 microcontroller, as already mentioned, is manufactured by ATMEL, its datasheet


it can be downloaded from:
[Link]

For a more in-depth study or for a subject where it is studied


microcontrollers, one should study the microcontroller internally, but in this case,
we are going to limit ourselves to using this microcontroller from the Arduino board and with it
bootloader installed.

However, throughout this course, it is possible that there will be some mention of something.
characteristic of this microcontroller and we should consult the datasheet to clarify the
functioning.

Juan Carlos López Gordillo Page 26


Basic Arduino Course

Juan Carlos López Gordillo Page 27


Basic Arduino course

The Arduino MEGA 2560

We can observe that the Arduino MEGA


2560 is larger in terms of plate.
regarding the Arduino UNO. It also has
of 54 digital input/outputs, 16 inputs
analog signals. It has three communications
TTL series, 5 external interruptions and possibility
to configure up to 14 pins as output
PWM. Being fully compatible with
Arduino UNO regarding software. The shields
designed for Arduino UNO are completely
compatible as can be checked in the
figure, but you have to be careful to place it
in its correct place (Note the digital pin 0)

Juan Carlos López Gordillo Page 28


Basic Arduino Course

Juan Carlos López Gordillo Page 29


Basic Arduino Course

Juan Carlos López Gordillo Page 30


Basic Arduino course

IMPORTANT:
According to the board we have, we will have to select it in the Arduino IDE.
This manual has used the Arduino UNO board and the Arduino Mega board.

The official Arduino IDE

Installation of the Arduino IDE


It is advisable to deposit this software on our computer so that it does not get lost.
Lose it there, let's open a folder for everything related to Arduino, that we can
Call it whatever you want, but I suggest it be called 'Arduino'. In this folder, in different
In subfolders, we will neatly store all the generated files.

Download the necessary software

We need to install the IDE (integrated development environment) software of


development, and also install the Arduino drivers, (device drivers). All the material
what we need, we reduce it from

[Link]

There is a page in Spanish whose address is[Link] but I don't know


find updated, so we will use the English page.
We will download the latest version of the IDE from the (Download) section, which will be
available for the following operating systems, Windows, Mac OS X and Linux: 32 bit and 64 bit.
We also have the sources of those programs available for download, as they
OPEN SOURCE software.

In our case, we will download the version for Windows. Upon completion of the download
we will obtain a compressed folder, (of the .zip type) that we must decompress in the folder
"Arduino", keeping the structure of the folder we have downloaded.

Juan Carlos López Gordillo Page 31


Basic Arduino Course

Install the Arduino drivers

To install the drivers on Windows, we will follow these steps:

1. Connect Arduino UNO to the PC using the type A-B USB cable.

2. The Windows 7 operating system detects the device and will attempt to install the
drivers, but it will not install them because it cannot find them.

3. We will access the 'Home' button - 'Control Panel' and click on


Device Manager

4. In the Device Manager window, under 'Other devices' we


must show 'Arduino Uno' with an exclamation mark in a yellow circle,
we will right-click and select 'Refresh'
controller software

Juan Carlos López Gordillo Page 32


Basic Arduino Course

5. We will click on 'Search for driver software on the computer. Search and install.
the manual shape controller software.” We will press the button
Click 'Browse' to select the folder where the drivers are located.

6. We will select the folder "Arduino" and, within it, the folder "Arduino
1.0.x/drivers and click 'Next'.

7. The assistant for installing a new driver will show us a notice of


security, we click 'Install this driver software anyway'.

Juan Carlos López Gordillo Page 33


Basic Arduino Course

8. If everything is correct, the assistant will have installed the driver for
Arduino UNO and it will show us in a window. The exclamation with the circle
yellow must have disappeared.

9. The Device Manager of Microsoft Windows 7 will show us the


new driver installed in "Ports (COM & LPT)". It is important that
let's note the name assigned to the COM port for Arduino, in our case
COM3, since we will need to select it in the Arduino IDE.

First steps with Arduino


Once we have studied the Arduino UNO board, we have installed
the development IDE and the appropriate drivers, we connect Arduino UNO
via the USB cable to our PC and run the development IDE by
double click on the file '[Link]'.

A window like the following will appear:

We must first note that


We have 4 differentiated zones.
Menu area, Icon area, Work area and
Message or notification area.

Once the application is opened, we need to configure some


parameters, for that, the first thing we need to do is click on
"Tools", then "Card" and we will choose the board that
we have, that is to say 'Arduino UNO'.

Later we will go to 'Tools' again and click


this time in "Serial Port" (if it is disabled it means}

Juan Carlos López Gordillo Page 34


Basic Arduino Course

that the application has not found our Arduino) and we select the Port where the
the system has recognized our Arduino (see point 9 of the driver installation).

Finally, we will click on 'File' and then on 'Preferences', and we will modify the
window according to the following figure:

The location of the Sketchbook (Arduino calls it


the Sketch programs, drawing in Spanish
it can be anyone, we will use
C:\Arduino\MySketch will be where
guard all our Sketch (Programs).

We will activate the boxes to show us


the detailed result during the compilation,
that I check the code after loading and
that automatically associates the files
with the '.ino' extension using the Arduino IDE.

Description of the menus

- File Menu:
It has the same options as any program
based on Windows (New, Open, Close, etc...) and
algunas opciones añadidas como por ejemplo:
Sketchbook: If we position ourselves on top, they will unfold.
all the Sketches that we have saved inside our
Sketchbook.
Examples: If we position ourselves on top, all will be displayed.
the examples that the Arduino IDE provides by default.
Upload: It is used to send the sketch to the Arduino board.
Load using Programmer: It is used to upload the sketch
to the Arduino board using an external programmer.

- Edit Menu:

It has the same options as any program.


based on Windows (Undo, Redo, Cut, etc...) and
some added options such as for example:

Copy to the forum, copy as HTML, increase


margin, reduce margin, etc..., whose function can be
check easily and they are not important to him
functioning of the sketch.

Juan Carlos López Gordillo Page 35


Basic Arduino Course

- Sketch Menu:
This menu has the following options:
Add FileImport Library
they add a file or to our Sketch
a bookstore.

The options to Check / Compile


Show the Sketch folder, they carry out the
function that describes.
- Tools Menu:

Automatic Format:
Establish
adequately the
tabs for
our sketch

Archive the Sketch: Compress all open sketches in the IDE and save them by default.
in the Arduino folder in the documents folder of our PC. Create a single *.zip file

Repair Encoding and reload: Compile and upload the sketch we are working on,
discarding all changes made since the last save.

Monitor Serial: Opens a monitoring system that allows us to visualize data.


sent by the microcontroller or send them to the microcontroller.

Card: We choose the type of Arduino board we are working with.

Serial port: We choose the port where we have connected the Arduino board.

Programmer: We choose the type of programmer in case we do not use the own board.
Arduino as a programmer.

Record Boot Sequence: It gives us the possibility to record the Arduino bootloader in
a microcontroller to be able to use the Arduino IDE.

Juan Carlos López Gordillo Page 36


Basic Arduino Course

- Help Menu :

As we can observe, we have several


options that, when clicked on, open
a webpage that is related to the
chosen option. The most used option is going to
as a reference, which will help us to
search for the functions, libraries, etc... of the
language used by Arduino.

Description of the icon area

By clicking on these icons, the functions explained earlier are performed.


it deals with shortcut icons for functions that are performed regularly.

Verify Open New

Load Save Monitor Serial

Description of the notification area

The notifications area is the zone of the Arduino IDE where the compiler will give us
information about possible errors, which board we have connected and to which port. We also
indicates which line we have the cursor in within the work area.

Juan Carlos López Gordillo Page 37


Basic Arduino Course

Description of the work area

The workspace is the editable area of the Arduino IDE where we will write our
code to later compile it and transfer it to the board. In the Arduino environment
we can have as many functions as we want (user-defined) but at a minimum
we will have two: setup() and loop()

The Arduino IDE,


assign a name
automatic to the sketch
composed of 'sketch_'
followed by the first 3
Characters of the month "Mar"
followed by 2 digits
numerical of the date '10'
and followed by a letter starting with 'a' and increasing as we create
new sketches. In the example shown in the figure, it is the first sketch 'a', which was completed on the 10th.
of March "mar". Of course, the name can be modified.

The names that have the character § at the end are because they have been modified and have not
have been saved.

The code located in the setup() function will run only once, when the system starts up.
that is, when starting the microcontroller (not to be confused with the bootloader). They are usually configured
los pines como entradas o salidas en esta función o inicializar algún dispositivo. El código que
let's place in the function loop() instead, it will run indefinitely (loop means loop in
English)

In the Arduino environment, the reserved words by the compiler change.


automatically formatted. Another feature is the differentiated treatment of letters
uppercase and lowercase.

Juan Carlos López Gordillo Page 38


Basic Arduino course

Example Blink Program

In 1972 Dennis Ritchie and Brian W. Kernighan published "The Programming Language"
C”. 40 years later, it is regarded as the beginning of high-level programming, the basis of the
most of the languages we know today and where the famous example of 'Hello' appears
World. Since then it has been common to name, as Dennis and Brian did, 'Hello World'
when the first test is performed in any programming language. In the world of the
physical computing, the equivalent of 'Hello World' is 'Blink', alternate
between a high and low state on a digital pin configured as output. Next, we are going to
load our "Blink" on our Arduino.

We open the Arduino IDE and


we click on :
File–Examples– Basics–
Blink

The example 'Blink' is studied next, although it is not essential for the reader.
fully understand each line, it is important to understand the algorithm that is
uses.

Description: You can start the code with a brief description of the functionality of
our sketch. Let's note that we use the instructions "/*" and "*/" to introduce
comments of more than one line.

Function setup( ): This function is executed only once when the system starts. In this case only
We use it to configure pin 13 of our Arduino UNO as output. We use the
pinMode function for that. When the comment occupies a single line we use the double
bar '//'. Pin 13 has an LED connected on the board itself in almost all models of
Arduino.

Juan Carlos López Gordillo Page 39


Basic Arduino Course

Function loop(): This function will run while the board is powered and not in
reset. With the digitalWrite function ( led, HIGH ), we write a high state to pin 13 (if
we measure the voltage at the pin, we will measure 5V). Then we make the microcontroller
wait for a while with the delay function. This function causes a wait in milliseconds in
function of the parameter used in its call. Later we will comment on things about this.
famous but dangerous function. After waiting, we write a low state on the same pin.
with the digitalWrite function (led, LOW), (if we measure the voltage at the pin, we will measure 0V) and
before writing a high state again, we wait a little for 1000
milliseconds.
If we consider that this function runs indefinitely, we already have the blinking of the pin.
as we wanted.

To check it, we click on the 'upload' icon and


after a while we will see how our led begins to
to blink.

From now on, all the sketches we create will be uploaded to Arduino in the same way.
way, so the process of uploading a sketch to Arduino will no longer be explained.

Juan Carlos López Gordillo Page 40


Basic Arduino Course

Software related to Arduino

One of the advantages of Arduino is, besides its simplicity, the possibility of
develop our code through graphical environments based on icons, a good option
if we don't want to waste much time creating the software or if we want to learn the
basics of programming.

Minibloq

Minibloq is a tool that allows us to program any board.


Arduino, whether Mega, UNO, Duemilanove, etc., and also its variants like Seeduino
Oh Duinobot. Through simple icons, it is possible to create complex codes with little
effort. Furthermore, I was struck by the fact that it is possible to see the code in C++
of Arduino equivalent to the list of instructions we have created. For more
information and download links visit their blog.

Minibloq programming environment

Modkit (alpha)

Modkit allows you to program a wide variety of microcontrollers: Arduino,


Seeduino, LillyPad and a long list. It also allows you to see the code we have created.
with icons and also modify it, which is great not only for beginners but also
to save time and work for the more experienced. It is currently located in
alpha version, and there will be a free version and a paid one. For more information visit
the official website of the project.

Juan Carlos López Gordillo Page 41


Basic Arduino course

Example of a program with Modkit

S4A

S4A or Scratch for Arduino is a modification of the popular Scratch designed


exclusively for Arduino boards. S4A aims to provide a beginner's platform for
world of programming, as well as a powerful and high-level tool for
programmers who use Arduino. It is completely free and can be downloaded from the
official project website.

Scratch 4 Arduino

Juan Carlos López Gordillo Page 42


Basic Arduino Course

Ardublock

Ardublock is a powerful tool that allows programming in a similar way to


Modkit or S4A. Its main advantages are the ability to configure quickly and
easily a large number of modules and sensors from blocks that come already by
defect, in addition to being compatible with the Arduino programming IDE. More
information on the blog.

Ardublock allows for quick configuration of sensors and components

Physical Etoys

Physical Etoys is a tool for graphical programming purposes


didactic tools that allow programming various devices including
Arduino. It is based onnEtoys, lgraphical programming language oriented to
education and the teaching of children. It can be downloaded from here.

Juan Carlos López Gordillo Page 43


Basic Arduino Course

Physical Etoys allows programming all kinds of physical devices

Simulate Arduino with 123D Circuits

It is a web application that allows you to create Arduino projects with layout of
breadboard or PCB. Such projects can be shared in a way that they are made
cooperatives, we can order the PCBs we make in a way very similar to the
What Fritzing offers us and we also have an online programming IDE, accordingly.
we can continue coding from our tablet.

Juan Carlos López Gordillo Page 44


Basic Arduino Course

It is a very attractive platform for being both easy and powerful at the same time.
It turns out. It is also a very good tool for teaching, that spirit that is so much
The Arduino community likes it. And of course you can simulate your code online!

How to start developing in 123D Circuits?

We are going to the [Link]


we registered, which is very easy and
fast. Once we have our account, the main screen will be this:

As we can see, it will offer us to start with a protoboard style layout.


Fritzing or with the appearance of PCB, the latter is a good option if we want to order.
a personalized Arduino shield that we design ourselves. If we want to access
We click on our photograph for our projects. And if we want to see projects
what the community has done we can see them scrolling on the web, this is
Interesting since, as if it were git, we can 'fork' others' projects.
and thus base ourselves on their designs.

Once we decide to create a project, we access the following screen.

Juan Carlos López Gordillo Page 45


Basic Arduino Course

When we have the circuit, we start with the code (it's not strictly
it is necessary to follow that order).

And once we have finished the code, it's as easy as clicking 'upload &
run" to start seeing how your creation comes to life. The only drawback it has is the
The platform is that if your code doesn't compile, it won't tell you where the error is, although
this is pure syntax. If you can't find your error, you can click on 'download code' or a
just copy and paste it into our Arduino IDE to check, correct, and paste it again.
As we can see, it simulates many components and also simulates a serial terminal.

Fritzing

Fritzing is one of the best


tools that exist today
for the design and creation of circuits
electronics, and it is so powerful and complete,
that can be used in a way
professional to create all types of circuits.
Fritzing has features
interesting in terms of the workspace,
it poses an IDE interface, in this way it
allows dragging and dropping elements in
the work area. Fritzing has a
work area, which is capable of creating
very detailed circuit diagrams for
the creation of the prototypes of our
projects in a short time.

Fritzing includes a visual section


quite complete that allows creating the circuits dynamically, dragging the
symbols of each electronic component towards the work area. Thus, the creation of
electronic circuits will be as simple as drawing them on a sheet, and there will be a
complete scheme that can quickly be turned into a real prototype.

Juan Carlos López Gordillo Page 46


Basic Arduino Course

Fritzing has 3 types of views.

The Protoboard (Prototype Board) view is designed to look like


a real breadboard.

The Outline view, this representation is similar to diagrams used to represent a


electronic circuit.

Juan Carlos López Gordillo Page 47


Basic Arduino Course

PCB view, where you can see or make the connections of our schematic
in PCB.

VirtualBreadboard - Arduino and PIC Simulator

VirtualBreadboard is a simulation environment and


development for embedded applications that use
microcontrollers. It is easy to use and can
replace a breadboard to experiment with new designs.

VBB simulates many microcontrollers from the PIC16 and PIC18 lines, now also
with the emulation of Arduino. In addition, there is a wide variety of
simulated components such as LCDs, servos, logic, and other I/O devices that
they can be used to model and simulate high-level circuits.

In its early versions, VBB was free, now it has become an application of
payment.

It works based on a library of virtual components that come included in the


software package: push buttons, LEDs, potentiometers, LCD displays, motors
servo and steppers, logic chips and even EEPROM memories and ADC converters and
DAC. Additionally, VBB includes a platform called Micromorph CDK (Kit of
Development of Micromorph Components that allows you to build and add your own
components with input and output simulation.

Juan Carlos López Gordillo Page 48


Curso básico de Arduino

Some components of the VirtualBreadboard

Creating and simulating a project is simple and basically involves the following:

Interconnect all the necessary components in the connection window


(virtual breadboard).
2. Write the code that must run on the microcontroller. For Arduino, the
Arduino language and for the PICs currently only supports assembly language.
3. Simulate the execution of the code and the behavior of the components.
4. Make the necessary adjustments to the hardware and code.

The VBB in its latest version at the time of this publication comes with numerous
proyectos de ejemplo para Arduino, PIC16 y PIC18, la plataforma Amicus y Netduino,
ready to run them and analyze them. Below are the breadboard windows
virtual and code of a simple example with Arduino, an LED and a potentiometer:

Juan Carlos López Gordillo Página 49


Basic Arduino Course

Advantages and Limitations of VirtualBreadboard

VBB is an excellent entry option for learning to program Arduino if you do not
it has the real plate and for those who want to try the platform first
verify that it meets your needs and expectations, before risking to carry out the
economic investment in the purchase of the hardware plate.

Regarding the simulation of the PICs, it would be excellent if the VBB supported the simulation.
in C language; currently it only supports the assembly language associated with the PIC,
it is complex and not very advisable for beginners, however it is possible that
In the future, it will also support C language.

From now on, any simulation platform has its limitations. For the
beginners, the VBB is an excellent tool for learning; for those who
they have more experience is useful for simple and quick tests and prototypes; but not
very useful for carrying out medium or high complexity projects in which generally
It is required to have the hardware implemented for real, non-simulated tests.

Proteus

PROTEUS is a CAD development environment of the


Labcenter Electronics Ltd, which integrates various
software tools for the most common tasks in the
desarrollo de proyectos electrónicos tales como: captura de
schematics, printed circuit board manufacturing and simulation
based on PSPICE.

The tools that make up PROTEUS are the following:

ISIS ("Intelligent Schematic Input System"). Which is a capture module of


schematic diagrams.
VSM ("Virtual System Modeling"). Which is the simulation module, including
PROSPICE.
ARES ("Advanced Routing and Editing Software"). Which is the module for the
manufacturing of printed circuits or PCBs.

Juan Carlos López Gordillo Page 50


Basic Arduino Course

The Arduino programming language

The Arduino programming language is based on C / C++. Next, I will proceed to


a summary of the language, although the entire reference can be consulted in the following
address:
[Link]

It will be about summarizing as much as possible and referencing the nuances that are
necessary to develop sketches as clearly as possible.

Basic structure of a program:


The basic structure of the Arduino programming language is quite
simple and consists of at least two parts. These two necessary parts, or functions,
they enclose blocks that contain statements, declarations, or instructions.

void setup()
{
estates;
}

void loop()
{
estates;
}

Where setup() is the part responsible for gathering the configuration and loop()
it is the one that contains the program that will run cyclically (hence the term loop)
Both functions are necessary for the program to work.
The configuration function must contain the declaration of the variables. It is the
first function to be executed in the program, it runs only once, and it is used to
configure or initialize pinMode (I/O working mode), configuration of the
serial communication and others.
The following loop function contains the code that will be executed
continuously (reading inputs, activating outputs, etc.) This function is the
core of all Arduino programs and the one that does the most work.

Setup ( )

The setup() function is called only once when the program starts. It
used to initialize the operating modes of the pins, or the serial port. Must be
included in a program even if there is no statement to execute.

void setup()
{
pinMode(pin, OUTPUT); // sets the 'pin' as output
}

Juan Carlos López Gordillo Page 51


Basic Arduino course

Loop ()

After calling setup(), the loop() function does precisely what


suggests its name, it runs cyclically, which enables the program to be
continuously responding to the events that occur on the card
void loop()
{
digitalWrite(pin, HIGH); // sets the 'pin' to one (on, 5v)
delay(1000); // wait for a second (1000 ms)
digitalWrite(pin, LOW); // sets the 'pin' to zero (off, 0v.)
delay(1000);
}

Functions

A function is a block of code that has a name and a set of


establishments that are executed when the function is called. They are setup() functions and
loop() of those that have already been discussed. User functions can be written to
perform repetitive tasks and to reduce the size of a program. Functions are
declared associated with a value type "type". This value will be what it returns.
function, for example 'int' will be used when the function returns a numeric value of
integer type. If the function does not return any value, then it will be prefixed with the
the word 'void', which means 'empty function'. After declaring the data type that
return the function the name of the function must be written and in parentheses is
they will write, if necessary, the parameters that should be passed to the function for it to
execute.
type functionName (parameters)
{
estates;
}
{ } Entre llaves

The keys are used to define the beginning and the end of a block of
instructions. They are used for the programming blocks setup( ), loop( ), if.., etc.

type function()
{
estates;
}

An opening brace “{“ must always be followed by a closing brace “}”, if


The program will produce errors. The Arduino programming environment includes a
a very useful tool to check the total number of keys. You just have to do
click on the insertion point of an open key and immediately the
corresponding closure of that block (closed brace).

Juan Carlos López Gordillo Page 52


Basic Arduino Course

The semicolon

The semicolon ';' is used to separate instructions in the language of


Arduino programming. It is also used to separate elements in a
for loop instruction.

int x = 13; // declares the variable 'x' as an integer type with the value 13

Note: Forgetting to end a line with a semicolon will result in an error.


of compilation. The instructions can be written one on each line or several in
the same line, but always separated by ';'.

Comment blocks /*…. */

Comment blocks, or multi-line comments, are areas of text


ignored by the program that is used for the code descriptions or
comments that help understand the program. They start with /* and end
with * / and can cover several lines.

/* this is a comment block


one should not forget to close the comments
these must be balanced
*/

Because the comments are ignored by the program and do not take up
memory space on Arduino can be used generously as well
They can be used to 'comment' code blocks for the purpose of annotating.
information for debugging.
Note: Within the same line of a comment block, it is not possible to write.
another block of comments (using /* .. */ )

Comment line //

A comment line starts with // and ends with the next line
code. Like block comments, line comments are ignored by the
program and do not take up space in memory.

// this is a comment

A comment line is often used after a statement, to


provide more information about what this does or to remember it better
forward.

Juan Carlos López Gordillo Page 53


Basic Arduino course

Variables

A variable is a way of naming and storing a numerical value for


its later use by the program. As its name suggests, variables are numbers
which can be continuously varied in contrast to what happens with constants
whose value never changes. A variable must be declared and, optionally, assigned
a value.
int variableEntrada = 0; // declares a variable and assigns it the value 0
variableEntrada = analogRead(2);// la variable recoge el valor analógico del PIN2

Note: Variables should take descriptive names to make the code more
legible. Nombres de variables pueden ser “contactoSensor” o “pulsador”, para ayudar
the programmer and anyone else to read the code and understand what
represent the variable. Variable names like 'var' or 'value' provide very little help.
that the code is intelligible. A variable can be any name or word that
do not be a reserved word in the Arduino environment.

Variable declaration

All variables must be declared before they can be used.


To declare a variable, you start by defining its type as int (integer), long
(long), float (floating point), etc., always assigning them a name, and optionally,
an initial value. This should only be done once in a program, but the value can be
change at any time using arithmetic and various reassignment.

int variableInput = 0;

A variable can be declared in a series of places in the program and in


function of the place where the definition takes place this will determine in which parts
it can be used by the program.

A variable can be declared at the beginning of the program before the part of
setup() configuration, at the local level within the functions, and sometimes inside a
block (not advisable), as for loops of the type if.. for.., etc.
Depending on the location of the variable declaration, the scope will be determined.
of application, or the ability of certain parts of a program to make use of it.

A global variable is one that can be seen and used by anyone.


function and status of a program. This variable is declared at the beginning of
program, before setup().

A local variable is one that is defined within a function or as part of


from a loop (not recommended). It is only visible and can only be used within the
function in which it was declared.

Juan Carlos López Gordillo Page 54


Basic Arduino Course

int variable0; //'variable0' is visible to any function


void setup()
{
Byte variable1; //‘variable1’solo es visible dentro de la función setup ( )
……..
……..
}
void loop()
{
Int variable2; // 'variable2' is only visible within the loop() function
for (int i=0; i<20;) // 'i' is only visible within the loop function ()
{
i++;
}
float f; //'f' is visible only within the loop() function
}

In the previous example, although it is possible to declare the variables as indicated, it


It is recommended to declare variables at the beginning of the program or at the start of the
functions, therefore, the variables 'f' and 'i', it is recommended that they be declared along with the
variable 'variable2', leaving the loop function as follows:

void loop()
{
Int variable2;
Int i; float f;
for (i=0; i<20;)
{
i++;
}
}
Types of variables (see all at:[Link] )

Byte: Stores an 8-bit numeric value without decimals. They have a range between 0 and
255.
Char: It is a data type that occupies one byte of signed memory. They have a range.
between -128 and 127. For a byte data (8 bits), use the data type 'byte'.
Integers are a type of primary data that store numerical values of 16
bits without decimals contained in the range -32768 and 32767.
Long: 32-bit integers without decimals that are within the range.
-2147483648 to 2147483647.
Float: Numbers with decimals. Floating-point numbers have a greater
resolution that those of 32 bits with a range between
-3.4028235E+38 to 3.4028235E+38.

Note: Floating-point numbers are not exact and can produce results
strange in comparisons. Floating-point mathematical calculations are
also much slower than those of the integer type, so it must
avoid its use if possible.

Juan Carlos López Gordillo Page 55


Curso básico de Arduino

Arrays

An array is a collection of values accessed by an index number.


Any value can be retrieved using the name of the array and the number of the
índice. El primer valor de la matriz es el que está indicado con el índice 0, es decir el primer
the value of the set is that of position 0. An array must be declared and
optionally assigned values to each position before being used

int myArray[] = {value0, value1, value2...};

In the same way, it is possible to declare an array by indicating the data type and the size.
and subsequently, assign values to a specific position:

int miArray[5]; // declares an array of integers of 6 positions


miArray[3] = 10; // assigns the value 10 to position 4

To read from an array, simply write the name and the position to read:

x = miArray[3] ; // x ahora es igual a 10 que está en la posición 4 del array

Arithmetic

The arithmetic operators included in the programming environment are addition,


subtraction, multiplication, division, and remainder.
y = y + 3;
x = x - 7;
i = j * 6;
r = r / 5;
a = b % 10; returns the remainder of b/10

The operations are carried out taking into account the type of data we have defined.
for the operands (int, dbl, float, etc.), so, for example, if we define 9 and 4 as
Integers 'int', 9 / 4 returns a result of 2 instead of 2.25 since 9 and 4 are values
of type integer 'int' (integers) and decimals are not recognized with this type of data.

This also means that the operation can suffer an overflow if the result
is larger than what can be stored in the data type. Let us remember the
scope of the numeric data types that we have explained earlier.

If the operands are of different types, the largest type will be used for the calculation.
of the operands in play. For example, if one of the numbers (operands) is of the type
float and another of integer type, for the calculation the float method will be used, that is
floating point method.

Juan Carlos López Gordillo Page 56


Basic Arduino Course

Compound assignments

Compound assignments combine an arithmetic operation with a variable


assigned. These composite assignments can be:

x ++ // just like x = x + 1, increment x by +1


x -- // the same as x = x - 1, to decrease x by -1
x += y // just like x = x + y, or increase x by +y
x -= y // just like x = x - y, to decrement x by -y
x multiplied by y// just like x = x * y, to multiply x by y
x /= y // the same as x = x / y, or divide x by y

Comparison operators

Comparisons of one variable or constant with another are frequently used in


conditional structures of the type if.. to test if a condition is true. Types of
operators :
x == y x is equal to y
x is not equal tox
y is not equal to y
x<y x is less than y
x>y x is greater than y
x is less than or equal
x toisy less than or equal to y
x is greater than or equal
x istogreater
y than or equal to y
Logical operators

Logical operators are used to compare two expressions and return a value.
‘TRUE’ or ‘FALSE’ depending on the operator. There are three logical operators, AND (&&),
OR (||) and NOT (!), which are often used in if.. statements:

if (x > 0 && x < 5) // true only if both expressions are true


if (x > 0 || y > 0) // true if any of the expressions is true
if not (x > 0) true only if the expression is false

Constants

The Arduino programming language has default values, which are


constant calls. They are used to make programs easier to read. The
Constants are classified into groups.
TRUE / FALSE / HIGH / LOW: They are boolean constants that define the levels of
HIGH (high) and LOW (low) tension when they refer to the logical states of the
digital outputs. FALSE is associated with 0, while TRUE is associated with 1, but TRUE
it can also be anything else except zero. Therefore, in a sense
boolean, -1, 2 and -200 are all also defined as TRUE. (this is important
keep it in mind)
These constants are used to define, at the beginning of
program, the operating mode of the pins using the pinMode instruction
so that the pin can be an INPUT or OUTPUT.

Juan Carlos López Gordillo Page 57


Basic Arduino Course

IF statement (if) / IF ... Else (if...else)

if it is a statement that is used to test if a certain condition has been


reached, for example, to find out if an analog value is above a
certain number, and execute a series of statements (operations) that are written
inside the braces, if it is true. If it is false (the condition is not met) the program jumps and
does not execute the operations that are within the braces.

The format for if is as follows:

if (aVariable ?? value)
{
executeInstructions;
}

In the previous example, a variable is compared with a value, which can be a


variable or constant. If the comparison, or the condition in parentheses is met (it is
If true, the statements within the braces are executed. If not, the program
jump and continue.

Note: Pay attention to the special use of the symbol '=', putting inside if (x = 10),
it may seem valid but it is not since that expression assigns the
value 10 to the variable x, so within the if structure x==10 would be used that in
In this case, what the program does is check if the value of x is 10.

‘if… else’ is a structure that executes in response to the idea 'if this does not happen...'
complete do this other thing." For example, if you want to test a digital input, and make a
What would you do if the input is high or do something else if the input is low, you would write that?
this way:

if (inputPin == HIGH) // if the inputPin value is high


{
instructionsA; //execute if the condition is met
}
else
{
instructionsB; //execute if the condition is not met
}

'Else' can be preceded by another condition in such a way that several can be established.
conditional structures of one type inside the other (nesting) so that
they are mutually exclusive and can be executed at the same time.

Juan Carlos López Gordillo Page 58


Basic Arduino Course

if (inputPin < 500)


{
instructionsA; // executes operations A
}
else if (inputPin >= 1000)
{
instructionsB; // executes operation B
}
else
{
instructionsC; // executes operations C
}
The For / Next loop

The for statement is used to repeat a block of statements enclosed in braces.


a certain number of times. Each time the instructions of the loop are executed,
retest the condition. The for statement has three parts separated by (;)

for (initialization; condition; expression)


{
executeInstructions;
}

The initialization of a local variable occurs only once and the condition is tested each time.
that the execution of the instructions inside the loop ends. If the condition continues
Once fulfilled, the instructions of the loop are executed again.
When the condition is not met, the loop ends.

While loops / do...While loops

A while loop is a loop that runs continuously as long as the condition is met.
expression placed in parentheses in the header of the loop. The variable used as
comparison, it will have to change to break the loop. The situation may change at the expense
from an expression within the loop code or also by changing a value in a
sensor input.

while (aVariable ?? value)


{
executeStatements;
}

Juan Carlos López Gordillo Page 59


Basic Arduino Course

The 'do... while' loop works in the same way as the while loop, with the exception
that the condition is tested at the end of the loop, so the loop will always execute at
less than once. do
{
Instructions;
} while (aVariable ?? value);

It is important to realize the ‘;’ at the end of the loop, behind the comparison.

pinMode(pin, mode)

This instruction is used in the setup() configuration part and is used to


configure the working mode of a PIN to be INPUT (input) or OUTPUT (output).

pinMode(pin, OUTPUT); // sets 'pin' as output

digitalRead ( pinDigital )

Read the value of a pin (defined as digital) giving a HIGH or LOW result.
(low). The pin can be specified either as a variable or a constant (0-13).

value = digitalRead(Pin); // makes 'value equal to the state read in 'Pin'

digitalWrite(pin, value)

Send the previously defined OUTPUT 'pin' the value HIGH or LOW (putting
in 1 or 0 output). The pin can be specified either as a variable or as a
constant (0-13).
digitalWrite(pin, HIGH); // deposits a HIGH value (high or 1) in the 'pin'

delay() and millis() functions

The delay function (time) stops the execution of the program for the specified amount of time.
as indicated in the instruction itself. Its use is not recommended; instead, it is suggested to
it is recommended to use the millis() function.
delay(1000); // waits 1 second

La función millis ( ) devuelve el número de milisegundos transcurrido desde el inicio


of the program in Arduino up to the present moment. It will usually be a large value.
depending on how long the application has been running after being loaded or
after the last time the 'reset' button on the card was pressed.

value = millis(); // value collects the number of milliseconds

Note: This number will overflow (if it is not reset back to zero) after
approximately 50 days unsigned long = 232ms = 49 days, 17 hours, and 2 minutes.

Juan Carlos López Gordillo Page 60


Basic Arduino Course

analogRead(pin)

Read the value of a specific pin defined as an analog input. The Arduino board
it has 6 channels connected to a 10-bit analog-to-digital converter. This means that
it will convert voltages between 0 and 5 volts to an integer between 0 and 1023. This provides
a resolution in the reading of:
5 volts / 1024 units, that is, 0.0049 volts (4.9mV) per unit.

value = analogRead(pin); // assigns to value what it reads from the input 'pin'

Note: The analog pins (0-5) unlike the digital pins, do not need to be
declared as INPUT or OUTPUT since they are always INPUTs. The input range
it can be changed using the analogReference() function.

analogWrite(pin,value)

Write an analog value (PWM) to a pin. It can be used to control the


brightness of an LED or the speed of a motor. After calling the function
analogWrite( ), the pin will generate a stable square wave with the specified duty cycle
until the analogWrite() function is called again (or a call to the functions
digitalRead() or digitalWrite() on the same pin.

The frequency of the PWM signal will be approximately 490 Hz. the values of
analogRead ranges from 0 to 1023 and the values of analogWrite range from 0 to 255.

Parameters :
pin: It is the pin where the PWM signal is to be generated.
value: The desired duty cycle ranging between 0 (always off)
y 255 (always on).

val = analogRead(analogPin);
analogWrite(ledPin, val / 4);

analogReference(EXTERNAL)

With this instruction, we are telling our Arduino not to use its voltage.
default reference ( +5 V ), or the one we introduce through the AREF pin of our
plate.

Juan Carlos López Gordillo Page 61


Basic Arduino Course

Communication Series

It is used for communication between the Arduino board and a computer or others.
dispositivos. Todas las placas Arduino tienen al menos un puerto serie. Se comunica a través
from digital pins 0 (RX) and 1 (TX), as well as with the computer via USB. Therefore, when
Using these functions, we will not be able to use pins 0 and 1 as digital input or output.
We can use the built-in serial port monitor in the Arduino environment to
comunicarnos con la placa Arduino. Se debe seleccionar la misma velocidad en baudios
used in the call [Link]().

[Link] (speed)

Set the data rate in bits per second (baud rate) for the
serial data transmission. To communicate with the computer, use one of these
velocidades: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 o
115200.
[Link](9600);
[Link]()
Read the incoming data from the serial port.
Byte = [Link]();

[Link]( val, [format] )

Print the data to the serial port as ASCII text.


val : el valor a imprimir, de cualquier tipo
Optional, specify the base (format) to use, it can be:
- BYTE
- BIN (binary, base 2)
- OCT (octal, base 8)
- DEC (decimal, base 10)
- HEX (hexadecimal, base 16).
For floating-point numbers, this parameter specifies the number
of decimal places to be used.

[Link](78); // prints "78"


[Link]('N'); //prints "N"
[Link](78, BYTE); prints "N"
[Link](78, DEC); print "78"
[Link](1.23456, 2); print "1.23"
[Link]( val,[format] )

Print the data to the serial port as ASCII text followed by a return.
carriage return (ASCII 13, or '\r') and a line feed character (ASCII 10, or '\n').

[Link](analogValue); // print as ASCII decimal


[Link](analogValue, HEX);// imprime como ASCII hexadecimal

Juan Carlos López Gordillo Page 62


Basic Arduino Course

[Link]()

Returns the number of bytes (characters) available to be read by the


serial port. It refers to data that has already been received and is available in the reception buffer.
port (which has a capacity of 128 bytes).

if ([Link]() > 0)
{
reads the serial port
}
min ( x, y )

Calculate the minimum of two numbers for any type of data returning the
smallest number.
value = min(value, 100); // assigns to value the smaller of the two specified numbers.

max ( x, y )

Calculate the maximum of two numbers for any type of data returning the
larger number of the two.
value = max(value, 100); // assigns to value the greater of the two numbers 'value' and 100

randomSeed(valor)

Set a value, or seed, as a starting point for the random() function.


randomSeed(value); // makes value the seed of the random

Because Arduino is incapable of creating a true random number,


randomSeed allows you to set a variable, constant, or other control function
within the random function, which allows for generating random numbers 'at random'. There are
a variety of seeds, or functions, that can be used in this function,
including millis() or even analogRead() which allows reading electrical noise through
an analog pin.

random( max ) / random( min, max )

The random function returns a random integer number from a range of values.
specified between the min and max values. If min is not specified, it is taken as 0.

value = random(100, 200); // assigns to the variable 'value' a random number between 100-200

Note: Use this function after using randomSeed().

Juan Carlos López Gordillo Page 63


Basic Arduino Course

The following example generates a random value between 0-255 and sends it to an output.
analog PWM
int randNumber; variable that stores the random value
int led = 10; // define led as 10
void setup() { } no need to configure anything
void loop()
{
randomSeed(millis()); random seed based on the millis() function
randNumber = random(255); Generate a random number between 0-255
analogWrite(led, randNumber); // sends the PWM type output led the value
delay(500); // wait 500 ms = 0.5 s.
}
Switch / Case

How if statements, switch...case control the flow of programs allowing the


programmers specify different codes that should be executed based on
various conditions.

In particular, a switch statement compares the value of a variable with the value
specified in the case statements. When a case statement is found whose value
If it matches that variable, the code of that statement is executed.

The keyword break exits the switch statement, and is typically used at the end of
each case statement. Without a break statement, the switch statement would continue executing the
following expressions ('falling-through') until finding a break, or until reaching the end of the
switch statement. It can also be used in do, for, while loops and is used to exit the loop in
the moment when break is executed.
switch (var)
{
case 1: //do something when it is equal to 1
break;
case 2: //do something when it is equal to 2
break;
default: // if nothing matches, execute the 'default'
the "default" is optional
}
continue
The continue statement skips the rest of the iterations of a loop (do, for, or while).
Continue jumping to the loop condition and proceeding with the next iteration.

for (x = 0; x < 255; x ++)


{
if (x > 40 && x < 120)
{
continue; create a break in these values
}
digitalWrite(PWMpin, x);
delay(50);
}
return
A function ends. It can return a value to the calling function.
return;
return value; // both forms are correct

Juan Carlos López Gordillo Page 64


Basic Arduino Course

#define

Allows the programmer to give a name to a constant value before it is compiled.


the program. The compiler replaces references to these constants with the value defined in
compilation time.

#define ledPin 3 // El compilador reemplaza ledPin con el valor 3 en tiempo de compilación.

We must ensure that it does not end with a semicolon ';'.


#include

It is used to include external libraries in the sketch. This grants the programmer
access to a large number of standard C libraries (groups of pre-made functions), and also
libraries specifically written for Arduino.

The main reference page for AVR C libraries (AVR refers to Atmel chips in
which is based on Arduino) is located at:

[Link]

Just like "#define" should not end with a semicolon " ; "

Bitwise operators

Bitwise operators perform their calculations at the bit level of the variables. They help
to solve many of the most common problems at the programming level. Most of the
The following material is taken from an excellent tutorial on logical mathematics, which can be
found in ([Link]

Podemos tener 6 tipos de operadores para trabajar a nivel de bits :

& ( and )
| ( or )
not
xor
( left shift )
(shift to the right)

A common task of bit-level operators is to read, modify, or write in a


port. In microcontrollers, a port is an 8-bit number that represents the
condition (state) of each pin. Writing to a port controls all the pins of that port to
the time.

Juan Carlos López Gordillo Page 65


Basic Arduino Course

PORTD is a constant defined to refer to the output states of the pins.


digital 0, 1, 2, 3, 4, 5, 6 and 7. If there is a 1 in a certain position, that pin is at
high level (HIGH). (The pins need to be declared as output using the instruction
pinMode). So, if we write PORTD = B00010100;, we will set pins 2 and 4 to high level.
high. A slight problem is that when assigning a value to the port directly, it can
modify the value of another pin, for example, the value of bit 0 and 1 of port D, used by the
Arduino in serial communications, so we could be interfering in that.
communication.

Bits and bytes

lowbyte (variable): Extracts the low-order byte (right) of a variable.

valor = lowByte(x);

highbyte (variable): Extracts the high byte (left) of a variable.

value = highByte(x);

bitRead(variable, position): Reads the bit that is located at position n of a


variable. The position n starts at 0 (least significant bit).

value = bitRead(x, n);

bitWrite(variable, position, value): Writes the value at position n of a variable x.


["0","1"]
bitWrite(x, n, b);

bitSet(variable, position): Sets the bit at position n of a variable to one.

bitSet(x, n);

bitClear(variable, position): Sets the bit at position n of a variable to zero.

bitClear(x, n);

bit(position): Calculates the value of the specified bit (bit 0 is 1, bit 1 is 2, bit 2 is 4,
etc.).
bit(n);

Juan Carlos López Gordillo Page 66


Basic Arduino Course

Practices (I) Digital inputs and/or outputs

All practices and/or projects that are carried out will have to be set up properly.
practice on the Arduino board, on a board and/or designing the appropriate PCB.

P1a) Reading the state of a Push Button and displaying it on a Led.


Using Proteus, we will assemble the following schematic:
The components used are:
The value can be observed in
ARDUINO
the scheme. The button "P"
AREF
has a resistance
RESET
PB5/SCK
PB4/MISO
53/26
52/25
51/24
R1 in pull configuration
~PB3/MOSI/OC2A

down, such that when


50/23
~ PB2/SS/OC1B
49/22
~PB1/OC1A
48/21
P
PB0/ICP1/CLKO

PD7/AIN1
47/20
46/19
we will press 'P' we will introduce
7/34 ~PD6/AIN0
PC0/ADC0 45/18
8/35 ~ PD5/T1

5V (+Vcc) through digital pin 5 of Arduino.


PC1/ADC1 44/17
9/36
PC2/ADC2
PD4/T0/XCK
43/16
D1
10/37 ~PD3/INT1
PC3/ADC3 42/15
11/38 PD2/INT0
PC4/ADC4/SDA 41/14

The LED 'D1' has a resistor.


12/39 TXPD1/TXD
PC5/ADC5/SCL R1
RXPD0/RXD
40/13 LED-GREEN
R2 10k
220
ARDUINO UNO R3
limiter 'R2' connected to the digital pin
2 of Arduino.
Once the circuit is designed, we will save it in the folder 'C:\MySketch\P1', with the
name '[Link]'. We will now proceed to write the program in the environment of
Arduino and we will save it with the name P1 in the same folder.
As a recommendation, whenever we have code that is
find between braces ( { , } ), we will insert a tabulator, of
This way we can have the code more readable.
In all our projects, we will always try to have the
same structure in the program, that is, all the variables
we will write them at the beginning of the program, if they are global
"pinButton" and "pinLed") and at the beginning of the function
corresponding, if they are local ("button").
Whenever we can, we will use variables for the pins that
we are going to use, with the name 'pin' followed by the name that
we want.
When we have inputs, in the loop function afterwards
From the definition of the variables, we will assign all the
functions that read inputs (digitalRead in our case) to their corresponding variables
("button" in our case). All output functions (digitalWrite in our case),
we will try to write them at the end of the loop function and in between the reading functions and
of writing, we will include the rest of our program (decisions, loops, assignments, etc....)
But always, we will try to make our program, whether it is written entirely in the function
loop or if it is written in several functions, it should never make the microcontroller stop
to read the entries or to take an excessive amount of time to reread the entries, that is to say, that
our program must enter the loop function, go to the end where it usually
you will find our assignments of the outputs and rerun the loop function.

Juan Carlos López Gordillo Page 67


Basic Arduino Course

For this reason, we must be especially careful with the local variables that are defined, since
that every time the execution of the loop function begins, the local variables will return to
initialize. If we use functions like delay(), we will make the microcontroller wait for a
determined time and did not execute any instruction during that time, therefore, the
inputs will be read with a delay and in practice this means that our circuit does not
will immediately respond to an external event, so we will try not to use
functions or loops of this kind.
Next, we will compile our sketch, running our project to see the
functioning.

As we can observe, when pressing 'P', the LED turns on and when releasing 'P', the LED turns off.

It is left as an exercise to modify the position of the button and the resistor.
R3
10k
input, that is, using the pull-up configuration and verify that when pressing 'P'
we will introduce a '0' and upon releasing we will introduce a '1' through the input pin
digital, turning the LED on and off opposite to the previous exercise.
Modify the sketch so that the operation is the same as the exercise developed.
That is to say, when pressing 'P', the LED lights up and when releasing 'P', the LED turns off.

P1b) Start and Stop Buttons: Following the same procedure as in practice 1, we
you should add a button such that one of them will turn on the led and the other will turn it off, the
we will call "[Link]" and "[Link]".
Sometimes, it can be interesting
use connections with
ARDUINO
terminals, in this way
AREF P. MARCHA P. PARO
we reduced the wiring in the
RESET
PB5/SCK
PB4/MISO
~PB3/MOSI/OC2A
53/26
52/25
51/24
scheme. In this case the
march strike
50/23
~ PB2/SS/OC1B
~PB1/OC1A
PB0/ICP1/CLKO
49/22
48/21 terminal 'march' of
R1 R3
7/34
PC0/ADC0
~
PD7/AIN1
~PD6/AIN0
47/20
46/19
45/18
march
strike 10k 10k button is a terminal of
8/35 PD5/T1
PC1/ADC1 44/17 D1
exit that is found
9/36 PD4/T0/XCK
PC2/ADC2 43/16
10/37 ~ PD3/INT1
PC3/ADC3 42/15
11/38 PD2/INT0
PC4/ADC4/SDA 41/14
12/39 TXPD1/TXD

connected with the terminal


PC5/ADC5/SCL 40/13 LED-GREEN
RXPD0/RXD
R2
220
ARDUINO UNO R3

"march" (entry) of pin 7


Arduino digital. The same
it happens with 'strike'.

Juan Carlos López Gordillo Page 68


Basic Arduino Course

The code we must enter is as follows:

As can be observed, we continue with the


same previous criteria; scales,
variables at the beginning, input functions at
principle, output functions at the end and the
decisions among these functions.
It is worth noting that to facilitate reading, it has been...
grouped the variables of the input pins
en una sola línea y las de salida en otra, lo
we highlight when the
Pines in the setup function.
The expressions 'if' used only have
an action to be taken in case it is fulfilled
the condition, in such case to reduce the lines
of the program, it is advisable to write everything in
a single line, that is, we could write:

If(pulsadorMarcha==1) { salida=1; }
If(pauseButton==1) { output=0; }

Compile the sketch, set up the circuit on a breadboard, and check the actual operation.

In the following practices, the same criteria explained will be attempted to be used.
preferably the pull-down resistor configuration, so that in the state of
rest, that is to say without pressing, we will introduce a '0' to the Arduino and when pressing the button, it
it will introduce a "1" to the Arduino, but it is possible that in some project we must use the
pull-up resistor configuration.

Libraries for Arduino

First of all, what is a library for Arduino?


Without getting into technical details at all, a library is a file of code that is used
to call from a program made for Arduino, with the purpose of performing a task
concrete.

There are many libraries that allow Arduino to gain new functionalities, such as
for example create a GPS, send SMS messages, manage LCD or TFT screens, etc.

We can create our own libraries to avoid rewriting code or use others that have been created.
by third parties. In any case, once they are available, they must be installed.

Juan Carlos López Gordillo Page 69


Basic Arduino Course

Installation of new libraries:

Check if there is another one in the 'sketchbook' folder of our personal folder.
called "libraries". If not, it needs to be created.
2. Download the desired library to the desktop, for example one called 'Time'.
([Link] and decompress it.
3. In this step, there are two possibilities:
o If the unzipped folder contains another folder with the same name inside,
this last one needs to be copied into the "libraries" folder from the first step.

o Otherwise, you must copy the uncompressed folder directly into the
folder 'libraries'.

Juan Carlos López Gordillo Page 70


Basic Arduino Course

The final result must be this:

Observation:

Another option is to install them as an administrator in the folder where the libraries are located.
/usr/share/arduino/libraries

Use new libraries:

The procedure to use the added library is the same as for using any other.
of those that come with Arduino by default:

Juan Carlos López Gordillo Page 71


Basic Arduino Course

Standard libraries

EEPROM - reading and writing to 'permanent' storage


Ethernetfor connecting to the internet using the Arduino Ethernet Shield
Firmatafor communicating with applications on the computer using a standard serial
protocol.
GSMfor connecting to a GSM/GPRS network with the GSM shield.
LiquidCrystalfor controlling liquid crystal displays (LCDs)
SDfor reading and writing SD cards
Servofor controlling servo motors
SPIfor communicating with devices using the Serial Peripheral Interface (SPI) Bus
SoftwareSerialfor serial communication on any digital pins. Version 1.0 and later of
Arduino incorporateMikal Hart'sNewSoftSerial library as SoftwareSerial.
Stepperfor controlling stepper motors
TFTfor drawing text, images, and shapes on the Arduino TFT screen
WiFifor connecting to the internet using the Arduino WiFi shield
WireTwo Wire Interface (TWI/I2C) for sending and receiving data over a network of
devices or sensors.

Due Only Libraries

Audio - Play audio files from an SD card.


SchedulerManage multiple non-blocking tasks.
USBHost - Communicate with USB peripherals like mice and keyboards.

Explore Only Library

Esplora - this library enables you to easily access various sensors and actuators.
mounted on the Esplora board.

Arduino Robot Library

Robotthis library enables easy access to the functions of the Arduino Robot

Arduino Yún Bridge Library

Bridge Library - Enables communication between the Linux processor and the Arduino
on the Yún.

USB Libraries (Leonardo, Micro, Due, and Esplora)

Keyboard - Send keystrokes to an attached computer.


Mouse - Control cursor movement on a connected computer.

Juan Carlos López Gordillo Page 72


Basic Arduino Course

Contributed Libraries

Communication (networking and protocols):

Messengerfor processing text-based messages from the computer


NewSoftSerialan improved version of the SoftwareSerial library
OneWirecontrol devices (from Dallas Semiconductor) that use the One Wire
protocol.
PS2Keyboardread characters from a PS2 keyboard.
Simple Message Systemsend messages between Arduino and the computer
SSerial2Mobile- send text messages or emails using a cell phone (via AT commands)
over software serial
Webduinoextensible web server library (for use with the Arduino Ethernet Shield)
X10Sending X10 signals over AC power lines
XBeefor communicating with XBees in API mode
SerialControl - Remote control other Arduinos over a serial connection

Sensing:

Capacitive Sensingturn two or more pins into capacitive sensors


Debounce - for reading noisy digital inputs (e.g. from buttons)

Displays and LEDs:

GFX- base class with standard graphics routines (byAdafruit Industries)


GLCD- graphics routines for LCD based on the KS0108 or equivalent chipset.
Improved LCD libraryfixes LCD initialization bugs in official Arduino LCD library
LedControlfor controlling LED matrices or seven-segment displays with a MAX7221
or MAX7219.
LedControlan alternative to the Matrix library for driving multiple LEDs with Maxim
chips.
LedDisplaycontrol ofaHCMS-29xxscrolling LED display.
MatrixBasic LED Matrix display manipulation library
PCD8544for the LCD controller on Nokia 55100-like displays (byAdafruit Industries)
SpriteBasic image sprite manipulation library for use in animations with an LED
matrix
ST7735 - for the LCD controller on a 1.8", 128x160 TFT screen (by Adafruit Industries)

Audio and Waveforms:

FFTfrequency analysis of audio or other analog signals


Tonegenerate audio frequency square waves in the background on any
microcontroller pin

Motors and PWM:

TLC5940 - 16 channel 12 bit PWM controller.

Juan Carlos López Gordillo Page 73


Basic Arduino Course

Timing:

DateTimea library for keeping track of the current date and time in software.
Metrohelp you time actions at regular intervals
MsTimer2 uses the timer 2 interrupt to trigger an action every N milliseconds.

Utilities:

PStringa lightweight class for printing to buffers


Streaming - a method to simplify print statements

As you can see, there are many libraries, and many more continue to appear.
As more components and/or shields for Arduino are being released, so in this
In this course, we will dedicate ourselves to using the most important libraries and they will be explained as we go.
that we need.

En un curso más avanzado de arduino veremos cómo crear nuestras propias


libraries, now we will limit ourselves to using them only.

Engine Management

Let's take a brief look at the different types of engines we are going to use and their
most common control circuits. We can find ourselves with direct current motors
and alternating current motors.

a) Direct current motors


DC Motors:
They are the most common and inexpensive, they can be found in the
most battery-operated toys, generally made up of two
permanent magnets fixed in the casing and a series of windings of
copper located on the motor shaft, which is usually three.
They have two terminals that connect to the power supply and according to the
the motor will rotate in one direction or another.
To control the direction of rotation, we will use the following circuit:

As can be verified, Q1y Q4they will be in saturation


when we input C.1 = '0' and C.2 = '1', while Q2y Q3they are in
cut, so the motor spins in one direction (red arrow). If we modify the

Juan Carlos López Gordillo Page 74


Basic Arduino Course

entries, entering in C.1="1" and in C.2="0", we will make Q2y Q3train


in saturation and Q1y Q4in cut, so the motor will be polarized from
reverse direction and will turn in the opposite direction to the previous one (blue arrow).

These circuits are known as H-bridge or H-Bridge,


we can find in integrated circuits, which facilitates the design of
our circuits, such as the UCN5804, the BA6286, the L293B, L297, L298 or
also with the ULN2803 or the ULN2003, the latter two are arrays of
transistors, but we can also use them in our circuits.

As an example, the integrated


L293B has 4 drivers.
The sideburns and the board of
truth is what they
show

To control the direction of rotation of a DC motor, we will have to


use 2 drivers from the integrated circuit, that is, the scheme will be:

Therefore, with an L293B, we will be able to control the direction of rotation in 2.


DC motors

stepper motors (PaP)


A stepper motor, like any motor, is essentially a converter.
electromechanical, that transforms electrical energy into mechanical. While
a conventional motor spins freely when a voltage is applied, the stepper motor
at step turns a certain angle incrementally (transforms impulses
electric in controlled rotation movements - steps), which allows it to
perform very precise fixed angular displacements.

The rotation angle of these motors is very varied, ranging from


90º up to 1.8º and even 0.72º, each angle of rotation is performed by sending a
pulse in one of its terminals, that is to say, for example in motors that
they have 90º of rotation per step, 4 pulses are required for a complete turn
while in the 1.8º ones, 200 pulses are needed.

Juan Carlos López Gordillo Page 75


Basic Arduino Course

Its main applications can be found in robotics,


aerospace technology, hard disk control, flexible, CDROM drives
or DVD and printers, in computer systems, handling and
positioning of tools and parts in general.

According to the construction of the stator coils, we can distinguish two types:

. Bipolar
The current that flows
due to the windings changes from
meaning in function of the
tension that is applied, for the
that the same winding
it can have at one of its ends, different
polarity (bipolar).

To identify terminals 1a, 1b, 2a, and 2b, a will be used


ohmmeter, measuring the resistance between each pair of terminals, the
Ends 1a and 1b must have the same resistance as the ends.
2a and 2b, if the resistance is measured in a crossed manner, it will not indicate anything anymore.

that correspond to different coils.

To control these motors, we must reverse the polarities.


from the terminals of coils 1 and 2 in a certain sequence
to achieve a right turn, and in the opposite sequence for it to turn to
left, the sequence would be the one shown in this table:

T
I
e
n

Juan Carlos López Gordillo Page 76


Basic Arduino Course

As an example, the following scheme for control is shown


motor :

Where L1 and L2 are the coils of our motor.

. Unipolar
They are called that because

the current that flows through the


different windings always
circulate in the same direction.

They have the coils with a winding


unique. Compared to bipolar individuals, they have their
advantages, despite having more than 4 cables are
easier to control, this is because they have a common terminal
in both coils. Some motors have the windings such that
in such a way that based on bridges they can become unipolar
bipolar motors. These motors have 5 or 6 wires.

- If we have 6 cables, four correspond to each of the


ends of the two existing coils (1a, 1b, 2a and 2b), while
that the other two correspond to the midpoint of each one (Com1
and Com2).

- If we have 5 cables, four correspond to each of the


ends of the two existing coils (1a, 1b, 2a, and 2b), while
that the remaining cable corresponds to the midpoint of each coil
internally connected (Com1 and Com2 connected internally).

Juan Carlos López Gordillo Page 77


Basic Arduino Course

To identify the terminals, once the cables have been located


we will measure the resistance with an ohmmeter. From this
how we locate the two coils (the three wires)
whose resistance to each other is different from infinity
correspond to a coil). We can say that
we have two groups of three cables (A, B, C) and
(D, E, F). We will now measure the resistance between A and B, B and C, and between A and
C. The previous pair with the higher reading corresponds to the ends
from the coil (1a and 1b), while the remaining is the midpoint of the
same (Com1). For the other coil, we will use the same procedure
but using the cable group (D, E, and F).

To know the motor sequence we will need a source of


continuous tension of the characteristic value of the motor (5 V). We will connect
for example, the positive pole of the source to the two
cables (Com1 and Com2) joined together (Com). The pole
negative of the source, we will connect it to one of the
four remaining wires (A, B, C or D) and we observe
to which side the passage occurs. We proceed the same way.
with the others, trying in different order, until
the four steps have occurred in the same direction. From this
We will have already found the engine sequence.

For the control, we will use the ULN2003 or the ULN2803 integrated circuit.

It is an array of Darlington transistors capable of


handle up to 500mA on its outputs, it should only be taken into account that
the outputs are inverted with respect to the inputs. The assembly will be:

Juan Carlos López Gordillo Page 78


Basic Arduino Course

We must pay attention to the fact that the motor windings require a
negative pulse to be activated, as the ULN has its outputs
inverted, when it receives a '1' through pin INn will send a "0" to the output
OUTn.
These sequences follow the order indicated in each table for
make the motor spin in one direction, if you want it to spin in direction
opposite, it is only necessary to reverse that sequence.

They can be controlled in 3 ways:

- The first one is to create a sequence that activates a coil by


pulse.
When polarizing a
single coil
loses a bit the
torque of
motor.

- The second is to activate the coils in pairs, in this case the field
magnetic is
duplicate, and in
consequence the
motor has
greater strength of
transfer and retention.

- The third is a combination of the two previous ones, and known


as half-step sequence. The two forms of control seen
previously the predetermined number of steps is respected
for each engine,
for example, if
it has an angle of
90° turn, with 4
steps will give a
full turn
with this
procedure, it
can do with 8
steps.

Juan Carlos López Gordillo Page 79


Basic Arduino Course

We can also use the L298N integrated circuit, specifically this module.
what can be easily acquired or assembled:

As we can see, we have


about some switches to activate output A
or the output B (A enable / B enable), a
switch to activate +5V internal
through the integrated regulator 78M05,
In that way, it wouldn't be necessary the
+5V power input. The module is
powered by the input +12V
power. The Input entries will be connected to the digital outputs of our
Arduino and the motors will be connected to the 'output A' and/or 'output'.
B”.

Juan Carlos López Gordillo Page 80


Basic Arduino Course

a3) Servomotors
A servomotor (also called a Servo) is a
device similar to a direct current motor,
that has the ability to locate itself in any
position within its operating range, and
remain stable in that position.
It is made up of an engine, a box
reducer (Gears), a potentiometer and a
control circuit. Servos are used
frequently in radio control systems and in
robotics, but its use is not limited to these. It is
possible to modify a servomotor to obtain a
direct current motor that, although no longer
It has the ability to control the servo, maintains the strength, speed, and lowers.
inertia that characterizes these devices.

Servomotors have 3 terminals:


Positive terminal: Receives power from the motor.
Negative terminal: Motor ground reference.
Signal input: Receives the control signal from the motor.

According to the manufacturer, the color of the terminal varies, here I present the manufacturers.
more known.

To control a Servo, we must power it with the voltage that we


indicate the manufacturer and its appropriate polarity and send one through the data line
square signal of a certain frequency (generally between 50Hz or
100Hz) in which the duty cycle will determine the position in the
what we want is for our servomotor to be positioned.
The internal electronics of the servomotor (analog or digital) generates a
error signal between the demanded position and the current position of
servomotor. The servomotor will move until the two positions are the same.
same, remaining in that position if it continues to receive the same signal
through the data line.

Juan Carlos López Gordillo Page 81


Basic Arduino Course

The standard control signal for all servos of this type,


chosen to facilitate the use in remote control, it is a square wave pulse of
1.5 milliseconds that repeats at a rate of between 10 to 22 ms, although it is
It is advisable to always consult the manufacturer.

As long as the pulse remains in


this width, the servo will be located at the
central position of its journey. If the
pulse width decreases, the servo becomes
moves proportionally towards a
side. If the pulse width increases, the
the servo turns to the other side. Generally
the rotation range of such a servo covers
between 0° and 180° of the total circumference, or
a little more, depending on the brand and model.

In digital servos, the signal is separated by about 3.3 ms. The


the separation between pulses varies in each brand of digital servo, but the rhythm of
arrival of the pulses is at least 300 times per second versus 50 to 100 in
an analog.

For a servo to rotate 360º, just like a DC motor but


maintaining the torque, we must dismantle the current system, so
we need to remove the four screws that hold the lower cover of the
we will carefully remove the top cover of the servo that,
it contains the speed reducer, at no time should any force be applied
part, all can be disassembled effortlessly.

To rotate 360º, we need to cut or file the plastic stop of the


gear, so that there is no burr and the teeth are not deformed
of the gear, in the image below, a comparative detail of how it should be
leave the gear.

Juan Carlos López Gordillo Page 82


Basic Arduino Course

Next, extract with


careful, the block composed of the
printed circuit to which the
motor and the rest of the speed control.
From this point, we can choose
enter, remove the entire control part
electronic or maintain said system.

If we eliminate the entire control part


electronic, leaving only the motor,
then we must use an H Bridge like the
studied earlier (L293 or similar).

If we maintain the electronic control part, we must make the


electronic circuit always detects a fixed value on the pins where it
find the soldered potentiometer, this value should be the one obtained when
position the potentiometer at its midpoint. As this potentiometer is
finds connected with the motor, so that when the motor turns, the shaft of
potentiometer too, we must avoid it, so we can then
opt for several solutions:

- Cut the potentiometer shaft so that it does not rotate when moved.
motor, adjust it to its midpoint with the help of an ohmmeter,
stick the axle with loctite so that it does not move from its midpoint and
put it back into the servo housing.
- Remove the potentiometer and
replace it with another one (for example
multiturn) and prepare the casing
to make a hole in the place
suitable, so that through a
screwdriver, we can vary the resistance of the potentiometer
introduced to adjust it to its midpoint.
- Remove the potentiometer and replace it with 2
fixed resistors whose value is equal to half
of the total value of the original potentiometer.
Solder them in their proper place to make believe
to the electronic circuit that the potentiometer
find it at its midpoint. The resistances
they must be of 1% tolerance.

Juan Carlos López Gordillo Page 83


Basic Arduino Course

b) Alternating current motors and high voltage motors.


The alternating current motors used in home automation are usually single-phase.
although we can also sometimes encounter three-phase motors. The
The typical motor for an awning or blind in home automation is usually single-phase and the control is
do it in a very simple way:

As we can see, the engine has


3 terminals; Neutral, up and down.
When we apply the phase to the terminal of
up, the engine spins in one direction, when
we apply the phase to the lower terminal, the
motor spins in the opposite direction. Also
these motors have limit switches
adjustable internals, so we can
modify the revolutions the engine must make
for the blind to go up or down
completely.
To control this type of motors, we must take into account that the voltage
the working voltage is normally 230 V, and Arduino operates at 5V, so in addition to
the turn change circuits studied previously, it will be necessary to use some
circuits that allow us to work with high voltages, these circuits can be
some of these:

Juan Carlos López Gordillo Page 84


Basic Arduino Course

In the case of having a three-phase motor, the control circuit for rotation direction is:

Using contactors Without using contactors

Here you can observe a control of a direct current motor


elevated power.

Using relays Without using relays


Important criterion:
Next, we will do some practical exercises using different types of engines.
explained earlier. It should be kept in mind that due to the scarce material that is
It is available, and to avoid delaying the practices too much, we can simulate the direction of rotation of the
motors using LEDs, in such a way that we will have an LED that will indicate that the motor is
find turning in one direction and another led, to indicate that the motor is turning in
opposite direction, and when both LEDs are turned off, the motor will be
stopped. We will also keep in mind that when a device is mentioned.
find activated, it will mean that it will be on, turning in one direction, pressed,
etc..... that is to say the logical state will be '1' and when it is mentioned that it is deactivated,
it will mean that it is off, stopped, not pressed, etc.... in other words, the logical state will be
The buttons and limit switches will all be normally open (N.O.).

Therefore, from now on and throughout this manual, this criterion will be applied and in
otherwise it will be duly indicated.

Juan Carlos López Gordillo Page 85


Basic Arduino Course

How to use the EEPROM memory of Arduino

Let's see how to use the EEPROM memory of Arduino to reuse the
important data, recover the Arduino configuration or even transfer data from a
sketch another.

Generally, the EEPROM memory of Arduino usually


to be quite underutilized. I don't know if it will be because
lack of knowledge or fear when using it
but it's a shame since, with a few
lines of code and less than 1kB increase
in the size of the sketch, a resource can be available
really interesting.

Using the EEPROM is especially useful when it comes to


save the Arduino configuration (such as MAC and IP addresses)
but its use goes far beyond that. If you want to calibrate a sensor (for example, an LDR)
to set their limit values, a code that always calibrates the
system at startup (in the setup), a code that calibrates and saves can be implemented
the data in the EEPROM memory and, once saved, use it in another sketch.

Thanks to this, we will save space on the microcontroller and ensure


that this data does not depend on the day or the area in which we use the system
(going back to the LDR example, we can achieve, for instance, that if we restart
Arduino at night, keep the data stored during the day.

EEPROM memory capacity of Arduino

Each board model has a different EEPROM.


capabilities of EEPROM memories:

For more information about the


characteristics of the different plates of
Arduino visit this link.

Juan Carlos López Gordillo Page 86


Basic Arduino Course

Programming the EEPROM

We can program the Arduino EEPROM memory using the library


EEPROM.h

In Arduino memory, we must work by addresses and byte by byte.


both for reading and writing. This means that for a 1KB memory
we will have from address 0 to 1023 and we will be able to use values from 0 to 255. In
In case of larger values, they will have to be divided by bytes.

Example using a Byte

1 /*Use Of EEPROM Memory With Bytes*/


2
3 //The EEPROM library is included
4 #include <EEPROM.h>
5
A variable is created with the value of the memory position
7 //in which the byte will be stored.
8 int Direction = 0;
9
10 //Se crean una variables para leer los valores de la memoria EEPROM
11 byte Val1;
12 byte Val2;
13
14 void setup()
15
16 [Link](9600);
17 //The information to be saved is stored in a byte.
18 byte Informacion = B11001;// La "B" indica que el formato es binario
19
It is also possible to store the information read through a
21 //sensor. It should be taken into account that the maximum value of a variable
22 //int type is 1023, while the highest value that can be stored
In a single byte it is 255. Therefore, the resulting value is divided by 4.
24 //and when using the value it is multiplied by 4 again. In the
25 //process loses precision.
26 // need to divide by 4 because analog inputs range from
27 int Value = analogRead(0) / 4;
28
29 //The previous values are stored consecutively.
30 [Link](Address, Information);
31 [Link](Address+1, Value);
32 }
33
34 void loop()
35 {
36 Val1 = [Link](Address);
37 Val2 = [Link](Address+1);
38

Juan Carlos López Gordillo Page 87


Basic Arduino Course

[Link]("In the direction ");


40 [Link](Direction);
41 [Link](" the information is located: ");
42 [Link](Val1, DEC);// DEC for data in decimal.
43 delay(100);
44 [Link]("At the address ");
45 [Link](Direction+1);
46 [Link](" the information is found: ");
47 [Link](Val2, DEC);// DEC for decimal data.
48 delay(100);
49 }

Example using two Bytes

1 A variable is composed of 2 bytes, for example, an int type.


2 int A = 800;
3
4 Two byte type variables are created to store the information.
5 byte L;
6 byte H;
7
8 The most and least significant bytes are stored.
9 H = highByte(A);
10 L = lowByte(A);
11
12 //Bytes are written in contiguous memory addresses.
13 [Link](Address, H);
14 [Link](Address+1, L);

Example using more Bytes

Although there are several algorithms, let's look at one:

Store the integer data in an auxiliary variable (to avoid losing the data.
original)
Check the number of bytes the data has.
Store the most significant byte in a byte type variable.
Store the byte in the EEPROM.
Shift eight bits (one byte) of the auxiliary variable to the left, in such a way
that the second byte of that variable becomes the most significant.
Repeat the operation as many times as the size of the variable.
initial.

Juan Carlos López Gordillo Page 88


Basic Arduino Course

1 A long type element is used (it contains 4 bytes).


2 long Dato = 123456789;
3 int i;
4 The data is stored in an auxiliary variable.
5 long AuxDato = Dato;
6
7 A byte is defined to store information in the EEPROM.
8 byte B;
9
The sizeof() instruction returns the number of bytes of a variable.
11 for (i = 0; i < sizeof(Dato); i++)
12
13 B = highByte(AuxDato); //The most significant byte is saved
14 [Link](i, B);
15 //They shift 8 bits to the left so that the first 8
16 bits are lost and the next 8 become the first
17 AuxDato = AuxDato << 8;
18

Composing Bytes

After separating a variable into bytes to store it in memory


The Arduino EEPROM comes with the problem of having to reassemble it to recover the
information. If, for example, we have a long type variable separated into four
bytes inside the EEPROM, when reading those data we have four bytes, not a
long.

Again, there are several ways to solve this problem, let's see one:

Create a variable of the type we want to recover and assign it the value 0 (of
so that all its bits will be 0.
Define another variable equal to the previous one (the auxiliary variable).
Read a byte from the EEPROM memory and store it in the auxiliary variable
using the OR instruction, which stores the byte in the eight
least significant bits of the auxiliary variable.
Shift the bits of the auxiliary variable to the left so that they remain
in the position that interests us.
Perform a new OR operation between the auxiliary variable and the final one.
Clear the auxiliary variable and repeat the process as many times as necessary.

Juan Carlos López Gordillo Page 89


Basic Arduino Course

1 Variable that will store the final result.


2 long Dato = 0;
3 //Auxiliary variable (used simultaneously as byte).
4 long B;
5 int i;
6 for (i = sizeof(Data); i > 0; i--)
7 {
8 The EEPROM value is stored in the least significant bits.
9 B = [Link](i-1);
10
The bits are shifted as many bytes as necessary, having in
12 //note that the final byte should not be shifted.
13 if (i != 1)
14 { B = B << (8*i); }
15
16
17 //The result of the OR operation is stored in the final variable
18 //both data. When performing the OR operation with a variable that only
19 //contains zeros (variable Data), the result is the value of the other
20 //variable. OR implies => 0+0=0, 0+1=1, 1+0=1, 1+1=1.
21 Date = Date | B;
The auxiliary variable is cleared so that in the following iterations
23 //do not change the result of the other bytes.
24 B = 0;
25 }

Juan Carlos López Gordillo Page 90


Basic Arduino Course

Practices (II) Mobile Hook

P2a) Carry out the control of a movable hook, whose diagram is the following:
In the state of rest, the limit switches Fa
y Fbare deactivated, the engine is
find stopped, and the start buttons
( Maand stop (P) deactivated.
The system in the initial state is located
activating FaThe stop button 'P' is
find disconnected (not used in this
exercise).

The operation should be the following:

With the system in the initial state, an operator presses [Link] that the
hook moves to the right (Md1, Mi="0"), until F is activatedb,
In that case, the hook must change its direction to the left (Mi1
Md="0"). When the hook arrives and activates Fa, the hook will stop,
staying still until a new pulse of Ma.

The operator only activates the system when the hook is present.
activating Fathat is to say, if the hook is in motion, whether towards the
right or left if the operator presses Mait should not produce any effect. The
The stop button “P” in this exercise has no effect. The motor used,
It is a 5V direct current motor.

P2b) Modify exercise P2a so that when the hook activates 'Fbit seems, but no
It will start until the operator presses M again.a.

P2c) Modify exercise P2b by adding the stop button "P" in such a way that,
When I pull "P", the hook should stop anywhere, waiting.
let the operator press "M" againaIn which case, the hook will move to the
sense in which it had stopped.

P2d) Analyze the EEPROM library and create a program using EEPROM memory
from our Arduino so that in case of a power outage,
the automation stops and when the power returns, the automation continues with its
normal operation, at the point where it stopped.

Juan Carlos López Gordillo Page 91


Basic Arduino Course

The code to enter is the following:

Juan Carlos López Gordillo Page 92


Basic Arduino Course

Juan Carlos López Gordillo Page 93


Basic Arduino Course

Sensors ( I )
Luminosity - LDR Resistance

A LDR (Light Dependent Resistor or light dependent resistor)


light) is a resistor that varies its value based on the light received, how much
the more light it receives, the lower its resistance.

The range of resistance that an LDR can give us from total darkness
In full light, it will vary from one model to another, but in general, they oscillate around 50 Ω.
at 1000 Ω when fully lit and between 50 KΩ and several MΩ when it is
completely in the dark.

One of the things to consider is the time it takes to change the resistance.
when the light it receives changes, there are models with different response times, in addition
it does not vary in the same way from light to darkness as from darkness to light. Anyway, except
that we need an extremely fast and precise variation response, the LDR gives us
it will be useful for most projects that we are going to use.

Juan Carlos López Gordillo Página 94


Basic Arduino Course

Ultrasonics - HC-SR04

Power Supply: 5V
Sensing angle: 15°
Distance range: 2 to 500 cm
Number of pins: 4 ( Vcc, Trig, Echo, Gnd )

If the speed of sound at 20ºC in the air is 343 m/s and knowing that the echo must go
and returning after "t" seconds. So we have that the distance "d" in meters is:

2d = 343 · t where do we obtain d = (343 · t) / 2

To take a reading with the HC-SR04, just follow these steps:

Send a pulse of at least 10 µs through the TRIG pin (trigger) to start the reading.
The sensor will send 8 ultrasonic pulses and set its ECHO output high,
We must detect this event and start a 'countdown'.
3) The ECHO output will remain high until it receives the echo reflected by the obstacle.
to which the sensor will set its ECHO pin low, that is, we will finish "counting the
time
4) The distance is proportional to the duration of the pulse and we can calculate it with the
following formulas:
d (m) = (343 · t(s) ) / 2 = 171.5 · t(s)

d (cm) = t (µs) · 0.01715 distancia en cm, t en µs


d (inch) = t (µs) · 0.00675 distance in inches, t in µs

Note: If the pulse duration is longer than 30 ms, it means there is no obstacle.

The timeline diagram is as follows:

This is the theory and we will not need it to use this sensor as there is
a library that returns the distance in centimeters or in inches called
Ultrasonic.

Juan Carlos López Gordillo Page 95


Basic Arduino Course

We must decompress it in the libraries directory of the compiler IDE. The


"Trig" and "Echo" earphones are connected to 2
digital inputs of Arduino at our choice.
For the example, we will connect 'Trig' to the 9 and
"Echo" at 8.

Open the Arduino IDE, click on 'Files' - 'Examples', then look for
"Ultrasonic" and select "Serial".

The example Serial program is as follows:

La primera línea“#include <Ultrasonic.h>”,lo que hace es incluir en nuestro


code, the necessary functions to be able to use the HC-SR04 module. The following
line "Ultrasonicultrasonic(9.8);" declares an object called "ultrasonic" that
belongs to the 'Ultrasonic' class and we send 2 parameters, the pin of the Arduino where
We have connected TRIG and the pin of the Arduino where we have connected ECHO.

It can then be verified that the Serial Monitor is used, which is


communicates with Arduino through the serial port RX (pin 0 of Arduino) and TX (pin 1 of
Arduino, so we should not use those pins. The serial port of the Arduino is
communicates with the PC via the USB cable, so we should not disconnect it
when we use the serial port. We also see that the speed has been configured for
serial port at 9600 bps (baud).

Finally, the line where '[Link](CM)' is located returns


the distance at which the detected object is located in centimeters (CM) and it
show through the serial port, if we want it to indicate in inches, we must
replace CM with INC.

Juan Carlos López Gordillo Page 96


Basic Arduino Course

This library as it comes has a timeout of 3 ms so


that the maximum distance it will measure will be 51 cm, which is somewhat scarce. The advantage of having a

a low timeout means that many measurements can be taken in a short time.
We can modify this timeout in the file '[Link]'.

We look for Time_out = 3000 and modify it to 30000 for 5 meters.

Important note:

The Arduino IDE is constantly being developed, with new versions being released regularly.
time. Until before version 1.0, the libraries needed to include the file 'WProgram.h',
but starting from version 1.0, the file name was changed to 'Arduino.h', and also it
it included several more features, with the appearance of the Arduino Due, it is expected that there will be a new one.

modification, but as of today, there is still no information. Many applications


for Arduino that we found on the Internet were developed for the early versions of the
Arduino IDE, so the '.cpp' and '.h' files contain the call to the file
"WProgram.h", if we use version 1.0 or later of the Arduino IDE, when compiling it will give us
an error indicating that it cannot find the file 'WProgram.h', the solution to this problem is,
edit the affected ".cpp" or ".h" file, and replace the line #include "WProgram.h" with
#include"Arduino.h".

Another more elegant solution that will make the compiler decide on its own, that
file include, depending on the version of the Arduino IDE used is to delete the line #include
"WProgram.h" and instead write this code:

#ifARDUINO >= 100


#include"Arduino.h"
#else
#include "WProgram.h"
#endif

Juan Carlos López Gordillo Page 97


Basic Arduino Course

Practices ( III )

P3a) Light regulation in a garden

We are going to use an LDR to simulate a hypothetical light compensation.


of 5 levels, that is, through a resistor that varies its value depending on the
received light, we will take advantage of that variation to create a program that will us
turn on or off a series of LEDs depending on whether there is more light or less light
we could extrapolate it to a lighting regulation system for a garden with five lines
of light that gradually turns on as night falls, compensating
progressively the deficiency of light.

We have also implemented a potentiometer to adjust the critical level.


minimum light that we want to support, from which our circuit will be activated and
The light in the place will gradually start to increase.

In the circuit on the left, it will give us the


maximum tension when we have the LDR in full
darkness, as it will present its maximum resistance,
obtaining a high voltage at Vout.
In the circuit on the right, the result will be the
inverse, we will have the maximum tension when it is
completely illuminated, since it will behave
practically like a short circuit, with a
resistance of 50 Ω or 100 Ω.

We will use the circuit on the right, so the more light


There will be more tension at the entrance of our analog input allowing
adjust like this, in a very intuitive way, the reference tension. Therefore, our
LDR will make Vout = 0 when it is completely dark, and approximately +5 V when
be completely illuminated, situations that can be difficult to achieve
depending on the environment in which we work, and on the other hand, that range of 0v to 5v
it will have to be divided into 1024 'steps' that our Arduino will read, but perhaps only
let's work in 500 or 600 steps, wasting a lot of resolution.

To solve this, in addition to avoiding changing the Arduino program every


Once we change it from the environment, we will use a function provided by Arduino.
very interesting, the pin 'Aref'.

We must keep in mind that this pin internally carries a resistor of


32KΩ to avoid damaging the chip, so that if we are going to connect the pin through
a fixed resistor, a new voltage divider will be produced, which will require
calculate the appropriate resistance for the exact voltage we want to introduce
through a simple formula:

Juan Carlos López Gordillo Page 98


Basic Arduino Course

Where:
Vin = Voltage that we introduce to Aref
Rinternal = Internal resistance of Arduino of 32KΩ
Rexternal = Resistance through which we supply Aref
Vrefencia = The voltage on which our program will reference.

So, for example, if we are introducing a voltage of +3 V to


through a 5KΩ resistor, the actual reference voltage in our Arduino will be
de:

By varying the reference signal, we are telling the analog converter to


digital of the Arduino, which takes 1024 values between 0 V and a certain voltage
maximum, and we have already set the distribution of those values equitably in our
program to progressively activate the lighting lines, by
so, even though we have a very low range of lighting to play with, of 1 V per
For example, it will always distribute the activation of the outputs proportionally.

That reference tension will be the point of illumination from which, if


decrease the ambient light, it will start to decrease the values obtained in the signal
input analog.

If we set that reference very low, the LEDs will start to work with less.
ambient light that if we put a very high signal, let's remember:

More light = Less resistance = Higher Vout


Less light = Greater resistance = Lower Vout

Let's look at the complete electrical diagram of the circuit:

Juan Carlos López Gordillo Page 99


Basic Arduino Course

The scheme will be as follows:

RV1
10k

50%

ARDUINO

+5V R1 D1 LED-RED

AREF 220

PB5/SCK
53/26 R2 D2 LED-RED
52/25
PB4/MISO
RESET 51/24
~PB3/MOSI/OC2A 220
LDR1 ~ PB2/SS/OC1B 50/23
TORCH_LDR ~PB1/OC1A 49/22 R3 D3 LED-RED
48/21
PB0/ICP1/CLKO
220
47/20
PD7/AIN1
7/34 ~PD6/AIN0 46/19 R4 D4 LED-RED
PC0/ADC0 45/18
8/35 ~ PD5/T1
PC1/ADC1 44/17
9/36 PD4/T0/XCK 220
PC2/ADC2 43/16
10/37 ~PD3/INT1
+88.8 R6 11/38
PC3/ADC3
PD2/INT0
42/15 R5 D5 LED-RED
1k PC4/ADC4/SDA 41/14
Volts 12/39 TXPD1/TXD
PC5/ADC5/SCL 40/13
RXPD0/RXD 220

ARDUINO UNO R3

The code to enter is the following:

Assemble the circuit and check its actual functioning.

Juan Carlos López Gordillo Page 100


Basic Arduino Course

Automatic access door to supermarkets, hospitals, etc...


In the resting state, the door is
find closed, activating "Fb".
When an object (person) enters the
sensor detection zone 'Fc1”
o"Fc2, will make the door open,
turning the engine clockwise
“Ma”. When the door activates to “Fa”,
it will make the engine stop. After 3 seconds
if the sensors "Fc1yFc2they do not detect any object, the door will close, turning the
motor in the "Mc" direction. If it detects any object before 3 seconds have elapsed, it will have to
wait another 3 seconds for the door to close. If the door is closing, that is 'Mc'
is activated, and the sensors 'Fc1o Fc2they detect some object, the door
must be reopened. If the sensors 'Fc1yFc2they do not detect any object, the
The door will close completely, activating 'Fb' and returning to the resting state.

Note: For the timer, the millis() function should be used. As a sensor of
We will use the HC-SR04 module, keeping in mind that we need to configure it.
the '.cpp' file to detect 5 m.

To simplify the assembly, we will use only one HC-SR04 sensor.


it tells us that if we want to use both in a real assembly, we must take into account that
As soon as one of the 2 sensors detects presence, the door must open.

Juan Carlos López Gordillo Page 101


Basic Arduino Course

The code to enter is the following:

Assemble the circuit and check its operation.

Juan Carlos López Gordillo Page 102


Basic Arduino Course

Sensors (II) - Infrared (IR)


Infrared light barrier for our projects

In many of our projects, we will need an infrared light barrier.


to detect the passage of objects, people, etc.... To do this, we will use a diode
(photodiode) emitter CQY99 and a (phototransistor) receiver BPW77.

CQY99 infrared emitter diode Manufacturer designation: TSUS5402

Specifications:
Type of infrared emitter LED
Wavelength λ 950 nm
Diode lens transparent, blue
Field of view 44°

BPW77 phototransistor infrared receiver

It is an NPN type phototransistor, whose characteristics


the following are:

Another more home-made alternative is to take advantage of the photodiodes and phototransistors from the
old ball PC mice, so when we disassemble the mouse, we will have:

Juan Carlos López Gordillo Page 103


Basic Arduino Course

In reality, each previous element of 3 legs consists of 2 phototransistors connected.


the following way:

Where we can observe that the terminal of


center, corresponds to the collectors of the
phototransistors and the terminals at the ends are
correspond to the emitters of the phototransistors.

The photodiodes have a red dot,


indicating the cathode, also in case of doubt it can be
to use an ohmmeter to find out.

For our purpose, we can combine the two transmitters, which will give us the
the center terminal which would be the collector and the other 2 connected which will be the emitter.

The circuit we will use is the following:

This circuit is valid for


+5V

any of the photodiodes and


+5V phototransistors that have been
R3
R2
10k
1k described previously.
Q3
PN2222
R1
56
Q2 The PCB board can be
PN2222

D1
Q1 1
J1 design in such a way that both the
R4 2

LED_IR
Phototransistor
470
Exit
photodiodes like the
phototransistors can be placed
in the places to be detected.

Juan Carlos López Gordillo Page 104


Basic Arduino Course

Rebounds
We have seen how we can read the state of the pin, but, what happens if
Do we want to count the number of times it changes state? We do not want to detect the
state in which the pin is found but we want to count the number of times
that changes state. This may be necessary when the same button needs to
determine different behaviors or simply, to implement a counter.

We will encounter the dreaded bounce problem (debounce). They are the undesirable ones.
state changes that occur when a mechanical contact changes state.

One way to minimize bounces is to use external hardware, for example:


Here we can see an R-C circuit connected to the circuit.
typical of a pull-down resistor, so that when
Let's press the button, the capacitor C1 will charge from 0V to 5V.
through R1, with a time constant Ƭ =R1 · C1, as
we see that signal is sent to a 7414 Trigger Smith inverter.
When it reaches 1.7 V, the inverter switches to a low state that
It will read the pin of the Arduino.

Cuando el pulsador se desactiva, C1 pasa de 5V a 0V. Al


reaching 0.9V, the Trigger Smith gate converts that state to a
high state. This high state is the one that reads the pin of our
Arduino.
Another way to minimize the effect of rebounds is to use software, we can create a
timer-based algorithm (millis()…), using interrupts or through the
next function:

How can we
observe, the function the
I have called anti-bounce and
as parameters of
entry receives a
byte type variable and
return the result
also like a byte.

Si tenemos una variable (“miVariable”) a la cual debemos quitar los rebotes, haremos
the call to this function in the following way;

if( noBounce( myVariable ) )


{
…………………….
This code only runs once.
…………………….
}

Juan Carlos López Gordillo Página 105


Curso básico de Arduino

When calling 'myVariable', it is copied into 'variableWithBounce' so


"myVariable" must be of type byte. The variable "flanco" of type byte is then declared.
static and assigned the value '0', this means that the variable 'flanco' the first time that
declare, it will have the value "0" and will also retain its value upon exiting the function as if it were a
global variable. Next, a comparison of "variableWithBounce" is made with the
rest value of that variable, which we will need to modify for each exercise. If we assume
that we are pressing a button

Practices (IV)

Different operating modes of a Push Button

We are going to design a circuit that has 2 buttons connected to a


analog input, a display that we will use for mode 3 and an LED with its
limiting resistor to see the operation of the chosen mode.

Mode 0: Normal mode, in this mode when pressing 'P' the LED turns on, when
release 'P' the LED turns off.

Mode 1: Switch Mode, in this mode, when pressing and releasing 'P', the LED
change of state.

Mode 2: Clapping mode, in this mode, we will simulate that when claps are given
2 claps (or two loud sounds), the LED changes state, having in
It says that the time between one clap and the next must be less than 500.
We would actually connect a microphone with an amplifier.
operational 741 to an analog input of the Arduino and we will detect
when the sound exceeds a threshold of tension, for example, 2 V.

Juan Carlos López Gordillo Page 106


Basic Arduino Course

Mode 3: In this mode, we will use the display. It will start representing a
Zero. When the "P" button is pressed and released before 2 seconds, the
the number displayed will increase each time
press and release 'P'. If 'P' is held down for 500 ms
approximately, the display will quickly increase at a speed of
500 ms. The numbers displayed must be
understood between 0 and 9, and they will be increasing. The next
the number to show after 9 will be 0.

The code to enter is the following:

Juan Carlos López Gordillo Page 107


Basic Arduino Course

Juan Carlos López Gordillo Page 108


Basic Arduino Course

P4b) Elevator of 5 floors.

Design a 4-story elevator plus the ground floor.


we have 5 buttons (one on each floor), to
call the elevator.
The elevator cabin must have a receiver of
infrared and on each floor we will have an infrared emitter
always activated, from +5V

way that when the D1


R1

Cabin go through each floor, the receiver will receive. P0 P1 P2 P3 P4 M1


220
LED-RED

D2
signal from the transmitter that will be placed in the P0 P1 P2 P3 P4
M2
R2
220
R5 R6 R7 R8 R9 LED-BLUE

suitable place, so that the cabin is 1k 1k 1k 1k 1k

find leveled with respect to the floor where it


find. +5V
ARDUINO

In its resting state, the elevator is AREF


CABIN
you will find it standing and located on the ground floor and the RESET
PB5/SCK
PB4/MISO
53/26
52/25
51/24
~PB3/MOSI/OC2A
50/23
~ PB2/SS/OC1B
49/22

receiver will be receiving signal from the emitter,


S ~PB1/OC1A M2
48/21
PB0/ICP1/CLKO M1
R3 47/20
PD7/AIN1
1k ~PD6/AIN0 46/19
7/34 P4

located on that floor.


PC0/ADC0 45/18
8/35 ~ PD5/T1 P3
PC1/ADC1 44/17
9/36 PD4/T0/XCK P2
PC2/ADC2 43/16
10/37 ~PD3/INT1 P1
PC3/ADC3 42/15
11/38 PD2/INT0 P0
PC4/ADC4/SDA 41/14

We must have a display that allows us


12/39 TXPD1/TXD
PC5/ADC5/SCL 40/13
RXPD0/RXD S

ARDUINO UNO R3

indicate the floor where the cabin is located.

As an improvement, it is left as an extra exercise to add the doors in the cabin in a way.
that upon arriving at the floor from which they have been called, the cabin doors will open. For the
that the doors must have their corresponding limit switches. In addition, it is possible to
add an infrared light barrier at the door as a security measure so that it does not
They can close the doors if there is any obstruction.

Juan Carlos López Gordillo Page 109


Basic Arduino Course

Strings (character strings) in Arduino

Although at first, using strings in a microcontroller may seem not to have


too much sense, there are times when its use is necessary. Let's suppose, for example, that
we want to establish a serial communication between Arduino and another device (PC, another
arduino, bluetooth, automaton, etc…..) we could send or receive a byte, a character
(char) or a string.

To define a variable of type char or a string, we will do it in one of these ways


two ways :

char variable1='x'; 'x' is the character we assigned to variable1


char variable2;
string variable3=”prueba”; // “prueba” es el string que asignamos a variable3
string variable4;
variable2=’y’; 'y' is the character we assigned to variable2
variable4=”esto es”; // “esto es” es el string que asignamos a variable4

To concatenate 2 or more variables of char type or string type, first


we must note that the result is a string, therefore, first of all, we

Juan Carlos López Gordillo Page 110


Basic Arduino Course

we must declare the variable of string type that will contain the result of the
concatenation, therefore;

String Resultado1=””; // “” significa que asignamos un stringvacío


String Resultado2;
Resultado2=””;
Result1 = variable1 + " - " + variable2 + " = z";
// Result1 will be x - y = z Pay attention to the spaces
Result2 = variable4 + 'a' + variable3 + ' ' + variable1; // ' ' is a space
// Result2 will be this is a test x Pay attention to the spaces

Before using Strings, we need to include the String library, as follows


next:

#include <String.h>

By including this library, we obtain several functions that we can use on


any variable of type string.

StringConstructors
String Addition Operator
StringIndexOf
String Append Operator
StringLengthTrim
String Case Changes
StringReplace
StringRemove
StringCharacters
StringStartsWithEndsWith
StringComparisonOperators
StringSubstring

Click on the link of each function to see how they are used. In this
in the course we will use some of these functions.

Juan Carlos López Gordillo Page 111


Basic Arduino Course

Control of a 16x2 LCD

We will use a shield that besides a 16x2 LCD, also has 6


push buttons, it is about the LCD Keypad Shield. 4 bits are used for control.
Pins 4, 5, 6, 7, 8, 9, and 10 are used for the with the
LCD. Analog pin 0 is used to read the 5 buttons. The LCD
supports contrast adjustment and backlit on/off.

Here we can see the internal diagram of this shield:

Juan Carlos López Gordillo Page 112


Basic Arduino Course

When mounting the shield on top of Arduino, we will have several Arduino pins occupied and
we will be able to have the following:

Estashield comes with a library called 'LCD KeyPad', which must be copied into the
folder libraries of the Arduino IDE, this library in turn uses the standard control library
the LCDs called 'Liquid Crystal', which is already included by default in the Arduino IDE.

The Liquid Crystal library:

It allows the Arduino board to control LCD displays based on the Hitachi chipset.
HD44780 (or compatible), which is found in most text LCDs.
the library works in 4-bit mode or in 8-bit mode (that is, through 4 or 8 lines of
data, as well as RS, ENABLE, and optionally, the RW control lines.

LiquidCrystal (): Creates a variable of type LiquidCrystal. The screen can be


control through 4 or 8 data lines. In the first case, omit the numbers of
pins for d0 to d3 and leave those pins disconnected. The RW pin can be
connected to ground instead of connecting to an Arduino pin, if so, skip it from the
parameters of this function.

Syntax: LiquidCrystal (Rs, Rw, Enable, d0, d1, d2, d3, d4, d5, d6, d7)

Rs: Arduino pin number that is connected to the RS pin of the LCD
Rw: Arduino pin number that is connected to the RW pin of the LCD
Enable: Arduino pin number connected to the Enable pin of the LCD
d0, d1, d2, d3, d4, d5, d6, d7: Arduino pin numbers that are
connected to the corresponding data pins of the LCD.
d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using
only four lines of data (d4, d5, d6, d7).

Juan Carlos López Gordillo Page 113


Basic Arduino Course

Begin(): Specify the dimensions (width and height) of the LCD display.

Syntax: [Link]( Columns , Rows )

Lcd: A variable of type LiquidCrystal.


Columns: Number of columns that the display has.
Rows: Number of rows that the display has.

Clear : Borra la pantalla del display LCD y posiciona el cursor en la esquina superior
left.
Syntax: [Link]()

Lcd: a variable of type LiquidCrystal.

home() : Positions the cursor at the top-left corner of the LCD. This is the
position in which the following text will appear on the display. Unlike with the
previous that does not clear the previous content of the display.

Syntax: [Link]()

Lcd: A variable of type LiquidCrystal.

setCursor( ) : Sets the cursor position where they will start to appear
following characters written on the LCD.

Syntax: [Link](Column, Row)

Lcd: A variable of type LiquidCrystal.


Column: Column where to position the cursor (0 - first column).
Row: Row to position the cursor (0 - first row).

write( ) : Write a character on the LCD.

Syntax: [Link]( Data )

Lcd: A variable of type LiquidCrystal.


The character to be displayed.

print( ) : Prints text on the LCD.

Syntax: [Link](Data, BASE)

Lcd: A variable of type LiquidCrystal.


Data to print (char, byte, int...).

Juan Carlos López Gordillo Page 114


Basic Arduino Course

BASE (optional): The base in which the numbers will be printed: BIN, DEC,
OCT, HEX.

For more details on the functions of this library:[Link]

Data transmitter and receiver module at 433.92 MHz


In home automation, most wireless devices
Commercial devices use a frequency of 433.92 MHz. Other devices
of RF of KNX, for example, use the frequency 868.4MHz. We
we will use these modules that operate at 433.92 MHz, and due to the
reduced price for the couple we can add it to our
Arduino to create a multitude of combinations among various
devices at a quite affordable price.

The technical specifications of the modules are:

TX Module RX Module
Working tension 3V~12V Working tension 5.0Vdc + 0.5V
Current max≤40mA (12V), min≤9mA(3V) Current ≤ 5.5mA ( 5.0VDC )
Modulation ASK / ALSO Modulation ASK / OOK
Frequency 315MHz - 433.92MHz Frequency 315MHz - 433.92MHz
Speed ≤ 10 Kbps Speed < 9.6 Kbps
20-200 m (depending on the tension of
For maximum distance,
TX distance RX Distance put up wire antenna
work
of 23cm
TX and RX come paired.

The way to connect these modules to our Arduino is as follows:

To use these modules in Arduino, we need to add a library called 'RCswitch'


to the 'libraries' folder of the Arduino IDE and we will see some usage examples.

This library uses external interrupt 0 (digital pin 2), which we will study further.
go ahead, for now we will only use it

Juan Carlos López Gordillo Page 115


Basic Arduino Course

We can use it to communicate between 2 Arduinos, control a compatible device


through Arduino or control Arduino using a compatible device. For example, a
one of the commercial brands in the field of home automation is "avidsen", whose catalog of
products we can view on:[Link]

Another brand is, for example, 'dinuy', whose product catalog we can
visualize in:[Link]

In the workshop we have the kit composed of a lamp holder and its remote.
distance from the avidsen brand whose reference is 103211. This kit is used to turn on, turn off
to regulate the increase or decrease of light intensity with the
remote control. It has a range of 20m (A23 12V battery included).
It only works with E27 incandescent bulbs.
The operating frequency is 433.92 MHz with ASK/OOK modulation.
In the transmission, the information is encoded with a code, which when
arrives at the receiver, which is responsible for decoding it. This code can be
modify through some switches that both the sender and
the receiver.

Practices ( V )

P5a) Communication using the Serial port.

LCD1
LM016L
We will use Putty (Software that simulates
a terminal, similar to HyperTerminal, but from
+5V
free license) to send a text to our
Arduino and this should be displayed on an LCD of
RIGHT
R1
2k RV1 16x2 (LCD Keypad Shield module). It also
AD0
10k you can use the Serial Monitor that comes with
R2
UP
330 integrated into the Arduino IDE although this does not
+88.8

send the information until it is not pressed


Volts
ARDUINO
R3

Send.
620
DOWN
AREF
ARDUINO UNO R3
53/26
PB5/SCK
52/25
PB4/MISO
R4 RESET
~PB3/MOSI/OC2A 51/24

The serial port configuration will be:


1k 50/23
~ PB2/SS/OC1B
LEFT ~PB1/OC1A 49/22
D9
48/21
PB0/ICP1/CLKO D8
47/20
PD7/AIN1 D7
~PD6/AIN0 46/19
AD0 7/34 D6
R5 8/35
PC0/ADC0
~ PD5/T1
45/18
D5
3.3k PC1/ADC1 44/17
9/36 PD4/T0/XCK D4
SELECT 10/37
PC2/ADC2
~PD3/INT1 43/16
PC3/ADC3 42/15
11/38 PD2/INT0
PC4/ADC4/SDA 41/14
12/39 TXPD1/TXD
PC5/ADC5/SCL 40/13
RXPD0/RXD

CTS

RTS

TXD

RXD

In this case, Arduino is located on COM4.


We must establish that the data is transmitted in code.
ASCII, so the backspace (delete) key is the
ASCII character 8 in decimal.

Juan Carlos López Gordillo Page 116


Basic Arduino Course

The ASCII code: (American Standard Code for Information Interchange—Standard Code
American for Information Exchange.

ASCII code uses 7 bits to represent characters, although initially


used an additional bit called parity bit, which was used to detect errors in the
transmission.

Juan Carlos López Gordillo Page 117


Basic Arduino Course

The code to enter is the following:

Automatic garage door using RF

A final is available
"Fc" race for detection
when the door is found
closed, another finish line
"Fa" to detect when the
the door is open, a barrier
of infrared light, which without
detecting any obstacle, send a '1' and when it detects an obstacle the beam of light
infrared is interrupted by sending a '0'. The door in a resting state is closed and
acting 'Fc', when a vehicle wants to enter or exit, the driver sends a signal of
433.92 MHz radio frequency modulated in ASK and the door opens until 'Fa' is activated.
At that moment, a timer starts counting.

Juan Carlos López Gordillo Page 118


Basic Arduino Course

If "t" seconds pass without "FIRdetect some obstacle, the door must
to close

If while closing "FIRdetect any obstacle or conductor press the


remote control, the door must open.

If there is no obstacle that cuts the infrared beam and the remote control does not
When pressed, the door must close completely, activating to 'Fc' and remaining at rest.
until a new pulse from the remote control.

If while the door is open, activating 'Fa', the infrared barrier 'FIRdetects
any obstacle, no time 't' should pass, starting to count from the moment
what 'FIR” deje de detectar el obstá[Link] simular el mando a distancia, utilizar un pulsador,
such that when pressed, it is assumed that the remote control has been pressed and the code has been transmitted
correctly.

Juan Carlos López Gordillo Page 119


Basic Arduino course

The code to enter is the following:

Juan Carlos López Gordillo Page 120


Basic Arduino Course

The variable 'CódigoPermitido' should be modified with the code of the remote control.
of RF used, for this it is necessary to view in the Serial Monitor the code that is transmitted
when the button on the remote is pressed and replace 'longCodigoPermitido=263507;' with the code
transmitted by the RF control.

Sensors ( III )

DHT11 Sensor (Humidity and Temperature) - Digital

This DHT11 sensor will help us measure both relative humidity and the
temperature. The downside of this sensor is that it will only give us whole measurements, that is, without
decimals, since the resolution that
The presentation is 1% for relative humidity
and 1ºC for the temperature.

But it compensates since it presents a


very economical price for small ones
projects and allows us to obtain
measures for both humidity and
temperature.

This sensor is characterized


for having the digital signal calibrated
ensures high quality
and a reliability throughout the
time, since it contains a
8-bit microcontroller
integrated. It is made up of two
resistive sensors (NTC and
humidity). It has an excellent
quality and a quick response in
the measurements.

It can measure humidity between the range of 20%-90% and temperature between the range
0ºC–50ºC.

Each DHT11 sensor is strictly calibrated in the laboratory, presenting a


extreme precision in calibration. The calibration coefficients are stored as
programs in the OTP memory, which are used by the signal detection process
internal of the sensor.

The communication protocol is through a single wire (1-wire protocol), so


It makes the integration of this sensor into our projects fast and easy.
It also has a compact size, low consumption, and the ability to transmit the signal.
up to 20 meters away.

Juan Carlos López Gordillo Page 121


Basic Arduino course

The connection of the sensor to Arduino (sensor only without module), we must add a
pull-up resistance :

We will use this module that


it has the pull-up resistor and the
connection is made through 3 pins Vcc,
Table and Data:

LM35DZ Sensor (Temperature) - Analog

Another temperature sensor, quite interesting is the LM35 whose output voltage is
linearly proportional to the Celsius temperature (centigrades).

It is a precision integrated temperature sensor, whose output voltage is


linearly proportional to temperature in ºC (degrees Celsius). Does not require any
external calibration or adjustment to provide a typical accuracy of ± 1.4 ºC at temperature
environment and ± 3.4 ºC throughout its temperature range (from -55 to 150 ºC). The device is
adjusts and calibrates during the production process. The low output impedance, the linear output
and the precise inherent calibration allow the creation of reading or control circuits
especially simple.

Juan Carlos López Gordillo Page 122


Basic Arduino Course

Sensor DS18B20 (Temperature) - Digital

Es un pequeño sensor de temperatura de 9 a 10 bits de precisión desde -55 ºC a 125 ºC


with a margin of error of just 0.5 ºC. It does not require external components for its
operation. Each sensor comes factory-equipped with a 64-bit serial number that allows
connect multiple sensors in parallel using only one pin as a data bus.

The main advantage that these sensors present


up to 100 devices can be connected to a
unique pin and at a maximum distance from our Arduino
of 200 meters. These sensors use the protocol of
1-wire serial communication designed by Dallas
Semiconductor.

This communication protocol is basically


a bus where we have a teacher and several
slaves in a single line of data (pin of our Arduino) where they are powered.
supposedly, it also needs a reference to common ground for all devices. Also
We must know that the data/power line must have a pull-up resistor.
connected to power so that when data transmission does not occur we have 5
volts in that line.

In this type of sensors, we can find two types of power supply:

The first only supplies


nutrition while performing the
conversion operations of
temperature (parasite mode), it
They must bridge the GND and VDD pins.
from DS18B20 to GND of the Arduino.

The second is feeding of


the sensors through a source of
external power connected to the
VDD pin of the DS18B20, and the pin
GND to the GND pin of Arduino.

To use this component in Arduino, we need to add the "OneWire" libraries and
"DallasTemperature" inside the "Libraries" folder.

Juan Carlos López Gordillo Page 123


Basic Arduino Course

Practices ( VI )

P6a) Temperature and humidity measurements with DHT11.

As an application of the DHT11 sensor, we will visualize through a Terminal,


the temperature and humidity of the workshop

Connect the module to our Arduino and enter the following code:

Juan Carlos López Gordillo Page 124


Basic Arduino Course

P6b) Medidas de la temperatura con DS18B20

We are going to analyze the operation of the DS18B20 temperature sensor,


modifying an example that includes the library of that component. The connection with
Arduino se realiza de forma muy sencilla, utilizaremosel modo “parásito”, por lo que
we must bridge the 2 pins of the DS18B20 and connect them to ground, the terminal of the
center, we will connect it with a pull-up resistor to digital pin 2 of the Arduino.
We must add the libraries mentioned above and introduce the following code:

Note: The transistor is not necessary to connect it.

Juan Carlos López Gordillo Page 125


Basic Arduino Course

Introduction to the HTML language

Next, we will start to communicate our Arduino with more devices.


A very fast form of communication is through the Internet. Our Arduino is capable of
communicate with web pages, sending and/or receiving information with only the requirement of
install the Ethernet shield, which some boards have integrated.

But before studying the Ethernet shield, we need to know the HTML language that
and on which websites are based.

We can use a program like Dreamweaver or another similar one in which


we can create a WEB page in design mode without having knowledge of HTML and
subsequently, through a button, view the code that this program has generated for
create the corresponding HTML file.

A document prepared by the University of Murcia is attached in which it is explained that


a very practical way to create web pages in HTML.

The Ethernet board will be studied next and several will be carried out subsequently.
practical exercises where we will see how information can be sent over the Internet
using Arduino, so we will use HTML language to create very WEB pages
simple.

The Ethernet shield plate

Next, we will see how to send and receive information.


through the Internet and, for this, we will need the board
Arduino Ethernet Shield. Some knowledge will be needed.
basics of HTML and/or PHP, simply to be able to make the
web page to our liking. Through this web page,
we will be able to send and/or receive information from a PC, iPad, tablet,
or any device with a WI-FI connection.

All devices that are connected to the same.


local network, to which the connected Arduino will have the possibility to access this page.

It is based on the Wiznet W5100 ethernet chip. It supports up to four connections of


simultaneous sockets.

Juan Carlos López Gordillo Page 126


Basic Arduino Course

Use the Ethernet library to write programs that connect to the internet using the
The Ethernet shield has connectors that allow it to connect to other
place them on top and stack them on the Arduino board.

Important:

Arduino uses digital pins 4, 10, 11, 12, and 13 (SPI)


to communicate with the W5100 on the ethernet shield.
These pins CANNOT BE USED for inputs and/or
generic outputs.

The shield provides a standard RJ45 Ethernet connector.


The reset button on the shield resets both the W5100 and the Arduino board.
The shield contains a number of LEDs for information:

a) PWR: indicates that the board and the shield are powered.
b) LINK: indicates the presence of a network link and blinks when the shield sends
or receive data.
c) FULLD: indicates that the network connection is full duplex.
d) 100M: indicates the presence of a 100 Mb/s network connection.
opposite to one of 10Mb/s)
e) RX and TX: blinks when the shield receives/sends data
f) COLL: blinks when collisions are detected on the network

We can observe that the Ethernet shield has a sticker on the bottom.
where it indicates to us the MAC (Media Access Control, 'media access control') is a
48-bit identifier (6 hexadecimal blocks) that uniquely corresponds to a
network card or device. It is also known as physical address. More information at:

[Link]

Juan Carlos López Gordillo Page 127


Basic Arduino Course

Shields that do not have any sticker indicating the MAC can be assigned.
a random MAC, but all the MACs of the devices on the local network must be different.

We can also observe that the Ethernet Shield has a connector to house
a microSD memory card, which we can use to store or read the data that
we want.

To analyze this shield in more detail, a document is attached in the course.


called "Arduino + Ethernet Shield", in which it is studied in greater detail.

Practices (VII)

P7a) Web Server: Control of a device from an HTML Web page.

What we are going to create with the Ethernet Shield is a Web server, which will allow us
it will provide the HTML code so that we can view it in our browser and thus interact
with him.

On the Internet, a server is a remote computer


that provides the requested data by
browsers from other computers. In local area networks (LAN,
Local Area Network), it is understood as the software that
set up a PC as a server to facilitate access to the
network and its resources. The servers store information
in the form of web pages and, through the HTTP protocol it
delivered at the request of clients (web browsers) in HTML format.

A server provides information to the computers that connect to it. When the
Users connect to a server, they can access programs, files, and other information.
from the server.

Para acceder a la página Web que creemos, deberemos acceder con una dirección IP
belonging to our network, which will be the one we have assigned to the Ethernet Shield. In the
code that you will see below, you will see that the IP address I have assigned is
[Link]/24.

What does /24 mean?

It is the subnet mask, being /24, means that we will have 24 bits as '1' and 8 as '0'.
'0', that is, it will be [Link].

Juan Carlos López Gordillo Page 128


Basic Arduino Course

Para comenzar, abriremos una consola de DOS ( Inicio–


Accessories–Run–cmd /o in 'Search programs and files'
we type "cmd" and press enter ) .

Next, we will type 'ipconfig' and we will be able to see in


What subnet are we in? My default gateway is
[Link], so I will assign the Ethernet Shield an IP address that
is free within the local network, for example
[Link]/24.

The assembly of the project is very simple, as it only requires


needs an LED and a limiting resistor, connected to pin 9 of
Arduino.

The list of the sketch is as follows:

Juan Carlos López Gordillo Page 129


Basic Arduino Course

With the program compiled and uploaded to Arduino, if we open the browser
any PC, mobile, tablet, etc. that is connected to the local network via cable or
wirelessly, and we type the IP [Link], we will enter the Web that we have written
in the sketch, that is, we will have the following window:

If we press the 'ON' button, we will see how


the LED lights up and if we press the 'OFF' button,
we will see how the Led turns off.

As can be deduced, if the website includes graphs or is more complex,


we would have problems hosting the website in the internal memory of the microcontroller, for that reason
This is why the possibility of using a microSD card has been included, however, hosting a page
web with graphics, on the microSD will make loading and/or refreshing very slow, so that, as
In conclusion, we will use the microSD to store or read data that is found in files.
We will host the web pages on normal servers whose speed and bandwidth
The bandwidth will far exceed that of the Ethernet Shield plate from Arduino.

Juan Carlos López Gordillo Page 130


Basic Arduino Course

Automatic temperature control of a room with Web visualization.

We are going to automatically control the temperature of a room to


Hello, we are going to use an Ethernet shield to which we will connect an LED (simulating
the air conditioning device), on pin 9 with its limiting resistor.

We will connect a temperature sensor.


DS18B20 in 'parasitic' mode on digital pin 2
Arduino and a 10 kΩ variable resistor in the
analog input 0 of the Arduino, this resistor
variable will serve to adjust the threshold of
temperature at which the air conditioning device is
active or deactivated.

If the room temperature exceeds the


established threshold, the air conditioning device must
deactivate and when the temperature of the
the room is below the established threshold, the
The air conditioning device must be activated.

The result, once compiled and saved in Arduino, we will be able to verify.
opening a browser and typing the IP address of the Ethernet shield. The page will refresh
every 5 seconds.

Juan Carlos López Gordillo Page 131


Basic Arduino Course

The code to enter is the following:

Juan Carlos López Gordillo Page 132


Basic Arduino Course

Final comments

To conclude, I will mention that every day new applications and new projects arise.
new modules and new research about Arduino that make this board have
much acceptance especially in Teaching, since it is possible to achieve with little effort
rather attractive projects.

Currently, I am teaching Arduino in the Home Automation Installations module.


of the second year, of the intermediate training cycle 'Telecommunications Installations',
As is known, the students who take these studies have an intermediate level of
electronics, so these contents must be adapted to the student's level.

Students at this level, when they start to work on projects with sensors,
motors, limit switches, relays, mobile devices, etc.... acquire a high motivation and this leads to
so that the students take an interest in the module and even some students acquire through their
count the Arduino board, shields, modules, and electronic components to carry out projects
individuals in their home.

Juan Carlos López Gordillo


Ing. Tech. Ind. Telecommunications
Teacher at IES Enric Valor–Silla (Valencia)
Electronic equipment

Juan Carlos López Gordillo Page 133


Basic Arduino Course

Bibliography

PROTEUS. Simulation of electronic circuits and microcontrollers through


examples.
Germán Tojeiro Calaza
Marcombo

CCS C compiler and PROTEUS simulator for PIC microcontrollers.


Eduardo García Breijo
Marcombo

Home Automation Installations.


Molina
McGraw-Hill

Automated installations in homes and buildings.


David Lasso Tarraga, Jose Moreno Gil, Elias Rodríguez Diéguez
Auditorium

Home Automation Installations.


Miguel Moro Vallina
Auditorium

Principles of electronics.
Malvino
McGraw-Hill

Introduction to Arduino Course.


Ricardo Carpio Richard
CEFIRE–Cheste

OpenDomo. Free security and home automation: [Link]

Arduino: [Link]

BricoGeek : [Link]

Arduteka :[Link]

Juan Carlos López Gordillo Page 134


Basic Arduino Course

INDEX OF PRACTICES

PRACTICE ( I ) : Digital inputs and outputs.


P1a) Reading the state of a button and visualizing it on an LED 67
Start and stop buttons 68

PRACTICE (II): Mobile hook.


Mobile hook 91
P2b) Mobile hook v2, with start and stop 91
P2c) Mobile hook v3, with start, stop, and memory 91
P2d) Mobile hook v4, using the Arduino EEPROM 91

PRACTICE (III): Practicing with LDR and ultrasound


P3a) Light regulation in a garden 91
Automatic access door to supermarkets, hospitals, etc... 101

PRACTICE (IV): The importance of rebound control.


Different operating modes of a push button 106
P4b) 5-story elevator 109

PRACTICE (V): Communications with Serial Port and practicing with RF.
P5a) Communication using the Arduino serial port 116
P5b) Automatic garage door using RF 118

PRACTICE (VI): Measuring Temperature and Humidity.


P6a) Measurement of temperature and humidity with DHT11 124
P6b) Temperature measurement with DS18B20 125

PRACTICE (VII): Communication using the WEB.


Web Server 128
P7b) Automatic temperature control with web visualization 131

Juan Carlos López Gordillo Page 135

You might also like