0% found this document useful (0 votes)
11 views120 pages

Comprehensive Arduino Guide

This document serves as a comprehensive guide to Arduino, covering topics from basic electronics and programming to practical applications and tutorials. It aims to demystify technology for beginners and enthusiasts by providing accessible information about physical computing, components, and project development. The guide includes detailed sections on Arduino hardware, software, and various DIY projects, making it suitable for learners at all levels.

Translated by

ScribdTranslations
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)
11 views120 pages

Comprehensive Arduino Guide

This document serves as a comprehensive guide to Arduino, covering topics from basic electronics and programming to practical applications and tutorials. It aims to demystify technology for beginners and enthusiasts by providing accessible information about physical computing, components, and project development. The guide includes detailed sections on Arduino hardware, software, and various DIY projects, making it suitable for learners at all levels.

Translated by

ScribdTranslations
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

A practical guide to the world of Arduino

BASIC GUIDE TO ARDUINO


BASIC GUIDE TO ARDUINO
Intentionally left blank page
Purpose..................................................................................... 9 T
A
What am I going to learn?........................................................10 B
Source of information .................................................................. 10 L
A
1. Introducción............................................................................ 11
D
1A. Physical Computing............................................................12 E
2. To take into account................................................................. 13 C
O
2A. Robotics Store...............................................................13
2B. Things of Mechatronics.............................................................13 N
2C. Free hardware ....................................................................14 T
Free software E
2E. Creative commons ................................................................14 N
2F. Arduino .............................................................................15 I
2G. Fritzing.............................................................................15 D
2H. Work License ...............................................................16
O
3. Electronics............................................................................. 17

3A. Concept of electronics.........................................................17


3B. Voltaje..............................................................................17
3C. DC Voltage..........................................................................18
3D. AC Voltage.............................................................18
3E. Current ...........................................................................18
3F. Resistance .........................................................................19
3G. Ohm's Law........................................................................19
3H. Electronic systems............................................................19
3I. Entries............................................................................19
3J. Outputs ..............................................................................20
3K. Signal processing..........................................................20
3L. Electronic signals..............................................................21
3M. Variable digital....................................................................21
3N. Analog variable.................................................................21
30. Digital input/output ............................................................22
3P. Analog input/output...........................................................22
Voltage divider .................................................................22
3R. Analog-to-digital converter..........................................22
3S. Pulse Width Modulation PWM..........................................23
3T. Serial communication..............................................................23

4. Electronic Components.......................................................... 25

4A. Microcontroller..................................................................25
4B. Protoboard.........................................................................26
4C. Resistance ........................................................................26
4D. Color code table for resistors............................................27
4E. Diode................................................................................28
4F. Transistor.......................................................................... 28
4G. Capacitor ...................................................................... 28
4H. LED ................................................................................. 29
4I. LED RGB ........................................................................... 29
[Link]............................................................................ 29
4K. Reed switch ....................................................................... 30
4L. Potentiometer.................................................................... 30
4M. Photocell......................................................... 30
4N. Bell or buzzer............................................................... 31
40. DC Motor............................................................... 31

5 Programming............................................................................ 33

5A. Concept of programming...................................................... 33


5B. Programming language...................................................... 34
5C. Machine language........................................................... 34
5D. Assembly language........................................................... 34
5E. High-level language ........................................................... 35
5F. Algorithm .......................................................................... 35
5G. Body of an Arduino program............................................ 35
5H. Structures ........................................................................ 36
5I . Variables........................................................................... 36
5J. Boolean operators............................................................ 36
5K. Comparison operators.................................................... 36
5L. Mathematical operators........................................................ 37
5M. Control structures........................................................... 37
5N. Conditionals
50. Cycles............................................................................... 37
5P. Functions.............................................................. 38
5Q. Digital functions............................................................... 38
5R. Analogous functions............................................................... 39
5S. Quick reference for scheduling............................................. 40

6. Arduino .................................................................................. 43

6A. Arduino Project ................................................................. 43


6B. Arduino Family .................................................................. .44
6C. Expand Arduino with shields ............................................... 45
6D. Arduino Uno board and its parts ................................................. 46
6E. Installing drivers................................................................. 48
6F. Knowing the Arduino software................................................ 51
6G. Loading my first program.................................................. 52

7. Basic kit................................................................. 55

7A. Description........................................................................ 55
7B. Distribution........................................................................ 55
7C. Fotos ............................................................................... 56
8. Fritzing.................................................................................. 57

8A. Software............................................................................57
8B. Protoboard view...................................................................57
8C. View diagram .....................................................................58
8D. Vista PCB—Printed circuit .....................................................58
8E. Master exercise...................................................................59

9. Tutoriales............................................................................... 60

T0. Learn what the tutorials are like .................................................60


T1. Hello World–Flashing LED..................................................62
T2. Turn on an LED with a button...............................................66
T3. Serial reading of a digital input...........................................70
T4. Serial reading of an analog input .........................................74
T5. Serial writing.....................................................................78
T6. Turning on an LED via PWM .......................................................82
T7. ON/OFF control with potentiometer ...........................................86
T8. Control of an LED with a photoresistor..........................................90
T9. Pulse counter...............................................................94
T10. Magnetic switch for a visual alarm...............................98
T11. RGB LED supported by color table ...................................... 102
T12. Motor ON/OFF control................................................. 106
T13. PWM control of a motor................................................ 110
T14. Generate tones with a buzzer................................................. 114
Page left intentionally blank
PURPOSE

Knowing how things work is something we have considered.


Since the beginning of time; today we face a reality
where automation, home automation (automation of the
houses and buildings), the interaction of people with machines, the
electronics, mechanics, and programming.

Almost any process we can imagine has a percentage of


dependence on these machines, for example: Your alarm clock went off at
6am for you to come to school or go to work, that machine, clock,
worked all night to finally let you know it was time to dis-
to wake up.

The purpose of this guide is to address the concept of physical computing that
it is the ability of a machine to interact and communicate with the
humans, using sensors and actuators. The decisions on this will be made by
Take a microcontroller that is located on the Arduino board.
The Arduino board is the heart of this guide.

9
WHAT AM I GOING TO LEARN?

Many times we think that technological topics require great skill


technical expertise and great knowledge, but this is not true. We want
that with the development of this guide you understand that many of those processes
technological ones are simple to understand and those that are complex are the
union of many simple processes.

In this guide, you will learn to imagine and ground all ideas into concepts.
tangible things you can be proud of, since it was your idea and you
you developed ;)

F Wikipedia is one of the largest cloud encyclopedias that can exist.


U you can find a wide variety of information in different languages and you are free to
E use it to learn.
N
This guide incorporates content from Wiki-
T pedia (text and images) in the spirit of ex-
E apply the various concepts that are stated.
The content from Wikipedia taken in this
D the guide has been transcribed verbatim in some-
E in some cases, in other cases the concepts have been
re-edited for easier understanding-
I lie the idea.
N
F Para referenciar que hemos tomado contenido
O from Wikipedia, next to each technical concept
you are going to find the Wikipedia logo of this
R
this way you can read more content if you search
M that same concept on Wikipedia.
A
C Wikipedia is free content, so that all the text is available under
I theCreative Commons Attribution-ShareAlike 3.0 (CC-BY-SA)The biggest
O part of the content is also available under theDocumentation License
GNU Free Documentation License (GFDL). This means that the content of Wikipedia can be distributed and
N
link according to the provisions of these licenses.

10
1. INTRODUCTION

The Robotics Store and the Mechatronics Stuff Team bring this guide
which addresses learning about the DIY (Do it yourself) concept
spanish - 'Do it yourself'. After a careful selection of components-
Electronic kits supported by the Arduino board are created.
Basic Arduino supported by this guide.

We addressed fundamental topics such as free hardware and software,


carefully sanding the Arduino project and relying on the Soft-
Fritzing tool to achieve very eye-catching assemblies similar to the real ones.
Dad. It's not necessary for you to know about electronics and programming because with
In the following two chapters, we will address the concepts from the most basic level.
up to the fundamentals. After understanding these concepts we have a capi-
a title dedicated to introducing you to electronic components such as an LED,
a motor, a buzzer, and many more. We have designed a special chapter
about Arduino and Fritzing which you cannot miss. This Basic Kit
it is ideal for all areas of learning from school to university
data, and if you are an enthusiast or a fan, you cannot miss having this.
home guide, a whole chapter is dedicated to showing the kit from bottom to top.
up :)

Finally, we have arrived at a very special part, the chapter on tutorials-


the, where 14 examples are explained step by step, during the reco-
In the learning journey, you will encounter questions, tips, and exercises.
cicios.
DIY

11
Physical computing
Physical computing means the construction of inter-
activos físicos mediante el uso de software y hardware que pueden
to feel and respond to the analog world. Although this definition is
sufficiently broad to encompass aspects such as systems
intelligent traffic control for cars or processes of
1A factory automation, in a broader sense, the computa-
Physical education is a creative framework for understanding the relationship
of human beings in the digital world. In practice, often
the term describes handmade art, DIY project design
the hobbies that use sensors and microcontrollers to
lead analog inputs to software-based systems, and/or with-
control electromechanical devices such as motors, servos, ilumi-
nation or other hardware.

Other implementations of computa-


physical education works with the recognition
the lie of the voice, which is captured and
they interpret their sound waves through
of microphones or other devices of
detection of sound waves, also the
computer vision, which applies something-
rhythms to the detected videos by
some type of camera. Touch interfaces-
the sounds are also an example of the com-
physical reputation.

Prototyping (creating quick assemblies with the help of a proto-


board and basic components of electronics) play an important role
aunt in physical computing. Tools like Arduino and Frit-
zing are useful for designers, artists, students and in-
enthusiasts because they help to quickly develop prototypes.

12
2. TO TAKE INTO ACCOUNT

We present to you information of interest that we recommend you keep.


in mind for the development of this guide. Learn more about the
developers and the pillars of this excellent material.

Robotics Store
The Robotica Store
in 2010 with the idea of
make available to you-
fronts, professionals and afi-
robotics the best used products in the world for
develop their projects.

The social responsibility that the world demands from us means that through
2A
Robotics store and the website Things of Mechatronics we can compare
news, events, tutorials, projects among others. The Store of
Robotics is located in the city of Bogotá D.C, Colombia and is
only virtual. We appreciate that you buy our products with the best
market price. Contact us to learn more about us.

Things about Mechatronics


Mechatronic things in
January 2007, after mu-
three attempts of its creator
Yesid Hernández to make pages-
in web. Until April 2009, it was hosted on wordpress (http://
[Link]). Starting in May 2009, Things of Mechatronics-
Nica acquired its own domain with the idea of continuing to share information
training and helping to grow the Mechatronics community in Spanish. 2B
Initially, it was born only as a place to publish and share.
the mechatronic projects carried out by Ibraim Yesid Hernández Olarte,
now seeks to be a collaborative environment for all people and organizes
interested parties in sharing information about Mechatronics.
The participation in the BLOG mainly comes from SENA students.
but not only from them, and it is sought to create a community by sharing
information about small and large projects in which we are all involved
working.

13
Free hardware
It is called hardware that frees hardware devices.
whose specifications and schematic diagrams are of
public access, whether under some type of payment or for-
it's free. The philosophy of free software (the ideas
about the freedom of knowledge) is applicable to that of
free hardware. It must be remembered at all times that
2C Free is not synonymous with free of charge. Free hardware forms
part of free culture.

Since the hardware is associated with various costs


