Basic Arduino Course Overview
Basic Arduino Course Overview
BASIC COURSE
Delivered remotely
18 / 04 / 2016 -- 29 / 05 / 2016 ( 30 HORAS )
CHAIR 2016
INDEX OF CONTENTS
Objectives 1
Content planning 2
Arduino Shields. 22
Introduction to Arduino. The Arduino UNO and the Arduino Mega 2560. 23
Engine Management. 74
Bounces 105
Sensors III: Humidity and Temperature (DTH11, LM35 and DS18B20) 121
Bibliography 134
Objectives
Content Planning
Engine Management.
How to use the EEPROM memory of Arduino.
Practice 2.
Sensors I: Light (LDR) and ultrasound (HC-SR04).
Practice 3.
The Moodle platform will be used to facilitate communication among the attendees.
course and the speaker.
Let's detail all the official models existing today, as well as present
some of the interesting unofficial and compatible ones. We must keep in mind that the
official Arduino models rise to more than 16 at the moment and there may be
hundreds if we add the compatible ones and the unofficial ones.
We will make a distinction between official, unofficial, and compatible, since they are not the same.
same. Let's look at the differences between these groups of plates:
Officials: they are those official plates manufactured by the Italian company Smart.
Projects and some have been designed by the American company SparkFun.
Electronics (SFE) or by the also American Gravitech. Arduino Pro, Pro Mini and
LilyPad is manufactured by SFE and Arduino Nano by Gravitech, the rest is
they are created in Italy. These plates are the officially recognized ones, include the logo and are the
only those that can carry the registered trademark of Arduino.
Unofficial or compatible: these are boards compatible with Arduino but cannot be
registered under the name of Arduino. Of course, they are designed and manufactured by
other external companies. These developments do not contribute anything to the own development of
Arduino, but rather they are derivatives that have emerged to meet other needs. These
they often use a name that includes the suffix "duino" to identify them,
for example, Freeduino, which we will talk about later.
Even in the Tools menu of Arduino IDE there is an option called Record
boot sequence. This option can be used to record the bootloader sequence
(bootloader) on the official Arduino microcontroller that for some reason has
it has become misconfigured or the microcontroller chip has been replaced by another. But it is also
A practical tool for programming a new microcontroller that we have introduced.
in our own plate 'duino'.
For example, there are compatible boards at the development environment level, that is,
only software level (being able to use Arduino IDE to program them). Others are
compatible at the hardware and electrical level in order to use the shields and modules
existing for Arduino without problem.
When selecting the license for our project, we need to keep this in mind very
present so we don't get surprises. We might be interested in a compatible board for certain
hardware qualities that Arduino lacks or due to licensing issues and yet
want it to be compatible with the Arduino IDE development environment. At other times it may
that simply seeks compatibility regarding the shields but has the need to
use another compiler (AVR Studio, Makefiles, ...).
General characteristics
The main thing we need to know is what type of projects we are going to implement. With
This gives us an idea of the number of analog and digital pins (normal and PWM type).
pulse width modulated to simulate an analog output) that we need for
our work. This first scrutiny allows us to discard some simpler plates that
not have enough pins or, on the contrary, discard those with the highest number of them to
reduce costs since we are satisfied with fewer pins.
We can also deduce the size of the code we are going to generate for our
sketchs. A very long program, with many constants and variables will demand an amount
larger flash memory for storage, so a board must be chosen
suitable so we don't fall short.
Finally, regarding the voltage, they do not matter much at an electronic level, except
in some cases, to take into account the amount of stress that the plate can handle for
assemble our circuits.
The best-selling board that is most recommended for the majority of projects,
Everything if you are starting out, is the Arduino UNO. It's enough for most projects, it has
a good price and has balanced parameters.
Official plates
Among the official plates, you can find numerous models. All especially
designed for a purpose, compatible with official shields and modules, as well as with Arduino
IDE. We will try to detail their main features in order to differentiate them from each other:
Arduino UNO: it is the most widespread platform and the first one that came to market, for
Hello, we can base ourselves on this to make the
comparison with the rest of the boards. All the
characteristics of this board will be
implemented in almost all boards
remaining, except for a few that already
We will see. It is based on a microcontroller.
Atmel ATmega320 8-bit at 16MHz that
it works at 5v. 32KB corresponds to the
flash memory (0.5KB reserved for the
bootloader), 2KB of SRAM and 1KB of EEPROM.
In terms of memory, it is one of the most limited boards, but that doesn't make it less so.
insufficient for almost all projects that circulate the network. The outputs can
work at higher voltages, between 6 and 20v but a voltage of
operates between 7 and 12v. It contains 14 digital pins, 6 of which can be used.
as PWM. Regarding analog pins, there are up to 6. These pins can
work with current up to 40mA.
Arduino Zero: in appearance, it is similar to Arduino UNO, but this board hides
surprises regarding the UNO platform.
Instead of the Atmel ATmega microcontroller
based on 8-bit AVR architecture, the Zero
it contains a powerful Atmel SAMD21 MCU of
48MHz with a 32-bit ARM Cortex M0 core.
With 256 KB of flash memory, 32 KB of SRAM and
an EEPROM of more than 16KB by emulation. The
the operating voltage is 3.3V/5V (7mA) and
it contains 14 digital I/O pins, of which 12
they are PWM and UART. In the analog field, it
it has 6 inputs for a 12-bit ADC channel and an analog output for DAC
10 bits. Ultimately, this board is intended for those whose Arduino UNO is insufficient.
short and need a bit more processing power.
Arduino Mega: its name comes from the microcontroller that manages it, a
ATmega2560. This chip operates at 16MHz and with a voltage of 5V. Its capabilities are
higher than the ATmega320 of the Arduino UNO,
although not as superior as the solutions
based on ARM. This 8-bit microcontroller
works together with an 8KB SRAM,
4KB of EEPROM and 256KB of flash (8KB for the
bootloader). As you can see, the
the features of this board are similar to the Due,
but based on AVR architecture instead of
ARM. In terms of electronic features, it is quite similar to the previous ones,
especially to the ONE. But as can be seen at a glance, the number of pins is
similar to the Arduino Due: 54 digital pins (15 of them PWM) and 16 pins
analogous. This board is ideal for those who need more pins and power than
it contributes ONE, but the necessary performance does not require resorting to ARM-based.
Arduino Ethernet: It is an Arduino UNO and an integrated Ethernet shield. This board is
quite similar to the UN, even in the
aspect, but it has networking capabilities. Its
the microcontroller is an ATmega328 that
operates at 16MHz (5V). It is accompanied by 2KB
of SRAM, 1KB of EEPROM and 32KB of flash. The
the rest of the electronic characteristics are like
the ones from UNO only that adds capacity to
Ethernet connection thanks to a controller
W5100 embedded TCP/IP and possibility of
conectar tarjetas de memoria microSD. Los
The available pins are 14 digital (4 PWM) and 6 analog. It should be taken into account that
that Arduino reserves pins 10-13 to be used for SPI, pin 4 for the SD card and the
2 for the W5100 switch.
Arduino Fio: It is an Arduino board reduced to its minimum expression. Due to its size, it is
especially considered for projects
wireless phones or to be inserted into
reduced spaces. Works with a
ATmega328P microcontroller, a version
similar to that of Ethernet but works at a
lower frequency, 8MHz. Being so reduced
lacks certain comforts, for example,
To upload the sketches, you need to use an FTDI cable or an additional adapter board.
Sparkfun. Likewise, the voltages used are reduced to the
3.35-12v maximum. 14 digital pins (6 PWM) and 8 analog pins will be the only ones.
available on this board. It also doesn't help that it has 2KB of SRAM, 32KB of flash, and 1KB of
EEPROM, all of this will greatly limit the size of the sketches and the circuit of the
project.
Arduino Nano: They started by incorporating an ATMega328 like the one in other boards.
previously seen, but after the 2.x review it was replaced by a 16MHz ATmega168.
Its dimensions are even smaller than
those of Fio, measuring only 18.5×43.2mm. Its
reduced size does not take away the possibility of
to be a complete plate, but it does need
of a mini-USB cable and does not have a connector of
external feeding. This version was
designed and produced by the company
Gravitech, specially designed for
low-cost applications where size matters. At an electrical level
It behaves like a UNO, with 14 digital pins (6 PWM) and 8 analog ones. But its
capacities have decreased with the new revisions in favor of lower consumption.
Therefore, it has changed from 32 to 16KB of flash (2 reserved for the bootloader), from
2 KB of SRAM and from 1 KB to 512 bytes of EEPROM.
Arduino LilyPad: Specially designed to be integrated into garments and textiles, that is, it is a
"available" version of Arduino. It was developed
by Leah Buechley and SparkFun Electronics for
to be employed for the same purposes as others
Arduino's only with certain limitations to
change in their integration capabilities and their
base flexible. It is based on two versions of
different microcontrollers, both low
consumption referred to as Atmega168V and
ATmega328V, this second one is more powerful.
Both work at 8MHz, but the first one
It works at only 2.7v and at second at 5.5v. It has
of 14 digital pins (6 PWM) and 6 analog to
along its perimeter. It also integrates 16KB
of flash memory for the program code, 1KB of SRAM, and 512 bytes of EEPROM.
Arduino Mega ADK: Board based on an ATmega2560 like the Mega version.
previously. But its main advantage
Does it have a prepared interface?
to be connected via USB to
mobile devices based on Android,
thanks to its IC MAX3421e. This allows
to have all the capabilities of a
Arduino Mega board (the same regarding the
remaining characteristics) plus the
joint development opportunities with
an Android platform.
Arduino Esplora: It differs from the other boards, apart from its small size and
due to its shape, it has a series of onboard sensors. It is good for the
people who begin to give their
first steps in the world of
electronics and they are learning, hence their
name. Includes some sensors
(accelerometer, temperature, light)
buzzers, buttons, joystick, microphone and
a socket to connect a screen to
TFT LCD color. It works with a microcontroller ATmega32u4 that operates at 16MHz and
5v, with 2.5KB of SRAM and 1KB of EEPROM. The flash reaches 32KB with 4KB reserved.
the bootloader. The biggest problem is its connectivity capability, which is almost nonexistent, since
everything is integrated for beginners.
Arduino Micro: Designed by Adafruit and aimed at high autonomy and with
a small size. Its price is
low compared to other models.
However, it has
similar characteristics to others
designs, like a microcontroller
ATmega32u4 at 16Mhz, 20 pins
digital (7 of them PWM) and 12
analogous. In many ways it is similar to Leonardo, but with the ability to
built-in USB communication, eliminating the need for a second processor.
We will only analyze the most famous ones since, as I mentioned, there are hundreds of them.
They and probably every day more of these plates are born. It is indeed true that the majority
we must pay attention to the official models for support and
developer community that may seem obvious, but it must be acknowledged that some boards
compatibles are certainly interesting:
[Link] U+: SlicMicro is the creator of this compatible board, both in hardware as well
in software, with Arduino UNO Rev3. This
open source hardware platform adds
characteristics in front of the official. To pass the code
from Arduino IDE we must select the option
Arduino UNO Rev3 as if it were ours
license plate and the code will load without issues. The
additional features that integrates (SlicBus
Port, an additional LED, potentiometer, button.
The rest is the same as the Arduino, including its ATmega328
that shares with some official versions. This
the board is interesting for those looking for the combined features of Arduino
UNO and Esplora, although more limited in onboard gadgets than the latter. What is certain is
one advantage is its SlicBus port which allows connecting special modules manufactured by
SlicMicro.
SainSmart UNO and Mega: they are two SainSmart boards fully compatible with Arduino.
UNO and with Arduino Mega that have followed the official branch
step by step, even in the reviews (see SainSmart UNO
Rev3). Even in terms of physical appearance and color, they are quite
identical to the official ones, not to mention in their characteristics
techniques, using even the same microcontroller. The
The price of Mega is around 15 euros and the UNO version is 8.
euros. We can verify that the great advantage of these plates is
its price compared to the official ones. Some characteristics are the
use of an ATmega8u2 chip programmed to control
the USB and convert it to serial instead of the method used
previously with controller chip. The
encapsulation of the chips, which in these boards is more advanced than the primitive DIP of
UNO official.
Braduino: it is based on UNO with rearranged LEDs, mini-USB connector, alteration of the
pin 13 of the circuit to restart the LED and a
resistance that does not interfere with the function of the pin
when it acts as an input. It was designed with
free software like KiCAD and is distributed under
GPLv2 license. For the rest of the features, it is
identical to the official and fully compatible with
this. It has been created by the Brazilians of
Holoscope for students, designers and
apprentices of the world of electronics. But
keep in mind that your availability is more
ChibiDuino2: created by the Japanese from TiisaiDipJp. It is compatible with UNO and includes two
mini-USB B, a port for a 1602 LCD and a breadboard area.
For the rest, it is similar in characteristics to the official, except in
its size, which is more reduced, due to its distribution and its
the price is quite economical.
Romeo 2012: DFRobot has created this board specifically designed for enthusiasts.
from robotics or mechatronics. It is totally
compatible with Arduino UNO Rev3 pin to pin and
its electronic and characteristics of
Programming is similar. The interesting thing is
that includes a series of features
onboard that the officials do not have,
highlighting, for example, the controller of
motors (in two directions and up to 2A). Another
features is a Xbee socket that allows
start the project immediately, without
need for a motor controller
additional or Wireless shields. It also works with an Atmega32u4 microcontroller,
accompanied by a multitude of programmable buttons and a socket for a module
APC220 and Bluetooth.
Seeeduino: SeeedStudio has created this compatible board, both physically and
software level, with official Arduino Diecimila.
Therefore, there will be no problem using
Arduino IDE and the official shields. In its version
first had an ATmega168, being able to choose
by an ATMega328 starting from v2.21. Certain
parts have been remodeled to provide
greater flexibility and a good experience of
user.
Zigduino: Logos Electromechanical has created this kit that is more than just a simple board. It integrates
an ATmega128RFA1 microcontroller, a ZigBee for
connections to wireless network (IEEE 802.15.4). Also
includes an external RPSMA jack and is fully
compatible with Arduino Duemilanove. When implementing
these network functionalities without the need for shields
externally, the price of the plate exceeds 50 euros.
Motoduino: Guibot has been responsible for creating this board with an ATMega328 and a
L293D with double H bridge for control
of motors without the need for elements
additional externals. For the rest of
features, this Chinese board is compatible
with Arduino. This board is interesting
to create vehicles with electric motors and
the use of motors in small robots.
Boarduino: it is a board created by Adafruit and compatible at the software level with
Arduino, but not at a physical level. So no.
it can be used with the official shields. Its
characteristics are similar to an Arduino
Ten thousand, but its size is smaller and
It's quite a bit cheaper. It is
specially designed to be inserted in
a breadboard type plate.
Femtoduino: ultra small board measuring just 20.7×15.2mm, barely larger than a
coin. This plate was designed by Fabio
Varesano for very small projects.
Integrates an ATMega3298P-MU and is compatible.
at the software level with Arduino.
Moteino: LowPowerLab has created a mini board the size of an SD card with
wireless communication possibilities thanks to the RFM12B or RFM69W/HW/CW chip
from HoperRF. It is compatible at the software level,
so you can program with Arduino IDE
using an FTDI adapter or directly
via USB interface in the Moteino version
USB.
Sanguino: compatible with Arduino at the software level and based on an ATmega644.
despite its small size, it integrates 64KB of
flash, 4KB SRAM and 32 general-purpose pins
general. It was developed together with the
RepRap 3D printer project.
Versalino Uno: Virtualbotix creates this compact and compatible design at the level of
software with Arduino. Its main
characteristic is the distribution of its
components, which has allowed to make a
very compact and smaller size plate, like this
such as the placement of its connection pins
that are not arranged transversely to
the board, but in parallel to save space.
Leaflabs Maple: almost all models are based on Atmega AVR chips or chips from
Atmel based on ARM. But this board breaks.
with that scheme and integrate an ARM STM32 (ARM
32-bit Cortex-M3 at 72MHz) manufactured by
STMicroelectronics. Leaflabs has created this board.
with a compact design that is compatible with the
shields, despite their architecture. The
programming can be done using Open
Maple IDE that implements the language
Arduino to avoid having to relearn another one.
programming language, as well as libraries
low-level native.
Goldilocks: Thin Layer Embedded designed this board based on an FPGA (Altera Cyclone
IV, with DDR2 RAM, SRAM, flash, oscillator and a
Atmel ATSHA204 Authentication IC/EEPROM
to offer extreme flexibility. It is
compatible with Arduino shields, but in
in this case you will not only be able to program it at the level of
pcDuino: it is a miniPC like the Raspberry Pi, only that it combines the features of
a development board like Arduino. It has an HDMI port to connect it to
a screen or your TV to use it as a monitor
of the system, in addition to other USB ports and slot
for microSD memory cards So you can
connect peripherals as in the case of the Raspi,
including those that add network functionalities.
It can boot operating systems like Ubuntu.
Android ICS, among other Linux distributions.
To move these systems comfortably available
1GB of RAM, 2GB of onboard flash, processor
ARM Cortex A8 (based on ARM11) at 1GHz and a
GPU Mali 400 (the same that are integrated in Samsung)
Galaxy S3). All of this makes it the perfect companion for the most advanced users.
who want an all-in-one (duino platform + miniPC) with superior hardware
to the Raspberry Pi.
Ruggeduino: is a board compatible with Arduino UNO (including at the software level) and
similar in almost all aspects to the official one. As such
we only found some very variations
interesting for electronics, such as the
integration of electronic protection against ESD
in its pins and electrical connections, thing of the
which the official UNO lacks. Its price amounts to
$39.95
More and more Arduino-based boards are appearing, especially unofficial ones. But
how to check what to look for when acquiring a board is if
we want hardware compatibility, software compatibility, or both.
Next, we will see if the board we want to purchase has the hardware that
we want to use. However, as of today, for education and due to the price difference,
I recommend acquiring either the Arduino UNO or the Arduino Mega 2560 with more.
benefits.
It is possible to stack various shields although the upper image is already a case.
extreme not advisable.
[Link]
I suggest to the reader to check out that website and analyze the information from different sources.
shields, we in this course will use the Ethernet shield, which will allow us to perform
applications that can be controlled and/or monitored via the web.
Introduction to Arduino
Arduino is a development platform for physical computing.
open source, based on a board with a simple microcontroller and an environment of
development to create software (programs) for the board.
We can use Arduino to create interactive objects, reading data from a large
variety of switches and sensors and control a multitude of types of lights, motors, and others
physical actuators. Projects with Arduino can be autonomous or communicate with a
program (software) that runs on a computer.
The board and the development software are open and we can download them for free from the
[Link]/en/Arduino can be powered through the USB connection or
with an external power supply. The power supply is selected
automatically.
Technical specifications
3.- ICSP: Connector for ICSP (In Circuit Serial Programming, or Programming
Serial in circuit). The ICSP is the system used to program the devices without
need to remove the chip from the circuit of which it is a part.
4, 5, 6 and 7: Digital Input/Output Pins:
Pin 0 (RX) and 1 (TX). It is used to receive (RX) and transmit (TX) TTL serial data.
Pins 2 and 3. External interrupts. These are pins responsible for interrupting the
sequential program established by the user. They can be configured to
activate an interrupt on a low value, a rising or falling edge, or
a change in value.
Pines 3, 5, 6, 9, 10 and 11. PWM (pulse width modulation)
width modulation).
They consist of 6 PWM output bits with the analogWrite() function.
Pin 13. LED. There is an SMD LED with its current limiting resistor connected to this.
pin. It is also the only pin that contains an integrated limiting resistor in the
Arduino board in series with the pin. Being able to connect an external LED between this pin and
GND directly.
SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins serve as support for the
SPI communication with the SPI library. The SPI Bus (from English Serial Peripheral
Interface) is a communications standard, primarily used for the
information transfer between integrated circuits in electronic equipment.
11.- Power connector: 2.1mm female plug for the power connection in the
plate.
VIN: Input pin for an external voltage source that will serve to
power the Arduino.
5V: Output pin, regulated voltage source of 5V, this voltage can
either come from the VIN pin, the USB connector, or another 5V source
regulated.
3.3V: Output pin, 3.3-volt source generated by the FTDI chip
integrated with a maximum current consumption of 50mA.
GND: ground pins.
Reset: A LOW (0V) value can be applied to reset the
microcontroller. Typically used to add a reset button to the
shields that do not allow access to this button on the board.
However, throughout this course, it is possible that there will be some mention of something.
characteristic of this microcontroller and we should consult the datasheet to clarify the
functioning.
IMPORTANT:
According to the board we have, we will have to select it in the Arduino IDE.
This manual has used the Arduino UNO board and the Arduino Mega board.
[Link]
In our case, we will download the version for Windows. Upon completion of the download
we will obtain a compressed folder, (of the .zip type) that we must decompress in the folder
"Arduino", keeping the structure of the folder we have downloaded.
1. Connect Arduino UNO to the PC using the type A-B USB cable.
2. The Windows 7 operating system detects the device and will attempt to install the
drivers, but it will not install them because it cannot find them.
5. We will click on 'Search for driver software on the computer. Search and install.
the manual shape controller software.” We will press the button
Click 'Browse' to select the folder where the drivers are located.
6. We will select the folder "Arduino" and, within it, the folder "Arduino
1.0.x/drivers and click 'Next'.
8. If everything is correct, the assistant will have installed the driver for
Arduino UNO and it will show us in a window. The exclamation with the circle
yellow must have disappeared.
that the application has not found our Arduino) and we select the Port where the
the system has recognized our Arduino (see point 9 of the driver installation).
Finally, we will click on 'File' and then on 'Preferences', and we will modify the
window according to the following figure:
- File Menu:
It has the same options as any program
based on Windows (New, Open, Close, etc...) and
algunas opciones añadidas como por ejemplo:
Sketchbook: If we position ourselves on top, they will unfold.
all the Sketches that we have saved inside our
Sketchbook.
Examples: If we position ourselves on top, all will be displayed.
the examples that the Arduino IDE provides by default.
Upload: It is used to send the sketch to the Arduino board.
Load using Programmer: It is used to upload the sketch
to the Arduino board using an external programmer.
- Edit Menu:
- Sketch Menu:
This menu has the following options:
Add FileImport Library
they add a file or to our Sketch
a bookstore.
Automatic Format:
Establish
adequately the
tabs for
our sketch
Archive the Sketch: Compress all open sketches in the IDE and save them by default.
in the Arduino folder in the documents folder of our PC. Create a single *.zip file
Repair Encoding and reload: Compile and upload the sketch we are working on,
discarding all changes made since the last save.
Serial port: We choose the port where we have connected the Arduino board.
Programmer: We choose the type of programmer in case we do not use the own board.
Arduino as a programmer.
Record Boot Sequence: It gives us the possibility to record the Arduino bootloader in
a microcontroller to be able to use the Arduino IDE.
- Help Menu :
The notifications area is the zone of the Arduino IDE where the compiler will give us
information about possible errors, which board we have connected and to which port. We also
indicates which line we have the cursor in within the work area.
The workspace is the editable area of the Arduino IDE where we will write our
code to later compile it and transfer it to the board. In the Arduino environment
we can have as many functions as we want (user-defined) but at a minimum
we will have two: setup() and loop()
The names that have the character § at the end are because they have been modified and have not
have been saved.
The code located in the setup() function will run only once, when the system starts up.
that is, when starting the microcontroller (not to be confused with the bootloader). They are usually configured
los pines como entradas o salidas en esta función o inicializar algún dispositivo. El código que
let's place in the function loop() instead, it will run indefinitely (loop means loop in
English)
In 1972 Dennis Ritchie and Brian W. Kernighan published "The Programming Language"
C”. 40 years later, it is regarded as the beginning of high-level programming, the basis of the
most of the languages we know today and where the famous example of 'Hello' appears
World. Since then it has been common to name, as Dennis and Brian did, 'Hello World'
when the first test is performed in any programming language. In the world of the
physical computing, the equivalent of 'Hello World' is 'Blink', alternate
between a high and low state on a digital pin configured as output. Next, we are going to
load our "Blink" on our Arduino.
The example 'Blink' is studied next, although it is not essential for the reader.
fully understand each line, it is important to understand the algorithm that is
uses.
Description: You can start the code with a brief description of the functionality of
our sketch. Let's note that we use the instructions "/*" and "*/" to introduce
comments of more than one line.
Function setup( ): This function is executed only once when the system starts. In this case only
We use it to configure pin 13 of our Arduino UNO as output. We use the
pinMode function for that. When the comment occupies a single line we use the double
bar '//'. Pin 13 has an LED connected on the board itself in almost all models of
Arduino.
Function loop(): This function will run while the board is powered and not in
reset. With the digitalWrite function ( led, HIGH ), we write a high state to pin 13 (if
we measure the voltage at the pin, we will measure 5V). Then we make the microcontroller
wait for a while with the delay function. This function causes a wait in milliseconds in
function of the parameter used in its call. Later we will comment on things about this.
famous but dangerous function. After waiting, we write a low state on the same pin.
with the digitalWrite function (led, LOW), (if we measure the voltage at the pin, we will measure 0V) and
before writing a high state again, we wait a little for 1000
milliseconds.
If we consider that this function runs indefinitely, we already have the blinking of the pin.
as we wanted.
From now on, all the sketches we create will be uploaded to Arduino in the same way.
way, so the process of uploading a sketch to Arduino will no longer be explained.
One of the advantages of Arduino is, besides its simplicity, the possibility of
develop our code through graphical environments based on icons, a good option
if we don't want to waste much time creating the software or if we want to learn the
basics of programming.
Minibloq
Modkit (alpha)
S4A
Scratch 4 Arduino
Ardublock
Physical Etoys
It is a web application that allows you to create Arduino projects with layout of
breadboard or PCB. Such projects can be shared in a way that they are made
cooperatives, we can order the PCBs we make in a way very similar to the
What Fritzing offers us and we also have an online programming IDE, accordingly.
we can continue coding from our tablet.
It is a very attractive platform for being both easy and powerful at the same time.
It turns out. It is also a very good tool for teaching, that spirit that is so much
The Arduino community likes it. And of course you can simulate your code online!
When we have the circuit, we start with the code (it's not strictly
it is necessary to follow that order).
And once we have finished the code, it's as easy as clicking 'upload &
run" to start seeing how your creation comes to life. The only drawback it has is the
The platform is that if your code doesn't compile, it won't tell you where the error is, although
this is pure syntax. If you can't find your error, you can click on 'download code' or a
just copy and paste it into our Arduino IDE to check, correct, and paste it again.
As we can see, it simulates many components and also simulates a serial terminal.
Fritzing
PCB view, where you can see or make the connections of our schematic
in PCB.
VBB simulates many microcontrollers from the PIC16 and PIC18 lines, now also
with the emulation of Arduino. In addition, there is a wide variety of
simulated components such as LCDs, servos, logic, and other I/O devices that
they can be used to model and simulate high-level circuits.
In its early versions, VBB was free, now it has become an application of
payment.
Creating and simulating a project is simple and basically involves the following:
The VBB in its latest version at the time of this publication comes with numerous
proyectos de ejemplo para Arduino, PIC16 y PIC18, la plataforma Amicus y Netduino,
ready to run them and analyze them. Below are the breadboard windows
virtual and code of a simple example with Arduino, an LED and a potentiometer:
VBB is an excellent entry option for learning to program Arduino if you do not
it has the real plate and for those who want to try the platform first
verify that it meets your needs and expectations, before risking to carry out the
economic investment in the purchase of the hardware plate.
Regarding the simulation of the PICs, it would be excellent if the VBB supported the simulation.
in C language; currently it only supports the assembly language associated with the PIC,
it is complex and not very advisable for beginners, however it is possible that
In the future, it will also support C language.
From now on, any simulation platform has its limitations. For the
beginners, the VBB is an excellent tool for learning; for those who
they have more experience is useful for simple and quick tests and prototypes; but not
very useful for carrying out medium or high complexity projects in which generally
It is required to have the hardware implemented for real, non-simulated tests.
Proteus
It will be about summarizing as much as possible and referencing the nuances that are
necessary to develop sketches as clearly as possible.
void setup()
{
estates;
}
void loop()
{
estates;
}
Where setup() is the part responsible for gathering the configuration and loop()
it is the one that contains the program that will run cyclically (hence the term loop)
Both functions are necessary for the program to work.
The configuration function must contain the declaration of the variables. It is the
first function to be executed in the program, it runs only once, and it is used to
configure or initialize pinMode (I/O working mode), configuration of the
serial communication and others.
The following loop function contains the code that will be executed
continuously (reading inputs, activating outputs, etc.) This function is the
core of all Arduino programs and the one that does the most work.
Setup ( )
The setup() function is called only once when the program starts. It
used to initialize the operating modes of the pins, or the serial port. Must be
included in a program even if there is no statement to execute.
void setup()
{
pinMode(pin, OUTPUT); // sets the 'pin' as output
}
Loop ()
Functions
The keys are used to define the beginning and the end of a block of
instructions. They are used for the programming blocks setup( ), loop( ), if.., etc.
type function()
{
estates;
}
The semicolon
int x = 13; // declares the variable 'x' as an integer type with the value 13
Because the comments are ignored by the program and do not take up
memory space on Arduino can be used generously as well
They can be used to 'comment' code blocks for the purpose of annotating.
information for debugging.
Note: Within the same line of a comment block, it is not possible to write.
another block of comments (using /* .. */ )
Comment line //
A comment line starts with // and ends with the next line
code. Like block comments, line comments are ignored by the
program and do not take up space in memory.
// this is a comment
Variables
Note: Variables should take descriptive names to make the code more
legible. Nombres de variables pueden ser “contactoSensor” o “pulsador”, para ayudar
the programmer and anyone else to read the code and understand what
represent the variable. Variable names like 'var' or 'value' provide very little help.
that the code is intelligible. A variable can be any name or word that
do not be a reserved word in the Arduino environment.
Variable declaration
int variableInput = 0;
A variable can be declared at the beginning of the program before the part of
setup() configuration, at the local level within the functions, and sometimes inside a
block (not advisable), as for loops of the type if.. for.., etc.
Depending on the location of the variable declaration, the scope will be determined.
of application, or the ability of certain parts of a program to make use of it.
void loop()
{
Int variable2;
Int i; float f;
for (i=0; i<20;)
{
i++;
}
}
Types of variables (see all at:[Link] )
Byte: Stores an 8-bit numeric value without decimals. They have a range between 0 and
255.
Char: It is a data type that occupies one byte of signed memory. They have a range.
between -128 and 127. For a byte data (8 bits), use the data type 'byte'.
Integers are a type of primary data that store numerical values of 16
bits without decimals contained in the range -32768 and 32767.
Long: 32-bit integers without decimals that are within the range.
-2147483648 to 2147483647.
Float: Numbers with decimals. Floating-point numbers have a greater
resolution that those of 32 bits with a range between
-3.4028235E+38 to 3.4028235E+38.
Note: Floating-point numbers are not exact and can produce results
strange in comparisons. Floating-point mathematical calculations are
also much slower than those of the integer type, so it must
avoid its use if possible.
Arrays
In the same way, it is possible to declare an array by indicating the data type and the size.
and subsequently, assign values to a specific position:
To read from an array, simply write the name and the position to read:
Arithmetic
The operations are carried out taking into account the type of data we have defined.
for the operands (int, dbl, float, etc.), so, for example, if we define 9 and 4 as
Integers 'int', 9 / 4 returns a result of 2 instead of 2.25 since 9 and 4 are values
of type integer 'int' (integers) and decimals are not recognized with this type of data.
This also means that the operation can suffer an overflow if the result
is larger than what can be stored in the data type. Let us remember the
scope of the numeric data types that we have explained earlier.
If the operands are of different types, the largest type will be used for the calculation.
of the operands in play. For example, if one of the numbers (operands) is of the type
float and another of integer type, for the calculation the float method will be used, that is
floating point method.
Compound assignments
Comparison operators
Logical operators are used to compare two expressions and return a value.
‘TRUE’ or ‘FALSE’ depending on the operator. There are three logical operators, AND (&&),
OR (||) and NOT (!), which are often used in if.. statements:
Constants
if (aVariable ?? value)
{
executeInstructions;
}
Note: Pay attention to the special use of the symbol '=', putting inside if (x = 10),
it may seem valid but it is not since that expression assigns the
value 10 to the variable x, so within the if structure x==10 would be used that in
In this case, what the program does is check if the value of x is 10.
‘if… else’ is a structure that executes in response to the idea 'if this does not happen...'
complete do this other thing." For example, if you want to test a digital input, and make a
What would you do if the input is high or do something else if the input is low, you would write that?
this way:
'Else' can be preceded by another condition in such a way that several can be established.
conditional structures of one type inside the other (nesting) so that
they are mutually exclusive and can be executed at the same time.
The initialization of a local variable occurs only once and the condition is tested each time.
that the execution of the instructions inside the loop ends. If the condition continues
Once fulfilled, the instructions of the loop are executed again.
When the condition is not met, the loop ends.
A while loop is a loop that runs continuously as long as the condition is met.
expression placed in parentheses in the header of the loop. The variable used as
comparison, it will have to change to break the loop. The situation may change at the expense
from an expression within the loop code or also by changing a value in a
sensor input.
The 'do... while' loop works in the same way as the while loop, with the exception
that the condition is tested at the end of the loop, so the loop will always execute at
less than once. do
{
Instructions;
} while (aVariable ?? value);
It is important to realize the ‘;’ at the end of the loop, behind the comparison.
pinMode(pin, mode)
digitalRead ( pinDigital )
Read the value of a pin (defined as digital) giving a HIGH or LOW result.
(low). The pin can be specified either as a variable or a constant (0-13).
digitalWrite(pin, value)
Send the previously defined OUTPUT 'pin' the value HIGH or LOW (putting
in 1 or 0 output). The pin can be specified either as a variable or as a
constant (0-13).
digitalWrite(pin, HIGH); // deposits a HIGH value (high or 1) in the 'pin'
The delay function (time) stops the execution of the program for the specified amount of time.
as indicated in the instruction itself. Its use is not recommended; instead, it is suggested to
it is recommended to use the millis() function.
delay(1000); // waits 1 second
Note: This number will overflow (if it is not reset back to zero) after
approximately 50 days unsigned long = 232ms = 49 days, 17 hours, and 2 minutes.
analogRead(pin)
Read the value of a specific pin defined as an analog input. The Arduino board
it has 6 channels connected to a 10-bit analog-to-digital converter. This means that
it will convert voltages between 0 and 5 volts to an integer between 0 and 1023. This provides
a resolution in the reading of:
5 volts / 1024 units, that is, 0.0049 volts (4.9mV) per unit.
value = analogRead(pin); // assigns to value what it reads from the input 'pin'
Note: The analog pins (0-5) unlike the digital pins, do not need to be
declared as INPUT or OUTPUT since they are always INPUTs. The input range
it can be changed using the analogReference() function.
analogWrite(pin,value)
The frequency of the PWM signal will be approximately 490 Hz. the values of
analogRead ranges from 0 to 1023 and the values of analogWrite range from 0 to 255.
Parameters :
pin: It is the pin where the PWM signal is to be generated.
value: The desired duty cycle ranging between 0 (always off)
y 255 (always on).
val = analogRead(analogPin);
analogWrite(ledPin, val / 4);
analogReference(EXTERNAL)
With this instruction, we are telling our Arduino not to use its voltage.
default reference ( +5 V ), or the one we introduce through the AREF pin of our
plate.
Communication Series
It is used for communication between the Arduino board and a computer or others.
dispositivos. Todas las placas Arduino tienen al menos un puerto serie. Se comunica a través
from digital pins 0 (RX) and 1 (TX), as well as with the computer via USB. Therefore, when
Using these functions, we will not be able to use pins 0 and 1 as digital input or output.
We can use the built-in serial port monitor in the Arduino environment to
comunicarnos con la placa Arduino. Se debe seleccionar la misma velocidad en baudios
used in the call [Link]().
[Link] (speed)
Set the data rate in bits per second (baud rate) for the
serial data transmission. To communicate with the computer, use one of these
velocidades: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600 o
115200.
[Link](9600);
[Link]()
Read the incoming data from the serial port.
Byte = [Link]();
Print the data to the serial port as ASCII text followed by a return.
carriage return (ASCII 13, or '\r') and a line feed character (ASCII 10, or '\n').
[Link]()
if ([Link]() > 0)
{
reads the serial port
}
min ( x, y )
Calculate the minimum of two numbers for any type of data returning the
smallest number.
value = min(value, 100); // assigns to value the smaller of the two specified numbers.
max ( x, y )
Calculate the maximum of two numbers for any type of data returning the
larger number of the two.
value = max(value, 100); // assigns to value the greater of the two numbers 'value' and 100
randomSeed(valor)
The random function returns a random integer number from a range of values.
specified between the min and max values. If min is not specified, it is taken as 0.
value = random(100, 200); // assigns to the variable 'value' a random number between 100-200
The following example generates a random value between 0-255 and sends it to an output.
analog PWM
int randNumber; variable that stores the random value
int led = 10; // define led as 10
void setup() { } no need to configure anything
void loop()
{
randomSeed(millis()); random seed based on the millis() function
randNumber = random(255); Generate a random number between 0-255
analogWrite(led, randNumber); // sends the PWM type output led the value
delay(500); // wait 500 ms = 0.5 s.
}
Switch / Case
In particular, a switch statement compares the value of a variable with the value
specified in the case statements. When a case statement is found whose value
If it matches that variable, the code of that statement is executed.
The keyword break exits the switch statement, and is typically used at the end of
each case statement. Without a break statement, the switch statement would continue executing the
following expressions ('falling-through') until finding a break, or until reaching the end of the
switch statement. It can also be used in do, for, while loops and is used to exit the loop in
the moment when break is executed.
switch (var)
{
case 1: //do something when it is equal to 1
break;
case 2: //do something when it is equal to 2
break;
default: // if nothing matches, execute the 'default'
the "default" is optional
}
continue
The continue statement skips the rest of the iterations of a loop (do, for, or while).
Continue jumping to the loop condition and proceeding with the next iteration.
#define
It is used to include external libraries in the sketch. This grants the programmer
access to a large number of standard C libraries (groups of pre-made functions), and also
libraries specifically written for Arduino.
The main reference page for AVR C libraries (AVR refers to Atmel chips in
which is based on Arduino) is located at:
[Link]
Just like "#define" should not end with a semicolon " ; "
Bitwise operators
Bitwise operators perform their calculations at the bit level of the variables. They help
to solve many of the most common problems at the programming level. Most of the
The following material is taken from an excellent tutorial on logical mathematics, which can be
found in ([Link]
& ( and )
| ( or )
not
xor
( left shift )
(shift to the right)
valor = lowByte(x);
value = highByte(x);
bitSet(x, n);
bitClear(x, n);
bit(position): Calculates the value of the specified bit (bit 0 is 1, bit 1 is 2, bit 2 is 4,
etc.).
bit(n);
All practices and/or projects that are carried out will have to be set up properly.
practice on the Arduino board, on a board and/or designing the appropriate PCB.
PD7/AIN1
47/20
46/19
we will press 'P' we will introduce
7/34 ~PD6/AIN0
PC0/ADC0 45/18
8/35 ~ PD5/T1
For this reason, we must be especially careful with the local variables that are defined, since
that every time the execution of the loop function begins, the local variables will return to
initialize. If we use functions like delay(), we will make the microcontroller wait for a
determined time and did not execute any instruction during that time, therefore, the
inputs will be read with a delay and in practice this means that our circuit does not
will immediately respond to an external event, so we will try not to use
functions or loops of this kind.
Next, we will compile our sketch, running our project to see the
functioning.
As we can observe, when pressing 'P', the LED turns on and when releasing 'P', the LED turns off.
It is left as an exercise to modify the position of the button and the resistor.
R3
10k
input, that is, using the pull-up configuration and verify that when pressing 'P'
we will introduce a '0' and upon releasing we will introduce a '1' through the input pin
digital, turning the LED on and off opposite to the previous exercise.
Modify the sketch so that the operation is the same as the exercise developed.
That is to say, when pressing 'P', the LED lights up and when releasing 'P', the LED turns off.
P1b) Start and Stop Buttons: Following the same procedure as in practice 1, we
you should add a button such that one of them will turn on the led and the other will turn it off, the
we will call "[Link]" and "[Link]".
Sometimes, it can be interesting
use connections with
ARDUINO
terminals, in this way
AREF P. MARCHA P. PARO
we reduced the wiring in the
RESET
PB5/SCK
PB4/MISO
~PB3/MOSI/OC2A
53/26
52/25
51/24
scheme. In this case the
march strike
50/23
~ PB2/SS/OC1B
~PB1/OC1A
PB0/ICP1/CLKO
49/22
48/21 terminal 'march' of
R1 R3
7/34
PC0/ADC0
~
PD7/AIN1
~PD6/AIN0
47/20
46/19
45/18
march
strike 10k 10k button is a terminal of
8/35 PD5/T1
PC1/ADC1 44/17 D1
exit that is found
9/36 PD4/T0/XCK
PC2/ADC2 43/16
10/37 ~ PD3/INT1
PC3/ADC3 42/15
11/38 PD2/INT0
PC4/ADC4/SDA 41/14
12/39 TXPD1/TXD
If(pulsadorMarcha==1) { salida=1; }
If(pauseButton==1) { output=0; }
Compile the sketch, set up the circuit on a breadboard, and check the actual operation.
In the following practices, the same criteria explained will be attempted to be used.
preferably the pull-down resistor configuration, so that in the state of
rest, that is to say without pressing, we will introduce a '0' to the Arduino and when pressing the button, it
it will introduce a "1" to the Arduino, but it is possible that in some project we must use the
pull-up resistor configuration.
There are many libraries that allow Arduino to gain new functionalities, such as
for example create a GPS, send SMS messages, manage LCD or TFT screens, etc.
We can create our own libraries to avoid rewriting code or use others that have been created.
by third parties. In any case, once they are available, they must be installed.
Check if there is another one in the 'sketchbook' folder of our personal folder.
called "libraries". If not, it needs to be created.
2. Download the desired library to the desktop, for example one called 'Time'.
([Link] and decompress it.
3. In this step, there are two possibilities:
o If the unzipped folder contains another folder with the same name inside,
this last one needs to be copied into the "libraries" folder from the first step.
o Otherwise, you must copy the uncompressed folder directly into the
folder 'libraries'.
Observation:
Another option is to install them as an administrator in the folder where the libraries are located.
/usr/share/arduino/libraries
The procedure to use the added library is the same as for using any other.
of those that come with Arduino by default:
Standard libraries
Esplora - this library enables you to easily access various sensors and actuators.
mounted on the Esplora board.
Robotthis library enables easy access to the functions of the Arduino Robot
Bridge Library - Enables communication between the Linux processor and the Arduino
on the Yún.
Contributed Libraries
Sensing:
Timing:
DateTimea library for keeping track of the current date and time in software.
Metrohelp you time actions at regular intervals
MsTimer2 uses the timer 2 interrupt to trigger an action every N milliseconds.
Utilities:
As you can see, there are many libraries, and many more continue to appear.
As more components and/or shields for Arduino are being released, so in this
In this course, we will dedicate ourselves to using the most important libraries and they will be explained as we go.
that we need.
Engine Management
Let's take a brief look at the different types of engines we are going to use and their
most common control circuits. We can find ourselves with direct current motors
and alternating current motors.
According to the construction of the stator coils, we can distinguish two types:
. Bipolar
The current that flows
due to the windings changes from
meaning in function of the
tension that is applied, for the
that the same winding
it can have at one of its ends, different
polarity (bipolar).
T
I
e
n
. Unipolar
They are called that because
For the control, we will use the ULN2003 or the ULN2803 integrated circuit.
We must pay attention to the fact that the motor windings require a
negative pulse to be activated, as the ULN has its outputs
inverted, when it receives a '1' through pin INn will send a "0" to the output
OUTn.
These sequences follow the order indicated in each table for
make the motor spin in one direction, if you want it to spin in direction
opposite, it is only necessary to reverse that sequence.
- The second is to activate the coils in pairs, in this case the field
magnetic is
duplicate, and in
consequence the
motor has
greater strength of
transfer and retention.
We can also use the L298N integrated circuit, specifically this module.
what can be easily acquired or assembled:
a3) Servomotors
A servomotor (also called a Servo) is a
device similar to a direct current motor,
that has the ability to locate itself in any
position within its operating range, and
remain stable in that position.
It is made up of an engine, a box
reducer (Gears), a potentiometer and a
control circuit. Servos are used
frequently in radio control systems and in
robotics, but its use is not limited to these. It is
possible to modify a servomotor to obtain a
direct current motor that, although no longer
It has the ability to control the servo, maintains the strength, speed, and lowers.
inertia that characterizes these devices.
According to the manufacturer, the color of the terminal varies, here I present the manufacturers.
more known.
- Cut the potentiometer shaft so that it does not rotate when moved.
motor, adjust it to its midpoint with the help of an ohmmeter,
stick the axle with loctite so that it does not move from its midpoint and
put it back into the servo housing.
- Remove the potentiometer and
replace it with another one (for example
multiturn) and prepare the casing
to make a hole in the place
suitable, so that through a
screwdriver, we can vary the resistance of the potentiometer
introduced to adjust it to its midpoint.
- Remove the potentiometer and replace it with 2
fixed resistors whose value is equal to half
of the total value of the original potentiometer.
Solder them in their proper place to make believe
to the electronic circuit that the potentiometer
find it at its midpoint. The resistances
they must be of 1% tolerance.
In the case of having a three-phase motor, the control circuit for rotation direction is:
Therefore, from now on and throughout this manual, this criterion will be applied and in
otherwise it will be duly indicated.
Let's see how to use the EEPROM memory of Arduino to reuse the
important data, recover the Arduino configuration or even transfer data from a
sketch another.
Store the integer data in an auxiliary variable (to avoid losing the data.
original)
Check the number of bytes the data has.
Store the most significant byte in a byte type variable.
Store the byte in the EEPROM.
Shift eight bits (one byte) of the auxiliary variable to the left, in such a way
that the second byte of that variable becomes the most significant.
Repeat the operation as many times as the size of the variable.
initial.
Composing Bytes
Again, there are several ways to solve this problem, let's see one:
Create a variable of the type we want to recover and assign it the value 0 (of
so that all its bits will be 0.
Define another variable equal to the previous one (the auxiliary variable).
Read a byte from the EEPROM memory and store it in the auxiliary variable
using the OR instruction, which stores the byte in the eight
least significant bits of the auxiliary variable.
Shift the bits of the auxiliary variable to the left so that they remain
in the position that interests us.
Perform a new OR operation between the auxiliary variable and the final one.
Clear the auxiliary variable and repeat the process as many times as necessary.
P2a) Carry out the control of a movable hook, whose diagram is the following:
In the state of rest, the limit switches Fa
y Fbare deactivated, the engine is
find stopped, and the start buttons
( Maand stop (P) deactivated.
The system in the initial state is located
activating FaThe stop button 'P' is
find disconnected (not used in this
exercise).
With the system in the initial state, an operator presses [Link] that the
hook moves to the right (Md1, Mi="0"), until F is activatedb,
In that case, the hook must change its direction to the left (Mi1
Md="0"). When the hook arrives and activates Fa, the hook will stop,
staying still until a new pulse of Ma.
The operator only activates the system when the hook is present.
activating Fathat is to say, if the hook is in motion, whether towards the
right or left if the operator presses Mait should not produce any effect. The
The stop button “P” in this exercise has no effect. The motor used,
It is a 5V direct current motor.
P2b) Modify exercise P2a so that when the hook activates 'Fbit seems, but no
It will start until the operator presses M again.a.
P2c) Modify exercise P2b by adding the stop button "P" in such a way that,
When I pull "P", the hook should stop anywhere, waiting.
let the operator press "M" againaIn which case, the hook will move to the
sense in which it had stopped.
P2d) Analyze the EEPROM library and create a program using EEPROM memory
from our Arduino so that in case of a power outage,
the automation stops and when the power returns, the automation continues with its
normal operation, at the point where it stopped.
Sensors ( I )
Luminosity - LDR Resistance
The range of resistance that an LDR can give us from total darkness
In full light, it will vary from one model to another, but in general, they oscillate around 50 Ω.
at 1000 Ω when fully lit and between 50 KΩ and several MΩ when it is
completely in the dark.
One of the things to consider is the time it takes to change the resistance.
when the light it receives changes, there are models with different response times, in addition
it does not vary in the same way from light to darkness as from darkness to light. Anyway, except
that we need an extremely fast and precise variation response, the LDR gives us
it will be useful for most projects that we are going to use.
Ultrasonics - HC-SR04
Power Supply: 5V
Sensing angle: 15°
Distance range: 2 to 500 cm
Number of pins: 4 ( Vcc, Trig, Echo, Gnd )
If the speed of sound at 20ºC in the air is 343 m/s and knowing that the echo must go
and returning after "t" seconds. So we have that the distance "d" in meters is:
Send a pulse of at least 10 µs through the TRIG pin (trigger) to start the reading.
The sensor will send 8 ultrasonic pulses and set its ECHO output high,
We must detect this event and start a 'countdown'.
3) The ECHO output will remain high until it receives the echo reflected by the obstacle.
to which the sensor will set its ECHO pin low, that is, we will finish "counting the
time
4) The distance is proportional to the duration of the pulse and we can calculate it with the
following formulas:
d (m) = (343 · t(s) ) / 2 = 171.5 · t(s)
Note: If the pulse duration is longer than 30 ms, it means there is no obstacle.
This is the theory and we will not need it to use this sensor as there is
a library that returns the distance in centimeters or in inches called
Ultrasonic.
Open the Arduino IDE, click on 'Files' - 'Examples', then look for
"Ultrasonic" and select "Serial".
a low timeout means that many measurements can be taken in a short time.
We can modify this timeout in the file '[Link]'.
Important note:
The Arduino IDE is constantly being developed, with new versions being released regularly.
time. Until before version 1.0, the libraries needed to include the file 'WProgram.h',
but starting from version 1.0, the file name was changed to 'Arduino.h', and also it
it included several more features, with the appearance of the Arduino Due, it is expected that there will be a new one.
Another more elegant solution that will make the compiler decide on its own, that
file include, depending on the version of the Arduino IDE used is to delete the line #include
"WProgram.h" and instead write this code:
Practices ( III )
Where:
Vin = Voltage that we introduce to Aref
Rinternal = Internal resistance of Arduino of 32KΩ
Rexternal = Resistance through which we supply Aref
Vrefencia = The voltage on which our program will reference.
If we set that reference very low, the LEDs will start to work with less.
ambient light that if we put a very high signal, let's remember:
RV1
10k
50%
ARDUINO
+5V R1 D1 LED-RED
AREF 220
PB5/SCK
53/26 R2 D2 LED-RED
52/25
PB4/MISO
RESET 51/24
~PB3/MOSI/OC2A 220
LDR1 ~ PB2/SS/OC1B 50/23
TORCH_LDR ~PB1/OC1A 49/22 R3 D3 LED-RED
48/21
PB0/ICP1/CLKO
220
47/20
PD7/AIN1
7/34 ~PD6/AIN0 46/19 R4 D4 LED-RED
PC0/ADC0 45/18
8/35 ~ PD5/T1
PC1/ADC1 44/17
9/36 PD4/T0/XCK 220
PC2/ADC2 43/16
10/37 ~PD3/INT1
+88.8 R6 11/38
PC3/ADC3
PD2/INT0
42/15 R5 D5 LED-RED
1k PC4/ADC4/SDA 41/14
Volts 12/39 TXPD1/TXD
PC5/ADC5/SCL 40/13
RXPD0/RXD 220
ARDUINO UNO R3
Note: For the timer, the millis() function should be used. As a sensor of
We will use the HC-SR04 module, keeping in mind that we need to configure it.
the '.cpp' file to detect 5 m.
Specifications:
Type of infrared emitter LED
Wavelength λ 950 nm
Diode lens transparent, blue
Field of view 44°
Another more home-made alternative is to take advantage of the photodiodes and phototransistors from the
old ball PC mice, so when we disassemble the mouse, we will have:
For our purpose, we can combine the two transmitters, which will give us the
the center terminal which would be the collector and the other 2 connected which will be the emitter.
D1
Q1 1
J1 design in such a way that both the
R4 2
LED_IR
Phototransistor
470
Exit
photodiodes like the
phototransistors can be placed
in the places to be detected.
Rebounds
We have seen how we can read the state of the pin, but, what happens if
Do we want to count the number of times it changes state? We do not want to detect the
state in which the pin is found but we want to count the number of times
that changes state. This may be necessary when the same button needs to
determine different behaviors or simply, to implement a counter.
We will encounter the dreaded bounce problem (debounce). They are the undesirable ones.
state changes that occur when a mechanical contact changes state.
How can we
observe, the function the
I have called anti-bounce and
as parameters of
entry receives a
byte type variable and
return the result
also like a byte.
Si tenemos una variable (“miVariable”) a la cual debemos quitar los rebotes, haremos
the call to this function in the following way;
Practices (IV)
Mode 0: Normal mode, in this mode when pressing 'P' the LED turns on, when
release 'P' the LED turns off.
Mode 1: Switch Mode, in this mode, when pressing and releasing 'P', the LED
change of state.
Mode 2: Clapping mode, in this mode, we will simulate that when claps are given
2 claps (or two loud sounds), the LED changes state, having in
It says that the time between one clap and the next must be less than 500.
We would actually connect a microphone with an amplifier.
operational 741 to an analog input of the Arduino and we will detect
when the sound exceeds a threshold of tension, for example, 2 V.
Mode 3: In this mode, we will use the display. It will start representing a
Zero. When the "P" button is pressed and released before 2 seconds, the
the number displayed will increase each time
press and release 'P'. If 'P' is held down for 500 ms
approximately, the display will quickly increase at a speed of
500 ms. The numbers displayed must be
understood between 0 and 9, and they will be increasing. The next
the number to show after 9 will be 0.
D2
signal from the transmitter that will be placed in the P0 P1 P2 P3 P4
M2
R2
220
R5 R6 R7 R8 R9 LED-BLUE
ARDUINO UNO R3
As an improvement, it is left as an extra exercise to add the doors in the cabin in a way.
that upon arriving at the floor from which they have been called, the cabin doors will open. For the
that the doors must have their corresponding limit switches. In addition, it is possible to
add an infrared light barrier at the door as a security measure so that it does not
They can close the doors if there is any obstruction.
we must declare the variable of string type that will contain the result of the
concatenation, therefore;
#include <String.h>
StringConstructors
String Addition Operator
StringIndexOf
String Append Operator
StringLengthTrim
String Case Changes
StringReplace
StringRemove
StringCharacters
StringStartsWithEndsWith
StringComparisonOperators
StringSubstring
Click on the link of each function to see how they are used. In this
in the course we will use some of these functions.
When mounting the shield on top of Arduino, we will have several Arduino pins occupied and
we will be able to have the following:
Estashield comes with a library called 'LCD KeyPad', which must be copied into the
folder libraries of the Arduino IDE, this library in turn uses the standard control library
the LCDs called 'Liquid Crystal', which is already included by default in the Arduino IDE.
It allows the Arduino board to control LCD displays based on the Hitachi chipset.
HD44780 (or compatible), which is found in most text LCDs.
the library works in 4-bit mode or in 8-bit mode (that is, through 4 or 8 lines of
data, as well as RS, ENABLE, and optionally, the RW control lines.
Syntax: LiquidCrystal (Rs, Rw, Enable, d0, d1, d2, d3, d4, d5, d6, d7)
Rs: Arduino pin number that is connected to the RS pin of the LCD
Rw: Arduino pin number that is connected to the RW pin of the LCD
Enable: Arduino pin number connected to the Enable pin of the LCD
d0, d1, d2, d3, d4, d5, d6, d7: Arduino pin numbers that are
connected to the corresponding data pins of the LCD.
d0, d1, d2, and d3 are optional; if omitted, the LCD will be controlled using
only four lines of data (d4, d5, d6, d7).
Begin(): Specify the dimensions (width and height) of the LCD display.
Clear : Borra la pantalla del display LCD y posiciona el cursor en la esquina superior
left.
Syntax: [Link]()
home() : Positions the cursor at the top-left corner of the LCD. This is the
position in which the following text will appear on the display. Unlike with the
previous that does not clear the previous content of the display.
Syntax: [Link]()
setCursor( ) : Sets the cursor position where they will start to appear
following characters written on the LCD.
BASE (optional): The base in which the numbers will be printed: BIN, DEC,
OCT, HEX.
TX Module RX Module
Working tension 3V~12V Working tension 5.0Vdc + 0.5V
Current max≤40mA (12V), min≤9mA(3V) Current ≤ 5.5mA ( 5.0VDC )
Modulation ASK / ALSO Modulation ASK / OOK
Frequency 315MHz - 433.92MHz Frequency 315MHz - 433.92MHz
Speed ≤ 10 Kbps Speed < 9.6 Kbps
20-200 m (depending on the tension of
For maximum distance,
TX distance RX Distance put up wire antenna
work
of 23cm
TX and RX come paired.
This library uses external interrupt 0 (digital pin 2), which we will study further.
go ahead, for now we will only use it
Another brand is, for example, 'dinuy', whose product catalog we can
visualize in:[Link]
In the workshop we have the kit composed of a lamp holder and its remote.
distance from the avidsen brand whose reference is 103211. This kit is used to turn on, turn off
to regulate the increase or decrease of light intensity with the
remote control. It has a range of 20m (A23 12V battery included).
It only works with E27 incandescent bulbs.
The operating frequency is 433.92 MHz with ASK/OOK modulation.
In the transmission, the information is encoded with a code, which when
arrives at the receiver, which is responsible for decoding it. This code can be
modify through some switches that both the sender and
the receiver.
Practices ( V )
LCD1
LM016L
We will use Putty (Software that simulates
a terminal, similar to HyperTerminal, but from
+5V
free license) to send a text to our
Arduino and this should be displayed on an LCD of
RIGHT
R1
2k RV1 16x2 (LCD Keypad Shield module). It also
AD0
10k you can use the Serial Monitor that comes with
R2
UP
330 integrated into the Arduino IDE although this does not
+88.8
Send.
620
DOWN
AREF
ARDUINO UNO R3
53/26
PB5/SCK
52/25
PB4/MISO
R4 RESET
~PB3/MOSI/OC2A 51/24
CTS
RTS
TXD
RXD
The ASCII code: (American Standard Code for Information Interchange—Standard Code
American for Information Exchange.
A final is available
"Fc" race for detection
when the door is found
closed, another finish line
"Fa" to detect when the
the door is open, a barrier
of infrared light, which without
detecting any obstacle, send a '1' and when it detects an obstacle the beam of light
infrared is interrupted by sending a '0'. The door in a resting state is closed and
acting 'Fc', when a vehicle wants to enter or exit, the driver sends a signal of
433.92 MHz radio frequency modulated in ASK and the door opens until 'Fa' is activated.
At that moment, a timer starts counting.
If "t" seconds pass without "FIRdetect some obstacle, the door must
to close
If there is no obstacle that cuts the infrared beam and the remote control does not
When pressed, the door must close completely, activating to 'Fc' and remaining at rest.
until a new pulse from the remote control.
If while the door is open, activating 'Fa', the infrared barrier 'FIRdetects
any obstacle, no time 't' should pass, starting to count from the moment
what 'FIR” deje de detectar el obstá[Link] simular el mando a distancia, utilizar un pulsador,
such that when pressed, it is assumed that the remote control has been pressed and the code has been transmitted
correctly.
The variable 'CódigoPermitido' should be modified with the code of the remote control.
of RF used, for this it is necessary to view in the Serial Monitor the code that is transmitted
when the button on the remote is pressed and replace 'longCodigoPermitido=263507;' with the code
transmitted by the RF control.
Sensors ( III )
This DHT11 sensor will help us measure both relative humidity and the
temperature. The downside of this sensor is that it will only give us whole measurements, that is, without
decimals, since the resolution that
The presentation is 1% for relative humidity
and 1ºC for the temperature.
It can measure humidity between the range of 20%-90% and temperature between the range
0ºC–50ºC.
The connection of the sensor to Arduino (sensor only without module), we must add a
pull-up resistance :
Another temperature sensor, quite interesting is the LM35 whose output voltage is
linearly proportional to the Celsius temperature (centigrades).
To use this component in Arduino, we need to add the "OneWire" libraries and
"DallasTemperature" inside the "Libraries" folder.
Practices ( VI )
Connect the module to our Arduino and enter the following code:
But before studying the Ethernet shield, we need to know the HTML language that
and on which websites are based.
The Ethernet board will be studied next and several will be carried out subsequently.
practical exercises where we will see how information can be sent over the Internet
using Arduino, so we will use HTML language to create very WEB pages
simple.
Use the Ethernet library to write programs that connect to the internet using the
The Ethernet shield has connectors that allow it to connect to other
place them on top and stack them on the Arduino board.
Important:
a) PWR: indicates that the board and the shield are powered.
b) LINK: indicates the presence of a network link and blinks when the shield sends
or receive data.
c) FULLD: indicates that the network connection is full duplex.
d) 100M: indicates the presence of a 100 Mb/s network connection.
opposite to one of 10Mb/s)
e) RX and TX: blinks when the shield receives/sends data
f) COLL: blinks when collisions are detected on the network
We can observe that the Ethernet shield has a sticker on the bottom.
where it indicates to us the MAC (Media Access Control, 'media access control') is a
48-bit identifier (6 hexadecimal blocks) that uniquely corresponds to a
network card or device. It is also known as physical address. More information at:
[Link]
Shields that do not have any sticker indicating the MAC can be assigned.
a random MAC, but all the MACs of the devices on the local network must be different.
We can also observe that the Ethernet Shield has a connector to house
a microSD memory card, which we can use to store or read the data that
we want.
Practices (VII)
What we are going to create with the Ethernet Shield is a Web server, which will allow us
it will provide the HTML code so that we can view it in our browser and thus interact
with him.
A server provides information to the computers that connect to it. When the
Users connect to a server, they can access programs, files, and other information.
from the server.
Para acceder a la página Web que creemos, deberemos acceder con una dirección IP
belonging to our network, which will be the one we have assigned to the Ethernet Shield. In the
code that you will see below, you will see that the IP address I have assigned is
[Link]/24.
It is the subnet mask, being /24, means that we will have 24 bits as '1' and 8 as '0'.
'0', that is, it will be [Link].
With the program compiled and uploaded to Arduino, if we open the browser
any PC, mobile, tablet, etc. that is connected to the local network via cable or
wirelessly, and we type the IP [Link], we will enter the Web that we have written
in the sketch, that is, we will have the following window:
The result, once compiled and saved in Arduino, we will be able to verify.
opening a browser and typing the IP address of the Ethernet shield. The page will refresh
every 5 seconds.
Final comments
To conclude, I will mention that every day new applications and new projects arise.
new modules and new research about Arduino that make this board have
much acceptance especially in Teaching, since it is possible to achieve with little effort
rather attractive projects.
Students at this level, when they start to work on projects with sensors,
motors, limit switches, relays, mobile devices, etc.... acquire a high motivation and this leads to
so that the students take an interest in the module and even some students acquire through their
count the Arduino board, shields, modules, and electronic components to carry out projects
individuals in their home.
Bibliography
Principles of electronics.
Malvino
McGraw-Hill
Arduino: [Link]
BricoGeek : [Link]
Arduteka :[Link]
INDEX OF PRACTICES
PRACTICE (V): Communications with Serial Port and practicing with RF.
P5a) Communication using the Arduino serial port 116
P5b) Automatic garage door using RF 118