direct statements, no definition of free software can be applied directly without
modification. Instead, the term free hardware has mainly been used to
reflect the use of free software with hardware and the free launch of
the information regarding the hardware, often including the launcher-
maintenance of schematic diagrams, designs, and assemblies.

Free software
Free software (in English free software, although this
the term is sometimes confused with 'free'
due to the ambiguity of the term 'free' in the language
2D English, so "free software" is also used and
"logical free" is the name of the software that
respect the freedom of users regarding their product
acquired and, therefore, once obtained it can be used
done, copied, studied, modified, and redistributed
freely. According to the Free Software Foundation, the soft-
Free software refers to the freedom of the users.
rights to execute, copy, distribute, study, modify the software and
distribute it modified.

Creative Commons
Creative Commons (CC) is a non-profit organization
governmental non-profit that develops
plans to help reduce legal barriers
2E from creativity, through new legislation
and new technologies. Creative Com licenses
mons or CC are inspired by the GPL (General Public License) of the Free
Software Foundation, sharing a good part of its philosophy. The main idea
behind them is to enable a legal model supported by computer tools
case, in order to facilitate the distribution and use of content.

There is a series of Creative Commons licenses, each with different configurations.


actions, which allows authors to decide how their work will be
circular on the internet, granting freedom to quote, reproduce, create works
derivatives and to offer it publicly, under certain different restrictions.
The license for this work is displayed on page 16.

14
Arduino
Arduino is an electronics platform.
open for prototyping based-
from free software and hardware, flexible and
easy to use. It was created for artists, designed-
pain, enthusiasts, and anyone interested in
create interactive environments or objects.

Arduino can take information from the environment


not through its input pins, for
2F
esto toda una gama de sensores puede ser
used and can affect what surrounds it by controlling lights, motors, and other ac-
drivers. The microcontroller on the Arduino board is programmed using the language
of Arduino programming (based on Wiring) and the Arduino development environment
(based on Processing). Projects made with Arduino can run without
need to connect it to a computer, although they have the possibility to do so and
communicate with different types of software (e.g. Flash, Processing, MaxMSP).

The boards can be handmade or purchased assembled from the factory; the software
can be downloaded for free. The reference design files (CAD)
they are available under an open license, so you are free to adapt them to your
needs.

[Link]

Fritzing
Fritzing is a design automation program
free electronic that seeks to help designers and artists
so they can move from prototypes (using, for example,
test plates) to final products.

Fritzing was created based on the principles of Processing and Ar-


duino and allows designers, artists, researchers and
aficionados document their prototypes based on Arduino and
create printed circuit schematics for later
2G
manufacturing. In addition, it has a complementary website that helps to compare
to pull and discuss outlines, experiences, and to reduce manufacturing costs.

[Link]

15
License of the work

2H

[Link]/licenses/by-nc-sa/3.0/[Link]

16
3. ELECTRONICS

From the beginning of this chapter, you will learn the technical terms.
what electronics has and that at the end of this you will most likely...
to master expertly.

Concept of electronics
Study and employ systems whose function-
namiento is based on driving and the
control of the flow of electrons
other electrically charged particles
you.

The design and the great construction of


electronic circuits to solve
practical problems are part of the
3A
electronics and the fields of engineering
electronic engineering, electromechanics and
Computer science in software design
for your control.

Electronics currently develops a wide variety of tasks. The main


the uses of electronic circuits are control, processing, distribution of
information, the conversion and distribution of electrical energy. These two uses
they involve the creation or detection of electromagnetic fields and electric currents
tricks.

Look around you: radio, television, PC, mobile phone, washing machine - all
they have electronics.

Voltage

A physical quantity that drives electrons to the


length of a conductor (for example a cable) in
a closed electric circuit, causing the flow of 3B
an electric current. Its unit is the Volt (V). The ins-
The instrument used to measure voltage is known as
as a voltmeter.

17
DC Voltage
It is the continuous flow of electrons through
a conductor between two points of different potential. In
in direct current, electric charges flow continuously.
flowing in the same direction, the current is continuous
it always has the same polarity. In the system standard-
European tic the color black corresponds to the negative and the

3C red to positive or simply symbolizes for him


positive with VCC, +, VSS and for the negative with 0V, -, GND.

Many devices need direct current to


to function, especially for those that carry electronics
(audiovisual equipment, computers, etc.), for
There they use power supplies. You can...
find in the batteries, batteries, output of the load-
computer pains.

AC voltage
It is the electric current in which the magnitude and
directions vary cyclically. The waveform of
the most commonly used alternating current is the
3D of a sine wave.

The AC voltage is the one that arrives at the electrical outlets.


dad of homes and to businesses, it is very common
find it in the outlets where it co-
we connect our appliances. However, the audio signals
and radio transmitted through electrical cables are also examples
of alternating current. In these uses, the most important purpose
it is usually the transmission and recovery of information
encoded (or modulated) over the AC signal.

Current
It is the flow of electrons through a conductor or semiconductor.
in a sense. The unit of measurement for this is the ampere (A).
An electric current, since it is a movement of
3E charges produce a magnetic field, a phenomenon that can
take advantage of the electromagnet, this is the principle of operation
engine maintenance.

The instrument used to measure the intensity of the current


the electric one is the galvanometer that, calibrated in amperes, is called
ammeter, placed in series with the conductor whose
intensity is desired to be measured.

18
Resistance

It is the physical property by which all matter-


they tend to oppose the flow of the current. The unit
The unit of this parameter is the Ohm (Ω). You can find 3F
resistances in electric heaters, cards
electronic stoves are very useful for limiting the passage
from the current.

Ohm's Law
The law states that the current (I) flowing through
an electrical conductor is directly proportional
to the voltage (V) and inversely proportional to
the resistance (R). 3G
The pyramid on the right is very useful to know
the formula to which the variable that you cover with is equal
the finger, for example: Cover the V with your finger
(voltage), then voltage will be equal to I
(current) through R (resistance), one more, cover I
(Current), I will be equal to V divided by R.

Electronic systems
An electronic system is a set of circuits that interact
join together to achieve a result. One way to understand
electronic systems consist of dividing them into inputs, outputs 3H
signal processing.

Entries
The inputs: They are sensors (or transducers) electronic-
or mechanics that take the signals (in the form of tempera-
pressure, humidity, contact, light, movement, pH, etc.
from the physical world and convert them into current signals or 3I
voltage.

For example, a temperature sensor, a p-


sador, a photocell, a potentiometer, a
motion sensor among many others.

19
Exits
Outputs: They are actuators or other devices (also
transducers) that convert current or voltage signals into
physically useful signals like movement, light, sound, force,
rotation among others.
3J
For example: a motor that turns, an LED or lighting system that
turns on automatically when it gets dark, a
buzzer that generates various tones.

Signal processing

It is done through signal processing circuits.


commonly known as microcontrollers. They consist of
3K in interconnected electronic pieces to manipulate,
interpret and transform voltage and current signals
coming from the sensors (Inputs) and take the respective
make decisions to generate actions in the outputs.

Summary of Electronic Systems

As an example, let's suppose a television. Its input is an analog signal received


through an antenna or through a cable. The integrated circuits inside the television
extract the information about the brightness, color, and sound of this signal. The devices-
output devices are an LED screen that converts electronic signals into images
visible on a screen and some speakers.

Another example could be that of a circuit that controls the temperature.


tour of a place, the temperature sensor and the integrated circuit
is responsible for converting the input signal into a voltage level
appropriate and if the recorded temperature is very high the
integrated circuit sends the information to a motor to
may this turn on the fan and cool the place.

20
Electronic signals
The inputs and outputs of an electronic system will be considered
variables such as variable signals. In electronics, one works with
variables that are taken in the form of voltage or current, these
They can commonly be referred to as signals. 3L
Signals can primarily be of two types
described below: Digital or analog

Digital variable

Also called discrete variables. They are characterized by


for having two differentiated states and for the 3M
they can be called binary. Being these va-
easier variables to handle (in logic they would be the
true (V) and false (F) values or they could be 1 or
0 respectively).

An example of a digital signal is the switch.


from the doorbell of your house, because this switch
it has two states pressed and not pressed

Analog variable

They are those that can take an infinite number of


values between two limits. Most of
The phenomena of real life are signals of this type.
(sound, temperature, voice, video, etc.)
3N

An example of an analog electronic system


it is a speaker, which is used to amplify
the sound in such a way that it is heard by a
large audience. The sound waves that are
analogous in origin, are captured by a
microphone and converted into a small varia-
analog voltage conversion called
audio signal.

21
Digital input / output

30
Entry Exit Entrance
Button LED Reed switch

Analog input/output

3P

Entry Exit Entrance


Photocell DC Motor Potentiometer

Voltage divider
A voltage divider is a circuit configuration
trick that distributes the voltage of a source (Vin) between a
or more resistances (R1, R2) connected in series (one to
continuation of another).
Thank you

Analog-to-digital converter ADC


An analog-to-digital converter (ADC), (or
The ADC (short for 'Analog-to-Digital Converter') is a device-
electronic device capable of converting an analog input of
voltage in a binary value. It is used in electronic equipment
3R such as computers, sound and video recorders, and eqi-
telecommunications post. The analog signal, which varies from
continuous form over time, connects to the input of the dis-
positive and is subjected to sampling at a speed
fixed, thus obtaining a digital signal at its output.

22
Pulse Width Modulation PWM
Pulse Width Modulation (also known as PWM, an acronym in English for
Pulse-width modulation of a signal or power source is a technique in which
the duty cycle of a periodic signal (a sinusoidal or a square wave) is modified
for example), whether to transmit information through a communication channel 3S
or to control the amount of energy sent to a load.

For example, if we apply PWM to an LED, we can vary its brightness intensity and if
we apply a PWM to a DC motor to vary its speed with it
characteristic of maintaining its torque (force) constant.

Serial communication
It is a communications interface of
digital data, frequently used
clad by computers and peripherals,
where the information is transmitted 3T
of sending a single bit to the
once. One of its uses is to monitor
through the computer screen
the condition of the beltway
connected, for example, when pressing the letter A on the keyboard it should turn on
a LED connected remotely to the computer.

SCAN WITH YOUR


SMARTPHONE

SEARCH T03AB
LIKE THIS

VISIT THE OPTION OF

23
Page left intentionally blank

24
4. ELECTRONIC COMPONENTS

Various electronic components join forces to achieve application-


fantastic things such as the television in your house or the computer,
Inside them you will find cards with resistors, capacitors-
resistors, integrated circuits, transistors among others.

Microcontroller
A microcontroller (abbreviated μC, UC, or MCU) is a circuit
programmable integrated circuit, capable of executing the recorded commands
in its memory. It consists of several functional blocks,
which perform a specific task. A microcontroller
includes inside the three main functional units:
central processing unit (CPU), memory, and input and output peripherals
(I/O).

So that I can control some process 4A


it is necessary to create and then save in the
EEPROM memory of the microcontroller
some program, which can be written
to assembly language or another len-
a bridge for microcontrollers; it must be
encoded in hexadecimal number system
What is finally the system that
makes the microcontroller work when-
this is powered with the appropriate voltage and associated with analog devices and
discrete for its operation.

Microcontrollers represent the vast majority of chips sold, tie-


are distributed surely among the appliances in your home one or two
dozens of microcontrollers. They can be found in almost any device
electronic items such as cars, washing machines, microwaves, phones, Arduino.

Microcontrollers are mostly used to receive signals from devices of


input/output, with the great advantage that it can do without any other
external circuitry.

The I/O (input/output) ports in


the microcontroller is grouped into ports
of 8 bits in length, which allows for reading
data from abroad or write in them from the
interior of the microcontroller, the destination is the
I work with simple devices like relays,
LED, motors, photocells, pulsed
res or anything else that is given to her
it occurs to the programmer.

25
Breadboard
It is a reusable board used to build prototypes of electronic circuits without
welding. Composed of perforated plastic blocks and numerous sheets
thin wires of an alloy of copper, tin, and phosphorus

4B

Real view Internal connections

Resistance

4C

Symbol Component

It is a material made of carbon and other resistive elements to decrease the


current that passes. It opposes the flow of current. The maximum current in a
The resistor is conditioned by the maximum power it can dissipate through its body.
This power can be visually identified from the diameter without it being
Another indication is necessary. The most common values are 0.25 W, 0.5 W, and 1 W.

The value of electrical resistance is obtained by reading the figures as a


number of one, two or three digits; it is multiplied by the multiplier and is
get the result in Ohms (Ω).

Q Complete according to the color table from the following page


U
I 1- 2-
Z _____Ω
_____Ω

26
Color code chart for resistors

4D

Example

The characterization of a resistance of


2,700,000Ω (2.7MΩ), with a tolerance of
±10%, it would be represented in the figure:

1st digit: red (2)

2nd digit: violet (7)

Multiplier: green (100000)

Tolerance: silver (±10%)

27
Diode

4E
Symbol Component
A diode is a two-terminal electronic component that allows the flow.
of the electric current through it in one direction. It has two parts: the cat-
and the anode.

Transistor

4F
Symbol Component
The transistor is a semiconductor electronic device that performs functions of
amplifier, oscillator, switch or rectifier. It has three parts: the base (B), the
emitter (E) and collector (C).

They are currently found in almost all household appliances in use.


diary: radios, televisions, recorders, audio and video players, ovens of
microwaves, washing machines, cars, refrigeration equipment, alarms, watches
quartz, computers, calculators, printers, fluorescent lamps,
X-ray machines, tomographs, ultrasound machines, MP3 players, phones
cell phones, etc.

Capacitor

4G
Symbol Component
A capacitor is a device used in electronics, capable of
storing energy by sustaining an electric field. It is formed by a pair of
conductive surfaces, usually in the form of sheets or plates, in situation
of total influence separated by a dielectric material or by vacuum.
The plates, subjected to a potential difference, acquire a certain
charged electric, positive on one of them and negative on the other.

28
LED

Symbol Component
4H
A LED (Light Emitting Diode, also 'luminous diode') is a semiconductor diode.
that emit light. They are used as indicators in many devices,
and increasingly more frequently in lighting. The LEDs
they offer many advantages over incandescent light sources
it has a much lower energy consumption, longer time of
life, smaller size, great durability and reliability.

The LED has a polarity, a connection order, and when connected the other way around
it can be burned, check the drawings at the top to get to know
what corresponds to the positive and the negative.

LED RGB

4I

Symbol Component

An RGB LED is an LED that incorporates three within its own encapsulation.
LEDs, it is RGB because R (red), G (green), and B (blue)
this way thousands of colors can be formed by adjusting individually
Each color has two. The three LEDs are connected by the negative or cathode.

Button

Symbol Component
4J
A button or switch is used to activate a function. Buttons are for
general activated when pressed, usually with a finger. A button on a device-
an electronic switch generally works like an electrical switch, that is to say in
its interior has two contacts, if it is a NO (normally open) device
to) NC (normally closed), so when pressed it will activate the fun-
reverse action of the one I am currently performing.

29
Reed switch

4K
Symbol Component

A reed switch is an electrical switch activated by a magnetic field.


example with a magnet. When the contacts are normally open, they close.
in the presence of a magnetic field; when they are normally closed they
they open in the presence of a magnetic field. A very widespread use can be
to find in the sensors of doors and windows of anti-
Robot, the magnet is attached to the door and the reed switch to the frame.

Potentiometer

4L
Symbol Component
A potentiometer is a resistor whose resistance value is variable. From this
way, indirectly, the intensity of current flowing through can be controlled
A circuit can connect in parallel, or control the voltage when connecting it in series.
They are suitable for use as a control element in the devices.
electronics. The user acts upon them to vary the parameters
operating standards. For example, the volume of a radio.

Photocell

4M
Symbol Component
It is a resistor, whose value in ohms varies with changes in the incident light.
A photocell exhibits a low resistance value in the presence of light and
a high resistance value in the absence of light.

They can be found in many consumer items, such as for example


in cameras, light meters, radios with clocks, security alarms or
lighting on and off systems for street lights.

30
Buzzer

4N
Symbol Component
The buzzer, or 'buzzer' in English, is an electroacoustic transducer that produces a
continuous or intermittent sound or buzz of the same tone. It serves as a mechanism
of signaling or warning, and are used in multiple systems such as in cars
or in household appliances. Initially, this device was based on a system
electromechanical that was similar to an electric bell but without the metal clapper
which imitated the sound of a bell.

Its construction consists of two elements, an electromagnet and a metal sheet of


steel. The buzzer can be connected to special integrated circuits to thus
achieve different tones. When activated, the current passes through the coil
of the electromagnet and produces a variable magnetic field that makes vibrate the
steel plate over the frame.

DC Motor

40
Symbol Component
The direct current (DC) motor is a machine that converts electrical energy
gear in mechanics, causing a rotational movement. This current machine
continua is one of the most versatile. Its easy control of position, stop, and speed.
they have turned it into one of the best options in con- applications.
troll and process automation. For example, you can find them in
the traction of battery-operated toy cars or on the wheels of robots.

SCAN WITH YOUR


SMARTPHONE

SEARCH T05AB
LIKE THIS

VISIT THE OPTION OF

31
Page left blank intentionally

32
5. PROGRAMMING

Programming is a great resource that allows us to create various sequences.


logical steps that will satisfy our needs and those of
our systems. Programming is a whole art that requires great
logical skill and concentration on the part of the programmer.

Concept of programming

It is the process of designing, writing, testing, debugging and


maintain the source code of computer programs
national. The source code is written in a language
of programming. The purpose of programming is
create programs that exhibit a behavior
desired. 5A
The process of writing code requires frequent
I have knowledge in several different areas,
In addition to the mastery of the language to be used, algorithms-
specialized fields and formal logic. Programming involves areas such as analysis and
application design.

To create a program that the computer interprets and executes the instructions.
escritas en él, debe usarse unLenguaje de programación. En sus inicios los compu-
taders only interpreted instructions in a specific language, of the lowest
level known as machine code, being this excessively complicated for
programming. In fact, it only consists of strings of numbers 1 and 0 (Binary system).

To facilitate the work of programming, the first scientists who worked on


the area decided to replace the instructions, sequences of ones and zeros, with
words or letters coming from English, encoding them this way and creating a language
of higher level, known as Assembly or assembly language. For example-
Well, to add you use the letter A from the English word add. In reality it is-
Writing in assembly language is basically the same as doing it in language
machine, but the letters and words are much easier to remember and understand
what sequences of binary numbers.

As the complexity of the tasks performed by computers increased


then, it became necessary to have a simple method for programming.
high-level languages were created. While a task as trivial as multi-
Multiplying two numbers may require a set of instructions in len-
Assembler language, in a high-level language it will be enough with just one.

33
Programming language
A programming language is an artificial language.
designed to express operations that can be
carried out by machines such as computers.
They can be used to create programs that control the
5B physical and logical behavior of a machine, for
express algorithms precisely, or as a way of
human communication.

It is made up of a set of symbols and syntactic and semantic rules that


define their structure and the meaning of their elements and expressions. To the process of
which is written, tested, debugged, compiled, and maintained the code
The source of a computer program is called programming.

Machine language
Machine code is the system of codes
directly interpretable by a micro-circuit
programmable, like the microprocessor of a com-
computer or a microcontroller. This language is
5C composed of a set of instructions that
determine actions to be taken by the machine
No. These instructions are normally executed
this in sequence, with potential flow changes caused by the program itself
the external events.

Machine language works with two voltage levels. These levels, by abstraction,
action, they are symbolized by zero (0) and one (1), which is why machine language only
use these signs. This allows the use of algebra theories
Boolean and binary system in the design of this type of circuits and in
its programming.

Assembly language
Assembly language or assembler is a language of
low-level programming for computers, my-
microcontrollers, and other integrated circuits program
blessings. Implement a symbolic representation of the
5D machine codes. This representation is usually
defined by the hardware manufacturer, and is based on
mnemonic codes that symbolize the steps of
processing (the instructions).

An assembly language is therefore specific to a certain architecture.


of physical (or virtual) computer. This is in contrast to most of
The high-level programming languages that are ideally portable.

34
High-level language
A high-level programming language is characterized by
to express the algorithms in a manner suitable for the
human cognitive ability, instead of ability
executor of the machines. 5E
For high-level languages, certain requirements are needed.
programming knowledge to carry out the sequences
logical instruction circuits. High-level languages
were created so that the average user could
solve a processing problem of
data in an easier and faster way.

Algorithm

An algorithm is a pre-written set of instructions


5F
well-defined, ordered, and finite actions or rules
that allows carrying out an activity through steps
successive ones that do not generate doubts for those who must carry out

this activity. Given an initial state and a


entry, by following the successive steps one arrives at a
final state and a solution is obtained.

Body of an Arduino program


Arduino is programmed in the high-level language C/C++ and generally has the
next components to develop the algorithm:

Structures 5G
Variables

Mathematical, logical and boolean operators

Control structures (Conditionals and loops)

Functions

35
Structures
There are two main functions that every Arduino program must have:

setup() {

5H }
Initial configuration code, it only runs once.

loop() {
}
This function runs after setup(), it keeps running until it
de-energize or disconnect the Arduino.

Variables
It is a piece of data or set of data that changes its value with the execution of the program.

Boolean Enter Character

5I
true or false Integer value Store an ASCII

Booleanencendido=true; intconta=5; charletra=’a’;

These are some types of variables and the most used in this guide. For more types
visit

[Link]/en/Reference/HomePage

Boolean operators
Generally used within the conditional If

5J &&(y)
If (a||b)
(o)
not

Comparison operators
Usually used within the conditional If and on the For and While

equal to (greater than)


5K != (less than or equal)
< (less than) >= (greater than or equal)

If (a==b)

36
Mathematical operators
They apply to the handling of variables, conditionals, and loops

assign remaining
% multiplication 5L
sum division
int value=value+5

Control structures
They are instructions that allow us to make decisions and perform various repetitions.
according to some parameters, among the most important we can highlight:

If
5M
Switch/case
For
While

Conditionals
Ideal for making decisions after evaluating the logical conditions:

If (Yes) Switch/case (Cases)

5N
if (input < 500) switch (var) {
{ case1:
// action A // action A
} else break;
{ case2:
// action B // action B
} break;
default:
// action C
}

Cycles
Ideal for repeating what is found within them

for While
50
for(int a=0; a<10; a++ ) while (var<200) {
{ action to repeat
action to repeat var++;
} }

37
Analogous functions
Ideal for reading and writing analog values

analogRead() analogWrite()—> PWM


5R
Read an analog value from 0 to 1023 Write an analogous value 0 to 255

analogRead(pin) analogWrite(pin, PWM value)

int a = analogRead(A0); analogWrite(9, 134);

EXERCISES

1
Relate the following terms, each letter has three associated terms:

A-Carbon Flow of electrons


Amperio
B–Light emitter Green
LED
C-Language in- Free software
assembler analogWrite()
PWM
D–Digital Open hardware
Button
E–Current Resistance
Instruction
F–Arduino ADD
1KΩ
G–Analog digitalRead()

SCAN WITH YOUR


SMARTPHONE

SEARCH T04AB
LIKE THIS

VISIT THE OPTION OF

39
5S Quick reference for programming
The Arduino program can be divided into three main parts: the
structure, variables (values and constants) and functions.

E setup() Comparison operators


S loop() == (equal to)
T - ! = (not equal to)
+Control structures < (less than)
R - if greater than
U if...else less than or equal to
C for >= (greater than or equal to)
switch case
T
while +Boolean operators
U - do... while -&&(y)
R break - || (o)
A continue -! no
return
goto
Pointer access
remove the reference of the opera-
+Syntax dor
-; (semicolon)
-&reference operator
-{} (keys)
-/ / (single line comment)
(multi-line comment)
Bitwise operators
-&(bit a bit AND)
# define
# include (bitwise OR)
(bitwise XOR)
~ (bit a bit NOT)
+Mathematical operators
- << (to the left BitShift)
-= (assignment operator)
>> (right BitShift)
+ (addition)
- - (subtract)
multiplication
+Compound operators
division + + + (increment)
modulus decrement
(compound addition)
- -= (compound subtraction)
=* (multiplication compound)
(compound division)
&& (bitwise AND)
- | = (bitwise OR operator)

V +Constants +Utilities
A byte -sizeof()
- HIGH | LOW
- int
R - INPUT | OUTPUT +Conversion
word
- true | false char()
I long
- Integer constants byte()
A Floating constants
unsigned long
float int()
B Data types word()
double
L void string - char array long()
E boolean - String - object float()
char array
S

40
F
Digital I/O
pinMode() U
digitalWrite() N
digitalRead() C
Random numbers
randomSeed() I
+Analog I/O random()
analogReference() O
analogRead() N
analogWrite() - PWM E
Bits and Bytes
lowByte() S
+Advanced I/O
highByte()
- tone()
bitRead()
noTone()
bitWrite()
shiftOut()
bitSet()
shiftIn()
bitClear()
pulseIn()
bit()

Time External interruptions


millis() attachInterrupt()
micros() detachInterrupt()
delay()
delayMicroseconds()
+Interruptions
interrupts()
Mathematics noInterrupts()
min()
max() +Communication
abs() Serial
constrain() begin()
map() end()
power() available()
- sqrt() read()
peek()
+Trigonometric flush()
- sin() print()
cos() println()
tangent() write()

L
EEPROM - read and write I
Ethernet - connect to the Internet B
Liquid crystal - LCD control
SD - reading and writing of SD cards
R
Servo - servo motor control E
- SPI - communication via the SPI bus R
- Step by step - motor control
Í
Wire - send and receive TWI/I2C data
A
... and many more visit S

[Link]

41
Blank page left intentionally

42
6. ARDUINO

With the capabilities of Arduino, we only need to have basic notions of


electronics and programming, that is enough to start developing
our projects. Arduino has a large community where there are
it breaks everything developed and is a great window for you to see everything
what can be developed.

Arduino Project
The project started in Ivrea, Italy (the site of the company)
Olivetti computers), in the year 2005 with the aim of creating a
device for students for the integrated control of projects
design and interaction, with the aim of making it more
cheaper than the available prototyping creation systems in
That was then. Starting in May 2011, more than 300,000 units
The Arduino boards have been distributed. The founders Massimo
Banzi and David Cuartielles named the project as Arduino of Ivrea, a prota- 6A
historical nothing of the city. Firstly, 'Arduino' is a masculine term.
Liano, which means 'great friend'.

The Arduino project is a fork (in software engineering, a


Fork is a project that happens when developers tie-
in a legal copy of the source code and they start the development
independent of her, creating a different software work
from the open source Wiring platform. Wiring was created
by Colombian artist and programmer Hernando Barragán
like a master's thesis at the Institute of Design and Interaction
Ivrea, under the supervision of Massimo Banzi and Casey Reas. On the other hand, Wiring
is based on Processing and its integrated development environment created by Casey Reas and
Ben Fry.

Arduino was built around Hernando's Wiring project.


Barragán. Wiring was Hernando's thesis project in the
Ivrea Institute of Design and Interaction. It was conceived to be a
electronic version of Processing that uses our environment
programming and was modeled for the syntax of Processing. It was
supervised by myself and Massimo Banzi, a founder of Ar-
I don't think Arduino would exist without Wiring and I don't think
Wiring would not exist without Processing. And I know that Processing would definitely not exist without Design By
Numbers and John Maeda

1 Interview with Ben Fry and Casey Reas by Shiffman Daniel (Sep 23, 2009)see more

43
Arduino Family
Like any respected family, we have members from the oldest to the youngest.
small ones, we invite you to get to know them:

6B Arduino UNO Arduino Mega2560

Arduino Pro Arduino Fio Arduino Mini

Light and practical Programming Small, ideal


XBee for protoboard

Arduino Bluetooth Arduino Mega ADK Arduino LyliPad

Programming via To connect the For artists and


bluetooth Android manage e-textiles

Arduino Nano Arduino Serial Arduino Leonardo

A little can- The beginning of the pro- The youngest and


roso Arduino project economic

44
Expand Arduino with shields
An Shield is a board that allows expanding functionalities to your Arduino.
with which you can connect motors, or to the cellular network, to a WiFi network, to a network
Ethernet or having an MP3 on the Arduino, among many more just look:
6C
Cell phone Ethernet Proto GPS

XBee WiFi LCD a color USB host

Joystick DC Motors SD Card

SCAN WITH YOUR


SMARTPHONE

SEARCH T01AB
THIS WAY

VISIT THE OPTION OF

45
6D Arduino Uno board and its parts

Front view

2 3

5
6 4
1

8
10

11 9

12

13 14

Auxiliary views

46
D
E
1 USB connector for Type AB cable
S
C
2 Reset Button
R
I
3 Digital I/O and PWM pins P
C
4 Green LED on board is on I
Ó
5 Orange LED connected to pin 13 N

6 ATmega 16U2 in charge of communication with the PC


D
7 LED TX (Transmitter) and RX (Receiver) of serial communication E

8 ICSP port for serial programming P


A
9 ATmega 328 microcontroller, brain of the Arduino R
T
10 16MHz quartz crystal E
S
11 Voltage regulator

12 2.1mm female connector with positive center

13 Voltage and ground pins

14 Entradas análogas

SCAN WITH YOUR


SMARTPHONE

SEARCH T02AB
LIKE THIS

VISIT THE OPTION OF

47
6E Installing drivers

MAC and LINUX


If your computer has a version of Mac as its operating system or a distribution-
LINUX installation, all you need to do is:

1 Connect the Arduino Uno board to the PC

2 Download the software [Link]/en/Main/Software

3 Ready to work and load programs

WINDOWS 7, Vista and XP


If your computer has the Windows operating system in version
7, Vista or XP, you must perform the following sequence of simple steps
steps:

1 Download the software [Link]/en/Main/Softwarefor Windows

2 Unzip the Arduino folder in an easily accessible location

3 Connect the Arduino Uno board to the PC and see this warning. We should not pre-
to occupy

4 Visit Control Panel and then Device Manager, there search


the following option

48
WINDOWS 7, Vista and XP

5 Right-click on Unknown Device and then on the option Update


uninstall driver software.

6
Access the Find driver software option on the device

7 Examine and search the folder of Arduino previously unzipped in the


Step 2. Inside that folder, access the Drivers folder and click Accept.

8 Once we search for the Drivers folder, we click Next.

49
We received the confirmation of the assigned COM port, this port number
9
COM is very important to keep in mind when programming.

SCAN WITH YOUR


SMARTPHONE

SEARCH T07AB
LIKE THIS

VISIT THE OPTION OF

50
Getting to know Arduino software

To run the Arduino program, enter


go to the Arduino folder and there look for
We click on the Arduino icon and double click it.
click

6F

Area to write the code

Software message zone


Errors and actions

1 Puerto COM

51
2 Select the board to work on

3 Serial console

Loading my first program


By the end of this exercise, you will have the ability to upload programs to your board.
Arduino. To do this, open the Arduino software and follow the instructions in the si-
next image.

6G
1

52
Loading my first program
Before proceeding to the next step, make sure to configure it correctly.
ta:
A–Puerto COM, check Step 1 of section 6F, remember that the value of the
We obtained the COM port in Step 9 of section 6E.
B-Board, review Step 2 of section 6F, remember that for this case the
Arduino UNO board

The blinking program that you just uploaded in electronics is


3 Hello world, it consists of turning a LED on and off at intervals of
one second. The LED that turns on and off is part 5 according to section 6 Do the
marked with the letter L according to the image below. Now we can give you the
Welcome to the world of Arduino :D!

53
Exercise
Based on the example loaded in the previous section, we now propose that you modify-
fix the program a little, for this in the two lines of code where it says:
delay(1000);
Change the value of 1000 to 2000 and reload the program to your Arduino board.
One, what do you observe?

54
7. BASIC KIT

It is the central resource of this guide, we suggest you get to know it.
so that you have proper management of its components.

Description
The Robotics Store brings the Basic Kit
Arduino includes a careful selection
selection of the best components to get started
in the world of Arduino. It is a tool
designed for beginners that includes
7A
with everything necessary to develop progra-
more that contribute to learning and management
of Arduino.

Distribution of the kit

BASIC KIT 7 6

2 5 7B
1

3 4

1 3 5
1 xArduino Uno 5 x 5mm LEDs 5 xResistance 220Ω

1 xProtoboard 1 xLed multicolor 5 x 1KΩ Resistance

1 x Piezoelectric 5 x 10KΩ Resistors


2 2xTransistor 2N3904
1 x Photo cell 4
6
1 x 10K Potentiometer 1 x 9V Alkaline Battery
1 magnet
1 x Reed switch 1 x Battery brooch
1 x DC Motor
2 x NO Push Buttons 1 x 2.1mm Connector

7
1 x USB Type AB Cable

10 x Fast connectors MM

55
Photos

7C

IN YOUR KIT BOX

56
8. FRITZING

Fritzing is software for designing setups on a breadboard and from there


from it generate the layout and the PCB (Printed Circuit), so easy :)

Software
Fritzing allows designers, artists, researchers, and enthusiasts
document their Arduino-based prototypes and create circuit diagrams
printed circuits for their subsequent manufacturing.

8A

Prototyping board

8B

57
View scheme

8C

Vista PCB—Printed circuit

8D

58
MASTER EXERCISE

1
In the following exercise, we want you to strengthen your
mounting capabilities in Fritzing, it is an exercise that
requires you to put your abilities to the test
recognition of electronic assemblies and wiring
between the Arduino and a protoboard, it is a summary
practical from the previous chapters. To develop it
we recommend that you work alongside the software and
from the image presented below. You can find the software
en:

[Link]/download/ 8E

DIY

59
9. TUTORIALS
These tutorials are designed with practical exercises that allow for
understand the concept and is constantly verifying what has been learned
through questions. Finally, exercises are proposed that involve ca-
sos of real life.

T0 Learn what the tutorials are like

A
E

F
C

G
D

A Tutorial Title

B What you need to know and what you will learn

C The materials you need

D Closer to you, multimedia content

E Assembly plan

F Assembly diagram

60
G Test your learning

H Programming code
step by step

H
I Very useful tips

J Applied exercises

K Express your ideas

61
T1 Hello world—flashing LED

What do I learn? Prior knowledge

Activate a digital output Digital signal

Turn on a LED ON/OFF digitalWrite() function

Time a output signal Polarity of an LED

Syntax of a program in Connection of the Ardui board


Arduino no to the computer

Materials

1 1

Arduino UNO Green LED

USB Type AB Cable

SCAN WITH YOUR


SMARTPHONE

SEARCH
THIS WAY

VISIT THE OPTION OF

62
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value What does this do? 3—Complete R
of this resistance? function? E
G
digitalRead()
U
_______________ ?
I = ___ N
_____Ω
_______________ R T
_____KΩ
A

63
C /*
Ó -----------------------------------
D Hello World
I -----------------------------------
G Turn on a LED for one second and turn it off for the same amount of time.
0 */

//------------------------------------
D
Main function
E
//------------------------------------
void setup() Executed every time the Arduino starts
{
P
pinMode(13,OUTPUT);// Initializes pin 13 as an output
R
}
O
G
R
//------------------------------------
A
Cyclic function
M
//------------------------------------
A
voidloop() This function keeps running
C
{ when the Arduino is powered
I
digitalWrite(13,HIGH);// Turns on the LED
Ó
delay(1000); Temporizes for a second (1s = 1000ms)
N
digitalWrite(13,LOW);// Turn off the LED
delay(1000); // Waits for one second (1s = 1000ms)
}

End of the program

T 1-The // in programming is used to make comments, it is very useful for that


I Can you explain something about the syntax of a line of code? An example of it.
P use
S
digitalWrite(13, LOW);// Turn off the LED

2–Digital signals (On or off) are very present in all


systems, and many sensors work on this principle, we invite you to learn more
some:

PIR Sensor SHARP optical sensor


Detects movement Detects the presence of any
object in a range of 5cm

64
EXERCISES

1
Starting from the programming code explained above, we want that
a LED lights up intermittently in the following manner:

A) 3 seconds on and 3 seconds off

B) 200 milliseconds on and 500 milliseconds off

Tip: 1s = 1000ms

2
The automation company NRJ Inc. hires you to do an assembly of
a blinking LED on an Arduino UNO board, with the only requirement that
the LED must be located on Pin 5, they kindly provided you with
Make the outline, your task is:

A) Carry out the assembly and the respective programming for 2 seconds on.
1 second off

3 A strobe is a light bulb that turns on and off very quickly,


widely used at parties, your mission is to create your strober
homemade with an LED, with the same circuit mounted on this
tutorial.

MY NOTEBOOK

65
T2 Turn on an LED with a button

What do I learn? Prior knowledge

Wire a circuit Digital signal

If/else conditional digitalWrite() function and


digitalRead()
State of a button
Voltage divider
Read a digital entry and
write a digital output Conditional and operators of
comparison

Materials

1
1
1
Yellow LED

Arduino UNO 1
Breadboard

Push button
1

1 4

USB Type AB Cable


1K resistor MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T10AB
LIKE THIS

VISIT THE OPTION OF

66
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value? What is this doing? 3—An example of R
of this resistance? function? a high-level language E
level G
digitalWrite()
U
_______________ _______________ N
_____Ω
_____KΩ _______________ T
A

67
C /*
-----------------------------------
Ó Turn on LED with a push button
-----------------------------------
D
I Press a button and while it is held down
a LED lights up
G
Mechatronics Things and Robotics Store
0
*/

//------------------------------------
D //Declare input and output ports
//------------------------------------
E intpulsador=2; //Pin where the button is located, input
intled=13; //Pin where the LED is located, output

//------------------------------------
P //Main function
//------------------------------------
R void setup() // Executes every time the Arduino starts
{
O pinMode(button, INPUT); // Set the button as an input
G set pin mode for led to OUTPUT;
Configure the LED as an output
}
R
A //------------------------------------
//Cyclic function
M //------------------------------------
A voidloop() // This function keeps running
{ when the Arduino is powered on
C
Conditional to know the state of the button
I if(digitalRead(button)==HIGH)
{
Ó Button pressed
N digitalWrite(led,HIGH);//Turns on the LED
}
else
{
// Normally open push button not pressed
digitalWrite(led, LOW);//Turn off the LED
}
}
//End program

T 1–When you are programming in the Arduino Software, many things that
I you write are reserved words of the language, all reserved words the
P You can find them in the 5S section, when you write them they are placed in a different color.

S rent, this is a trick to know that it is okay, for example:

All programming instructions for Arduino are found


completely documented with clear examples of how they are used, you
we invite you to visit:[Link]/en/Reference/HomePage

68
EXERCISES

1
The French multinational Flante, expert in ma-
industrial machinery has hired you to auto-
you are a machine for cutting paper. The condi-
the main action is that the machine operator
when making the cut always keep
both hands occupied, this is a rule of follow-
Industrial safety measures to prevent accidents. The operator must press both buttons.
you do one with each hand and the cutting blade must go down and make the cut. The
The following setup simulates the control of the machine, the two buttons (S1 and S2)
and the red LED simulates the cutting blade.

S1 S2

2 Your father wants you to create an LED lighting system for


the stairs of the house. The condition is that if you are upstairs and
if you press S1 or if you are down and press S2 the Red LED lights up and
When you stop pressing, it turns off. As a mounting guide, take the ima-
anterior gen.

MY NOTEBOOK

69
T3 Serial reading of a digital input

What do I learn? Prior knowledge

Manage a digital entry Digital signal

View data on the screen of digitalRead() function and Se-


computer [Link]()

Serial console Serial console option,


ver6F(step 3)
Read a digital entry and
write to serial console

Materials

1
1

Arduino UNO
Button Breadboard

1
1

4
1K Resistance
USB Type AB Cable
MM connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T11AB
LIKE THIS

VISIT THE OPTION OF

70
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value? What does this do? 3—This symbol to R
from this resistance? function? what corresponds E
G
[Link]()
U
_______________ N
_____Ω
_____KΩ _______________ _______________ T
A

71
C /*
--------------------------------------
Ó Serial reading of a digital input
--------------------------------------
D Read a digital entry and display on the screen of
I computer (serial console) the state of the button
when oppressed
G Mechatronics Things and Robotics Store
0 */

//------------------------------------
//Declare input and output ports
D //------------------------------------
intboton=2; Pin where the button is located, input
E
//------------------------------------
//Main function
//------------------------------------
voidsetup() // Executes every time the Arduino starts
{
P Configuration
pinMode(button, INPUT); //Set the button as an input
R [Link](9600); Start serial communication
}
O
G //------------------------------------
//Funcion ciclicla
R //------------------------------------
voidloop()// This function keeps running
A { when the Arduino is powered
M Store in an integer variable the value of button 0 or 1
intestado=digitalRead(boton);
A
//Conditional to know the state of the button
C if(state==1)
{
I Pulsed
Pressed //Prints to the serial console
Ó } Pressed
else
N {
Not pressed
[Link]("NO Pressed"); //Prints to the serial console
} NO Pressed
delay(100);//Delay for data visualization in the console
}
//End program

T 1–Binary encoding is very important for transmitting data between 0 000


I devices, are long chains of 0s and 1s, for example
1 001
P 00011101010101 this could be a message that contains information
regarding a personal code to access a building. The numbers 2 010
S
In base 10, they can be represented as binary values: 3 011

4 100
To remember
5 101

6 110

7 111
To read a digital signal use: digitalRead(pinNumber);

To write a digital signal use: digitalWrite(pinNumber, value);

A digital output or input is always HIGH or LOW

72
EXERCISES

1
A soda company has a system with two
sensors, one of them indicates if the bottle is full-
with the liquid and the other sensor indicates if the bottle
it already has the lid. For this case, we will simulate both.
sensors through two buttons (S1 and S2).

The routine is described this way: if the bottle


fill in appropriately (S1 must be activated and
show on console - 'Full soda') then if it has the cap on (it
You must activate S2 and display "Capped soda" on the console at the end of the process.
a LED should be lit to indicate that the process finished successfully and additionally, it
It must display a message on the console - 'Well packed soda'. Remember
First, S1 must be activated and then S2 for the process to be valid.

Some moderate Christmas lights


the following are: mien-
while S1 is pressed
an integer variable initializes
S1 S2
from 0 it starts to incre-
subtracting 20 by 20, when released
S1 the variable stops increasing
to mention itself, when S2 is pressed
the value of the variable is
must load to a -Hello

World of the LED, this means that the LED goes


to be intermittent at equal time intervals to the value
from the variable. You should display the
valor de la variable. Para que puedas volver la variable a 0
and you can do another intermittent routine, set the condition that S1 and S2 are
press the time, with that the integer variable must return to 0.

MY NOTEBOOK

73
T4 Serial reading of an analog input

What do I learn? Prior knowledge

Handling an analog input Analog signal

View data on the screen of the analogRead() function and


computer [Link]()

Multiple states of a potentiometer Serial console option,


cylinder ver6F(step 3)

Read a similar entry

Materials

1
1

1
Arduino UNO
Breadboard

1
10K potentiometer
3

USB Type AB Cable


MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T12AB
LIKE THIS

VISIT THE OPTION OF

74
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value? 2—What does this do? 3—This symbol to R
of this resistance? function? what corresponds E
G
analogRead()
U
_______________ N
_____Ω _______________
_____KΩ _______________ T
A

75
C /*
--------------------------------------
Ó Serial reading of analog input
D --------------------------------------
I Read an analogous entry and display it on the screen.
G computer (serial console) the value after turning
the potentiometer
0
Mechatronics Things and Robotics Store

*/
D
E //------------------------------------
Main function
//------------------------------------
void setup() // Executes every time the Arduino starts
{
P [Link](9600);//Starts serial communication
R }

O //------------------------------------
//Cyclic function
G //------------------------------------
R voidloop()// This function keeps running
{ When the Arduino is powered on
A
M Store in an integer variable the value of the potentiometer 0 to 1024
intvalor=analogRead(A0);
A
C //Prints the value of the variable to the serial console
[Link](value);
I
Ó Delay for data display in the console
delay(100);
N
}

//End program

T 1–We invite you to learn about some types of potentiometers


I
P
S SoftPot Trimmer Encoder RGB
Touch system High precision Continuous turn

2–To remember

- Para leer una señal análoga usa:analogRead(numeroPin);


To write an analog PWM signal use: analogWrite(pinNumber, value);
An analogous entry goes from 0 to 1023

An analog PWM output ranges from 0 to 255

76
EXERCISES

1 This challenge is simple, but it will give you an idea of how


doing great things by writing a few lines of
code. As you well know, reading a signal
an analogue gives you a value from 0 to 1023 (if you have any
Doubt just check the code of the previous page.

The challenge of this exercise consists of showing by the


serial console a number between 0 and 10, this number
it must change when you move the potentiometer. The assembly of this exercise
use the same connection scheme as the one shown on page 75. Suggest-
Reference... Check the function map()

2 Think of a secret number from 0 to 1023 and keep it in a


integer variable, make a program so that your friend must mo-
see the potentiometer, if the number it is generating
(show in serial console the value of the potentiometer reading)
metro) when turning the potentiometer it is 10 numbers above or
10 numbers below the number you thought of and confirm with
the button S1 that is
it is the number, the program-
you must show for
console - You guessed the
number ‖ otherwise
Try again.
S1
This case could be a
example so that it
applies to a Box of
security, for what
you save a lot of money ;)

MY NOTEBOOK

77
T5 Serial writing

What do I learn? Prior knowledge

Input through console (keyboard) Digital signal

Boolean variables digitalWrite() function and


[Link]()
LED status
Configuration of a comu-
serial communication
Digital serial writing
Polarity of an LED

Materials

1 1

Arduino UNO Green LED

USB Type AB Cable

SCAN WITH YOUR


SMARTPHONE

SEARCH T13AB
LIKE THIS

VISIT THE OPTION OF

78
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value What is this doing? 3—Name 4 types R
of this resistance? function? of variables E
G
[Link]() a._______
U
_______________ b._______ N
_____Ω
_______________ c._______ T
_____KΩ
d._______ A

79
C /*
--------------------------------------
Ó Serial writing
--------------------------------------
D It consists of writing on the computer screen (serial console)
I a predetermined letter, the first time it is written is
a LED lights up, if it is rewritten for the second time
G the LED turns off.

0 Mechatronics Things and Robotics Store


*/

//--------------------------------------------------
D //Declares input and output ports and variables
//--------------------------------------------------
E intled=13; //Pin where the LED is located, output
charleer //Variable where the lyrics are stored
boolean isOn=false;//LED state the first time, off

//------------------------------------
P Main function
//------------------------------------
R void setup() // Runs every time the Arduino starts
{
O [Link](9600); Start serial communication
pinMode(led, OUTPUT);//Set the LED as an output
G }
R
//------------------------------------
A //Cyclic function
//------------------------------------
M voidloop()// This function keeps running
{ when the Arduino is powered
A
Save the value of the serial console in a variable
C read=[Link]();
I If it is the letter 'a' and the LED is off
if ((read == 'a') && (turnedOn == false))
Ó {
digitalWrite(led,HIGH);// Turns on the LED
N prendido=true; Update the LED status
}
If it is the letter 'a' and the LED is also on
else if( (read=='a')&&(turnedOn==true) )
{
digitalWrite(led,LOW);// Turn off the LED
prendido=false; Update the LED status
}
}
//End program

T 1–Boolean tables are very useful for understanding the logic of programs.
I Do you know what the AND boolean table is?&&),OR(||)yNOT(!)?
P
S

80
EXERCISES

Luminous Notices S.A. has hired you to create a program


1
that has the characteristic of receiving data, because the idea is that the
light warning is located on the 130th floor of the Bulli Building and you can.
control from the 1st floor, so for every letter you write to him
keyboard to the serial console the program must perform a certain routine
with three LEDs, if you write to it:
Letter A: Turns on the three LEDs
Letter B: Turns on LED1 for one second and turns it off, then turns on LED2 for one second
turns it off and finally turns on LED3 for one second and turns it off, and it goes back
Let's get started. This routine generates a feeling of movement.
Letter C: Turn off the three LEDs

LED1 LED2 LED3

2 Your grandpa has a crop of big and green lettuces.


this crop has 3 water sprinklers and your grandpa wants
turn on these sprinklers from your computer just by typing-
Enter some values via keyboard, the sprinklers have a status.
digital (Value 0 is off and value 1 is on). You must perform
to create a program that reads a string of three values, for this exercise the
We are going to simulate the sprinklers with three LEDs 1, 2, and 3, for example:

If your grandpa writes000: All water sprinklers must be off


If your grandpa writes101: Sprinkler 1 and 3 turn on but the two must be off
If your grandpa writes001: The sprinkler 1 and 2 turn off but the three should be on.

MY NOTEBOOK

81
T6 Turn on an LED by PWM

What do I learn? Prior knowledge

Turn on an LED in a way PWM


proportional
analogWrite() function
Appropriate the concept of PWM
Polarity of an LED
Write an analogous output
Increase and manipulate
If/else with logical operators variables

Materials

1
1
1

Yellow LED
Arduino UNO
Breadboard

1
1

USB Type AB Cable Resistance 220Ω


MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T14AB
LIKE THIS

VISIT THE OPTION OF

82
P
L
A
N
O

E
S
Q
U
E
M
A

P
What is the value? What does this do? 3—What are you running to-R
of this resistance? function? put these ope- E
timers G
analogWrite()
&&_______ U
_______________ N
_____Ω ||_______
_____KΩ _______________ T
==_______
A
!=_______

83
C /*
---------------------------------------------
Ó Turn on/Off an LED proportionally
---------------------------------------------
D Program that proportionally turns on a LED when
I it reaches its maximum brightness and starts to fade
proportionally.
G Mechatronics Stuff and Robotics Store
0 */

//--------------------------------------------------
//Declare input and output ports and variables
D //--------------------------------------------------
intbrillo=0; //Brightness variable starts at 0
E intvariacion=5; Increment variable set to 5
intled=9; //Pin where the LED is located, output

//------------------------------------
//Main function
P //------------------------------------
voidsetup()// Se ejecuta cada vez que el Arduino se inicia
R {
pinMode(led, OUTPUT);//Set the LED as an output
O }
G
//------------------------------------
R Cyclic function
//------------------------------------
A voidloop()// This function keeps executing
{ when the Arduino is powered on
M
Analog writing (PWM) to the LED, I write the brightness value
A analogWrite(led, brightness);
C I increase the brightness variable by 5 each time.
brightness=brightness+variation;
I
// Note: PWM ----> 0 - 255
Ó
If the brightness is 0 or 255
N if(brightness==0||brightness==255)
variation = -variation; // The variation becomes negative
delay(30);//Time to increase brightness
}

//End of program

T 1–These elements receive PWM signals and are used for:


I
P
S
Water pump Micromotor
Vary the speed of Vary the speed of
pumping turn

PWM

LED Servo motor


Vary the intensity of Vary the position in
light degrees

84
EXERCISES

1 Your mom wants to have adjustable intensity lights in the living room.
from your home, wants low light for the moments when the family
shares to maintain harmony but requires quite a bit of light
when she makes her fabrics, she wants to have control over the intensity-
control the light through a potentiometer and the LED bulb will
light up according to what she graduated. Your task is to carry out the
program that reads an analog input from a potentiometer (0—1023) and
adjust the PWM value (0-255) of an LED, remember to scale the value...map()

2 A novel bread oven is about to hit the market. This


the oven is different from all the others because you can adjust the
temperature and baking time from the computer. Your
The task is to create a program that reads temperature from the Serial Console.
temperature in °C (0-255) then separated by a comma (,) and continues-
baking time comes in seconds (1-10). The value of the
the temperature will be the PWM that will be adjusted to the LED and the time-
baking time is the time during which the LED is kept
turned on at that temperature. Use the diagram from page 83 as a setup, for example:

The LED turns on with a PWM of 180 for 3 seconds.


The LED turns on with a PWM of 50 for 2 seconds.
9.5 The LED turns on with a PWM of 9 for 9 seconds.

MY NOTEBOOK

85
T7 ON/OFF control with potentiometer

What do I learn? Prior knowledge

Digital output If/else

Control ON/OFF digitalWrite() function and


analogRead()
Comparison
Value of an analog input
Conditional based on a ga
integer value of an entry
analog Conditional and operators of
comparison

Materials

1
Green LED 1

1
Arduino UNO
Breadboard

1
10K potentiometer

1
3

USB Type AB Cable

Resistor 220Ω MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T15AB
LIKE THIS

VISIT THE OPTION OF

86
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value 2—What is it for? 3—This symbol a R
of this resistance? the operator? what corresponds E
G
++ U
_______________ N
_____Ω
_____KΩ _______________ _______________ T
A

87
C /*
---------------------------------------------
Ó ON/OFF control with potentiometer
---------------------------------------------
D
I Programa que enciende un LED cuando el valor de la entrada
analog controlled by the potentiometer is at a certain value,
G when this value changes the LED turns off, it is a system with
control ON/OFF
0
Mechatronics Stuff and Robotics Store
*/
D //------------------------------------
Main function
E //------------------------------------
void setup() // Runs every time the Arduino starts
{
[Link](9600);//Starts serial communication
pinMode(13, OUTPUT); // Set pin 13 as an output
P }
R //------------------------------------
O Cyclic function
//------------------------------------
G void loop() // This function keeps executing
{ when the Arduino is powered on
R
Save the value of the analog reading in a variable
A intvalor=analogRead(A0);
M [Link](value);//Prints the value to the console
A If the value is greater than or equal to 500
C if(value>=500)
{
I digitalWrite(13,HIGH);//Turns on the LED on pin 13
Ó }
If the value is less than 500
N else
{
digitalWrite(13, LOW);//Turn off the LED on pin 13
}
delay(100);//Delay of 100ms to see the console data
}
//End program

T
I
You must be very careful when
P
moment when your Arduino board is
S energized, if you look at the palca by the
the bottom has all its points
air welding equipment, if you have it
feed the plate and place it on top
from a metallic surface, for example-
I set a table, it is possible that the plate
it gets damaged because it shorts out. If you are going to

working with the Arduino board is recommended


we work on surfaces of
insulating materials such as those are
synthetic, wood or glass. This is a
advice to take care of your plate.

88
EXERCISES

1 A tuning car has neon lights on the bottom,


this is the feeling of the fair. The driver controls the lights
(three LEDs) through a potentiometer next to the
gear lever, he has three options for lights
according to the reading value of the potentiometer that goes from 0 to
1023

0 - 350 Intermittency of the 3 LEDs at 100ms


351 - 700 Intermittence of the 3 LEDs at 500ms
Intermittence of the 3 LEDs at 1000ms

2 The sound system has a knob for you to turn up the


volume and also has 5 luminous indicators (LED)
arranged one after another in a straight line (just as you see it in
the assembly) as the value of the potentiometer goes
increasing by turning it, LED1 starts to light up, then the
LED2, then LED3 and so on up to LED5. If you reach the value of 1023 all the LEDs should
to be turned on, and if you start turning the potentiometer in the opposite direction, they will disappear.
turning off the LEDs one after another in the reverse order in which they were turned on, in the end if you are in
the value 0 all the LEDs must be off. Generate a feeling of motion.

LED1 LED2 LED3 LED4 LED5

89
T8 Control of an LED with a photocell

What do I learn? Previous knowledge

Writing by PWM on an LED Analog signal

Read a similar entry by analogWrite() function and


middle of a photocell analogRead()

Working with a variable PWM

Adjust an analog input to Print data to console


an analog output serial

Materials

1 1

1
Green LED
Arduino UNO

1 1 Breadboard

Photocell
USB Type AB Cable

1 5
1

10K Resistance 1K resistance MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T16AB
THIS WAY

VISIT THE OPTION OF

90
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value 2—The letter A 3—This symbol a R
of this resistance? keeps in a va- what corresponds E
variable of type: G
U
_______________ N
_____Ω
_____KΩ
T
A
_______________

91
C /*
---------------------------------------------
Ó LED intensity control
---------------------------------------------
D Program that lights up an LED proportionally from
I according to the amount of light that strikes a
photoelectric cell
G Mechatronics Things and Robotics Store
0 */
//------------------------------------
//Main function
//------------------------------------
void setup() // Runs every time the Arduino starts
D {
[Link](9600);//Starts serial communication
E pinMode(9,OUTPUT);//Configure pin 9 as a PWM output
}
//------------------------------------
//Cyclic function
//------------------------------------
P voidloop()// This function keeps running
{ when the Arduino is powered on
R
Store the value of the analog reading in a variable
O photoelectric cell
intfoto=analogRead(A0);
G
Check the maximum value and perform a conversion
R intconversion=780-foto;
A //Conditional to establish an absolute value
if(conversion<0)
M conversion = conversion * -1; // Multiply by -1 because it is negative

A Print the data of the analog reading value of the photodetector


Photo :
C [Link](photo);
[Link]("" );
I
//Print conversion value data
Ó [Link]("Conv : ");
[Link](conversion);
N [Link]("");
Analog writing of PWM in the LED according to the conversion
analogWrite(9, conversion);
delay(100);//Delay for data in the console
}
//End program

T 1–Think for a moment about where you can find a photocell, these are
I some examples:
P
S
Calculator Digital camera
Charge battery and turn off Check if there is a need
of the automatic dad with flash photo

Light meter Public lighting


Measures an amount of Turn on the light when
light and it is given in lux (lx) the darkness arrives

92
EXERCISES

We propose that you create a sensor to measure the light radiated by a body.
1
bright. We are going to have two teams, A and B. Team A is going to have a
LED that varies its brightness according to the position of a potentiometer (See
T6) y en el equipo B va estar comandado por una fotocelda. La idea es que
bend the LED and the photoresistor at 90°, place them as close together as possible and the
you face each other, as if both were going to look at each other head-on. You must show through the serial console-
Read the light of the photocell, this reading should be in percentage from 0% to 100%. A
Light concentration 57%

2 The beautiful biologist María Paula ;) is in charge of taking care of


the great Herbarium of Santa Monica CA where it is preserved
various plants. Bilumetium is a type of rose that requires-
at an early age lighting of the type lit-
on/off, when its light sensor is malfunctioning
At 600 the light must be turned on (LED1), how
When the plant is adult, it requires light.
proportional nation, as the light begins to dim
it gradually lights up (LED2). Using the button S1
the young plant program is activated and through the S2 button
the corresponding program for the adult plant is activated.

LED 1

LED 2

Light sensor
S1 S2

93
T9 Pulse counter

What do I learn? Prior knowledge

Increase a variable Digital signal

Condicional If/else anidado digitalWrite() function and


digitalRead()
Button debounce
Print data to console
Read a digital entry and
write a digital output to Declare integer variables
certain condition

Materials

1
1
1
Yellow LED

Arduino UNO 1
Breadboard

Button
1

1 4

USB Type AB Cable


1K Resistor MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T17AB
LIKE THIS

VISIT THE OPTION OF

94
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value 2—What are the 3—This symbol a R
of this resistance? states of a what corresponds E
boolean variable? G
U
a._____________ N
_____Ω _________
_____KΩ b._____________ T
A

95
C /*
---------------------------------------------
Ó Pulse counter
---------------------------------------------
D Program that displays the number on the screen (serial console)
I the times the button has been pressed, an action is performed
process that lights up according to the number of pulses
G a LED,

0 Mechatronics Things and Robotics Store


*/
//--------------------------------------------------
//Declare input and output ports and variables
D //--------------------------------------------------
intconta=0;//Variable para guardar el conteo de los pulsos
E
//------------------------------------
Main function
//------------------------------------
void setup() // Executes every time the Arduino starts
{
P [Link](9600);//Inicia comunicación serial
pinMode(2, INPUT); //Set pin 2 as an input, button
R pinMode(13,OUTPUT);//Configures pin 13 as an output, LED
}
O
//------------------------------------
G Cyclic function
//------------------------------------
R voidloop()// This function keeps executing
{ when the Arduino is powered on
A
If the button is pressed
M if(digitalRead(2)==HIGH)
{
A If the button is not pressed, falling edge
if(digitalRead(2)==LOW)
C {
count++; Increment the counter
I [Link](conta);//Prints the value to the console
delay(100);// Delay
Ó }
}
N
If the value of the counter is 5
if(count==5)
{
digitalWrite(13,HIGH);//Turn on the LED
}
If the value of the counter is 8
if(count==8)
{
digitalWrite(13,LOW);// Turn off the LED
}
}
//End program

T 1–Arduino has a large learning community and to share various pre-


I questions, in the official forum you can find various topics with a large amount of
P answers:
S

[Link]/forum

96
EXERCISES

1 For the next party, DJ Lui Lote has hired you to


incorporates a truly fantastic light show, for this he has
a button 1 (B1) that can be pressed many times, the
the number of times he presses is the number of times they will
turn on and off the lights at an interval of 1s. A button 2 is used
(B2) to confirm the routine. Once I finish doing the routine the
the system must be ready to give many more pulses and see another
different routine.

B1 B2

2 DJ Lui Lote from exercise 1 returned recharged with


new ideas for your Show. Now it has three
different lighting zones for your dance floor,
on his DJ console he has a button to give a closure
to number of pulses and then through the Serial Console the
say which lighting zone those are assigned to
pulses at intervals of 1s. The words that it receives the
Serial Console are: zone1 zone2 zone3

zone1 zona2 zona3

Button

97
T10 Magnetic switch for a visual alarm

What do I learn? Previous knowledge

For loop Digital signal

If/else conditional digitalWrite() function and


digitalRead()
Reed switch state
Parameters of a for loop
Read a digital entry and
to write a digital output Intermittence of an LED

Materials

1
1
1
Green LED

Arduino UNO 1
Breadboard

Reed switch
1

1 4

USB Type AB Cable


1K resistor MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T18AB
THIS WAY

VISIT THE OPTION OF

98
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value 2—What does it receive the 3—This symbol to R
of this resistance? functiondelay()? what corresponds E
G
U
_______________ N
_____Ω
_____KΩ ____________ T
A

99
C /*
---------------------------------------------
Ó Magnetic switch - Thief in the house
---------------------------------------------
D Program that generates a visual alarm with an LED
I from a magnetic field generated from a
reed switch.
G Mechatronics Stuff and Robotics Store
0 */
//--------------------------------------------------
//Declare input and output ports and variables
//--------------------------------------------------
D
intcontacto=2;//Pin asignado al reed switch
E intled=13; //Assigned pin to the LED
//------------------------------------
//Main function
//------------------------------------
void setup() // Executes every time the Arduino starts
P {
pinMode(contacto, INPUT);//The reed switch as an input
R pinMode(led, OUTPUT); The LED as an output
O }
G //------------------------------------
//Circular function
R //------------------------------------
voidloop()// This function keeps running
A { when the Arduino is powered on
M If the magnet approaches the reed switch
if(digitalRead(contact)==LOW){
A
//For loop that goes from 0 to 50, the counter is
C in variable a, it repeats while a is
less than 50
I for(int a=0; a<50; a++) {
Ó digitalWrite(led,HIGH);//Turns on the LED
delay(50);//Time
N digitalWrite(led, LOW);//Turn off the LED
delay(50);//Time
}
If the magnet is far from the reed switch
else {
digitalWrite(led,LOW);//Keeps the LED off
}//End of if

}
End of the program

T 1–These devices will allow you to develop security-oriented applications.


I from an enclosure, in the style of a burglar alarm or recognition systems
P biometric parameters (fingerprint, iris, voice or face)
S
Color camera Vibration sensor
Capture at a resolu- Detects vibrations in
VGA connection horizontal surfaces

PIR MEMS Microphone


Sensor to detect Supports a high range
movement of noise

100
EXERCISES

1 A house requires an alarm system, for this exercise you


proponemos que emulemos una. Cuando todos salen de la casa la
the last person to leave is in charge of activating the alarm via a
4-digit number, at that moment the system begins to receive
information about the magnetic detectors (reed switch) located in
at every window and at every door. The alarm should go off when a
the magnetic field alters the state of the reed switch when the alarm
it activates, it starts emitting a sound and also generates a visual alarm, the only
The way to deactivate the alarm is through a 4-digit numeric code that must be
different from the activation code, the steps are described below:

A - A 4-digit integer is received via serial console; if this number is equal to


saved by the system the alarm system is activated, for this it must be displayed by
console―Alarm activated
B–If the Reed switch detects any magnetic field, the serial console must display
Strange presence, system triggered
C–As the alarm went off, the buzzer must be turned on to generate sound.
it (is managed as a digital output) and also the yellow and red LED
it must alternate on/off and emulate the movements of a siren
bomberosa intervals of 1s.
To deactivate the alarm, a numeric code must be entered.
four-digit integer must be correct show on console serial - Alarm deactivated
Contrary to step C, it must be repeated as long as the correct code is not entered.

Siren
Buzzer

Reed

MY NOTEBOOK

101
T11 RGB LED supported by color table

What do I learn? Previous knowledge

Manage the color code Digital signal


RGB
analogWrite() function
Use of a function
Common anode LED
PWM with three outputs
Structure of a program
Manipulate a variable in Arduino

Materials

1 1 1

Arduino UNO
LED RGB Breadboard

1 3 5

USB Type AB Cable


Resistance 220 MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T19AB
LIKE THIS

VISIT THE OPTION OF

102
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value? 2—The word 'pulse' 3—This symbol to R
of this resistance? it should be kept in what corresponds E
a variable of type: G
U
_____Ω _______________ ____________ N
_____KΩ
T
A

103
C /*
---------------------------------------------
Ó LED RGB - Color Table
---------------------------------------------
D Program that makes use of a function called
I color to generate various shades in
an RGB LED
G Mechatronics Stuff and Robotics Store
0 */
//--------------------------------------------------
//Declare input and output ports and variables
//--------------------------------------------------
D intledRojo=9;//Declara Pin LED Rojo
intledVerde=10;//Declara Pin LED Verde
E intledAzul=11;//Declara Pin LED Azul
//------------------------------------
//Main function
//------------------------------------
void setup() // Executes every time the Arduino starts
P {
pinMode(ledRojo,OUTPUT);//El LED Rojo como una salida
R pinMode(ledVerde, OUTPUT);//The Green LED as an output
pinMode(ledAzul,OUTPUT);//The Blue LED as an output
O }
G //------------------------------------
//Cyclic function
R //------------------------------------
voidloop()// This function keeps running
A { when the Arduino is powered on
M Call to the Color function that receives
1st position: Red Intensity
A 2nd position: Green Intensity
3rd position: Blue Intensity
C
color(255,0,0); Red
I delay(1000);
Ó color(0,255,0); Green
delay(1000);
N
color(0,0,255); Blue
delay(1000);
color(255,255,255);//White
delay(1000);
color(255,0,255);//Magenta
delay(1000);
color(255,128,0);//Naranja
delay(1000);
}
//------------------------------------
//Color function
//------------------------------------
void color(int red, int green, int blue) {
PWM writing of the Red color
analogWrite(ledRed, 255-red);
PWM writing of the Green color
analogWrite(ledVerde,255-verde);
Writing of PWM for the Blue color
analogWrite(blueLed, 255 - blue);
}
End of program

T These two devices can generate up to a billion different colors.


I
P MegaBrite ShiftBrite
S

104
EXERCISES

1 The lighting of the reception of the Mancherie Hotel is something special because of
according to the mood of the owner Mr. Martin, the light should be configured in
a RGB scale. The light operator is very skilled as he is in charge of receiving
the colors desired by Mr. Martin, so the worker is responsible for writing
through Serial Console a RGB value separated by commas (,). So you must develop
a program that takes this information and applies it to an RGB LED, takes as
Outline page 103. For example, if it is sent:

255,0,0-> RGB LED shows the Red shade


153,255,0 -> RGB LED shows a Lime Green
0,102,255-> RGB LED shows a sky blue

2 The worker from the previous point is going on vacation, which is why Mr. Martin is very upset because not...
He understands very well how to write the color separated by commas. That's why the worker came up with a
great idea, place two buttons:

Button 1 (S1) allows you to choose a color from a menu (Red, Green, or Blue) each time it is pressed.
The text on the Serial Console that says the color must change, must have debounce so that for each
pulse given, just change a color. An example of the pulse given and the value displayed on the console:

Pulse 1-> Red


Pulse 2 -> Green
Pulse 3 -> Blue
Pulse 4 -> Red

Button 2 (S2) allows you to vary the color from 0 to 255 of the last assigned color name.
the Button 1 (S1). While S2 is pressed at intervals of 100ms (milliseconds), the variable of
that color should increase by one. The name of the Color should be printed (last state)
due to S1) and then the numerical value of the color, finally the result should progressively be reflected
I already in the RGB LED. For example, according to the last state of the Pulse 4 and then S2 is pressed:

Pulse 4 -> Red


Red 0
100ms
Red 1
100ms
Red 2

Assistance to solve it: For each color, you need to create two variables, one to store the name of the color and
the other to store the numerical value that you have for that color.

LED RGB

S1 S2

105
T12 Motor ON/OFF control

What do I learn? Prior knowledge

Control ON/OFF Digital signal

If/else Conditional digitalWrite() function and


digitalRead()
Connect a DC motor by
transistor Voltage divider

Conditionals from the Recognize a transistor and a


state of the button motor

Materials

1
1

1
NPN Transistor
Arduino UNO
1
1 Breadboard

Button
USB Type AB Cable

1 2 8

1K resistor MM Connectors
DC Motor

SCAN WITH YOUR


SMARTPHONE

SEARCH T20AB
LIKE THIS

VISIT THE OPTION OF

106
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value? If I want to save 3—This symbol to R
of this resistance? the number π that what corresponds E
type of variable G
Should I use?
U
_____Ω N
_______________ _______________ T
_____MΩ
A

107
C /*
---------------------------------------------
Ó Motor ON/OFF control
---------------------------------------------
D Program that makes use of a motor and a button,
I while pressed, the motor must
be turned on (ON) otherwise it must be
G off

0 Mechatronics Stuff and Robotics Store


*/

D //--------------------------------------------------
//Declares input and output ports and variables
E //--------------------------------------------------
intpulsador=7;//Declares Pin of the button
intmotor=3; //Declare Motor Pin

P //------------------------------------
Main function
R //------------------------------------
void setup() // Executes every time the Arduino starts
O {
pinMode(button, INPUT); //The button as an input
G pinMode(motor, OUTPUT);//The motor as an output
}
R
A
//------------------------------------
M //Cyclic function
//------------------------------------
A voidloop()// This function keeps running
{ when the Arduino is powered on
C
I If the button is pressed
if(digitalRead(button) == HIGH) {
Ó
digitalWrite(motor,HIGH);//Turns on the motor
N
}else{//if the button is not pressed
digitalWrite(motor, LOW); //Turns off the motor
}

}
// End program

T 1–A Bridge It is an electronic circuit that allows a motor


I DC can rotate in both directions, forward and backward. They are widely used.
P in robotics and as power converters.
S
The H bridges are available as circuits.
integrated, but they can also be built at
starting from discrete components. The term
"Bridge H" comes from the typical representation
circuit diagram. An H bridge is built with
4 switches (mechanical or by transistor-
When the switches S1 and S4 are closed
Two and S2 and S3 open, a positive voltage is applied to the motor, making it turn in a
sense. By opening switches S1 and S4 and closing S2 and S3, the voltage is inverted,
allowing the motor to reverse direction. With the nomenclature that
we are using, the switches S1 and S2 can never be closed at
same time, because this would short-circuit the power source. The same
It happens with S3 and S4.

108
EXERCISES

1 A mill to extract groundwater has a motor that helps


to the pumping process of the liquid, the water is at a depth of
A height of 40m and the pump must operate continuously.
The farmer has a single button (S1), when pressed it
the motor pump is turned on for the first time if he presses the button again
my button for the second time the water pump turns off with which
stop pumping the liquid. The setup for this exercise uses the mis-
It is a connection scheme different from the one presented on page 107.

2 A new washing machine detergent has hit the market, with


a great novelty, if when you use the detergent in your washing machine it is
turn to the right (D) at a certain time is possible
remove stains from clothes while the washing machine is spinning
to the left(I) at a certain time at the end of the cycle of
washing the clothes will have a very silky texture as if it were
I would have applied fabric softener. The company Lucky Lucgran manufactures
the washer's singing wants to implement this system, for that
you have been hired to develop the program that gives
according to what is received from the console, the washing machine must be operated, for example:

D,3 Washer beats to the right for 3 seconds


I, 2 Washing machine hits to the left for 2 seconds
A Washing machine off

MY NOTEBOOK

109
T13 PWM control of a motor

What do I learn? Prior knowledge

Read data from the Serial Console Analog signal

Handling the map() function analogWrite() function and


[Link]()
Vary the PWM to produce 5
different speeds PWM

Power stage for a Conditional and operators of


motor through transistor comparison

Materials

1
1
1
NPN Transistor

Arduino UNO 1
Breadboard

DC Motor
1

1 5

USB Type AB Cable


1K Resistance MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T21AB
LIKE THIS

VISIT THE OPTION OF

110
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value 2—How do you write- 3—This symbol to R
of this resistance? I am the following what corresponds E
numbers in binary? G
U
7=______ N
_____Ω
_____KΩ 5=______ _______________ T
2=______
A

111
C /*
---------------------------------------------
Ó PWM control of a motor
---------------------------------------------
D Program that uses an engine and the Console
I Arduino serial has the possibility of
set the engine to 5 different speeds,
G from the PC keyboard you can send him the
desired speed. The 5 speeds are configured
0 with 5 different PWMs.
Mechatronics Stuff and Robotics Store
*/
D //--------------------------------------------------
//Declare input and output ports and variables
E //--------------------------------------------------
intmotor=3; Declare Motor Pin
//------------------------------------
//Main function
//------------------------------------
P void setup() // Executes every time the Arduino starts
{
R [Link](9600);//Starts the serial communication Arduino-PC
}
O
//------------------------------------
G //Cyclic function
//------------------------------------
R voidloop() // This function keeps running
{ // cuando este energizado el Arduino
A
If there is any value in the Serial Console
M if([Link]()){
A //Variable where the character sent from the keyboard is stored
chara = [Link]();
C
If the entered character is between 0 and 5
I if(a>='0'&&a<='5'){
Ó Variable to scale the input value to PWM range
intspeed=map(a,'0','5',0,255);
N PWM writing to the motor
analogWrite(motor,speed);
//Mensaje para el usuario
The motor is turning at the speed
[Link](a);
}else{// If the entered character is NOT between 0 and 5
//Mensaje para el usuario
Invalid speed
[Link](a);
}
}
}
//End program

T 1–Arduino can also be programmed in graphical languages, for example:


I
P
Modkit
S

Scratch for Arduino

112
EXERCISES

The director of the movie Super Crocodile must record a


1 scene where Super Crocodile receives strong winds to
make your superhero cape move in unison with the
wind speed, for that it has a large fan
(motor) high power, the speed control of the
the fan is with the director, as he turns the potentiometer
The speed must be changing. Your mission is to develop a program that meets
these characteristics for the scene to be recorded ;)

The latest news from the Appliance Fair has left everyone greatly re-
2
name a blender that incorporates two buttons through which it is
It is possible to vary the 10 different speeds (0 to 9) at the time of blending.
All of this is supported from the serial console where it is possible to see the Speed
chosen, the buttons are adjusted as follows:

Button 1 (S1) allows you to choose a speed from a menu (Speed 0 … Speed 9), each time
when S1 is pressed, the text on the Serial Console that says the speed must change, it must have debouncing
so that for each pulse given only one speed changes. An example of the pulse given and the value shown
through the console:

Pulse 1 -> Speed 0


Pulse 2 -> Speed 1
Pulse 3 -> Speed 2

Button 2 (S2) when pressing S2 for the first time, the motor should start spinning at the chosen speed.
In front of S1, if S2 is pressed a second time, the motor must stop. It should be displayed on the serial console.
Blender spinning at speed x or Blender stopped as appropriate.

S1 S2

113
T14 Generate tones with a buzzer

What do I learn? Prior knowledge

Handling variables of type Digital and analog signal


entered
map() function and analogRead()
Use special functions of
Arduino Send parameters to the fun-
actions
Generate various tones
Delays through delay()
Produce frequency outputs

Materiales

1 1 1

Arduino UNO Buzzer


Breadboard

1 1

USB Type AB Cable 10K potentiometer


MM Connectors

SCAN WITH YOUR


SMARTPHONE

SEARCH T22AB
LIKE THIS

VISIT THE OPTION OF

114
P
L
A
N
O

E
S
Q
U
E
M
A

P
1—What is the value 2—Elswitch...case 3—This symbol to R
of this resistance? it's a type of what corresponds E
G
U
_____Ω N
_______________ _______________
_____MΩ
T
A

115
C /*
---------------------------------------------
Ó Generate tones with a buzzer
---------------------------------------------
D Program that uses a buzzer and a
I potentiometer, the idea is to generate various tones
in the buzzer from the analogous state of
G potentiometer. Additionally, the function is used
tone that is very useful for generating various melodies
0 Mechatronics Stuff and Robotics Store
*/

//--------------------------------------------------
D //Declare input and output ports and variables
//--------------------------------------------------
E intbuzzer=9;//Declara Pin del buzzer
inttono=0; //Declare potentiometer pin

//------------------------------------
Main function
P //------------------------------------
void setup() // Executes every time the Arduino starts
R {
No initial parameters are set, but they should be.
O // place the header of the setup() function
}
G
R //------------------------------------
Cyclic function
A //------------------------------------
voidloop() // This function keeps running
M { when the Arduino is powered
A Integer variable where the value of the potentiometer is stored
intsensor=analogRead(tono);
C
Variable where the frequency is scaled from 100 to 5000Hz
I intfrecuencia=map(sensor,0,1023,100,5000);
Ó Integer variable to store the desired time in ms
intduracion=250;
N //Function tone(), which receives:
1st position: Sound element pin
2nd position: Desired frequency in Hz
3rd position: Tone duration
tone(buzzer, frequency, duration);
Delay
delay(100);
}

//End program

T 1–If you are having difficulty learning the colors of the resistors, a little help
I online wouldn't hurt you at all ;) inWolfram Alphacan you do this:
P
S

116
EXERCISES

We suggest making a musical synthesizer for two.


tones, using two buttons. The idea is that when pressing
S1 produces a tone at a frequency of 400Hz with
a duration of 100ms, while if you press S2 it
produce a tone at a frequency of 2600Hz with a hard-
200ms action. Combine these two tones until
develop a beautiful melody.

Buzzer

S1 S2

MY NOTEBOOK

117
A Hello, we want to know your
P
O opinions regarding this ma-
R material, they are very helpful with the
T the spirit of continuing to improve
E
S contents and making them
clearer.

We are ready to receive everything


type of comments that we
serve as feedback and strengthen our co-
community of knowledge.

Write to us at:

sales@[Link]
Thank you very much for your contributions :D

118
Basic Guide to Arduino

Do it yourself and learn electronics and programming

9 Chapters of content

14 Step by Step Tutorials

28 Exercises applied to real-life cases

Questions, tips, quizzes and much more

Contáctenos

[Link]
ventas@[Link]

tdrobotics

tdrobotics

Things About Mechatronics

You might also like