100% found this document useful (2 votes)
2K views149 pages

Arduino - Advanced Methods and Strategies of Using Arduino

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (2 votes)
2K views149 pages

Arduino - Advanced Methods and Strategies of Using Arduino

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 149

Arduino

Advanced Methods and Strategies of


Using Arduino
© Copyright 2020 by Ethan Thorpe - All rights reserved.
This document is geared towards providing exact and reliable information in
regards to the topic and issue covered. The publication is sold with the idea that
the publisher is not required to render accounting, officially permitted or
otherwise qualified services. If advice is necessary, legal or professional, a
practiced individual in the profession should be ordered.
From a Declaration of Principles which was accepted and approved equally by a
Committee of the American Bar Association and a Committee of Publishers and
Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this
document in either electronic means or printed format. Recording of this
publication is strictly prohibited, and any storage of this document is not allowed
unless with written permission from the publisher. All rights reserved.
The information provided herein is Provinced to be truthful and consistent, in
that any liability, in terms of inattention or otherwise, by any usage or abuse of
any policies, processes, or directions contained within is the solitary and utter
responsibility of the recipient reader. Under no circumstances will any legal
responsibility or blame be held against the publisher for any reparation,
damages, or monetary loss due to the information herein, either directly or
indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely and is
universal as so. The presentation of the information is without a contract or any
type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the
trademark is without permission or backing by the trademark owner. All
trademarks and brands within this book are for clarifying purposes only and are
owned by the owners themselves, not affiliated with this document.
Table of Contents
Introduction
The Shield
Arduino Uno
Download and Install the IDE
Chapter One: Controlling The LED
Arduino Connection
Chapter Two: Alarm Siren & Signal Light
Hardware and Software Required
Test the PWM Output
Install the System with LED
LED Control Using PWM Connector
Chapter Three: MDF Robotic Arm Kit & Recording of Micro SD Card with
Arduino
MDF Robotic Arm Kit with Arduino
Variable Declaration and Void Setup () Function
Void Loop () function
Chapter Four: Home Automation: Presence Sensor & Automation of Irrigation
System With Arduino
Home Automation: Presence Sensor with Arduino
Automation of Irrigation System: Humidity Sensor and Solenoid Valve
Chapter Five: Flammable Gas Sensor & RFID Kit with Arduino
The MQ-2 Sensor
RFID Kit with Arduino: Access Control System
How Does an RFID module work?
Setup () and Lopp () Functions
Chapter Six: Current + Energy Meter & Audio Module WTV020-SD With
Arduino
Audio Module WTV020-SD - Incorporating Audio Elements with Arduino
Chapter Seven: KY039 Heart Rate Meter & Audio Recording And Playback
With Arduino
KY039 Heart Rate Meter with Datalogger
Audio Recording and Playback with ISD1820 Module
Chapter Eight: Digital Scale With Arduino And Strain Gauge Cell
How a Strain Gauge Sensor Works
Chapter Nine: IoT with Esp8266 WiFi Module & Updating ESP-01 Firmware
The Esp8266 WiFi Module
Talking to the ESP-01 Module through AT Commands
How to Connect to a Network with the ESP-01
Sending Data to the Browser
Receiving Data Sent by Cell Phone
Chapter Ten: RTC - Real Time Clock DS1302, 1307 And 3231
RTC DS3231
RTC 1302
RTC 1307
Differences between Modules
Conclusion
What are the Possibilities?
Accessible Technology >> Movement Maker
Introduction
One of the main phenomena of the last few years and one that has given greater
visibility to open source software, but above all, to the concept of open-source
hardware, is that of "makers." This phenomenon must be seen as a modern
interpretation of the "do it yourself" (DIY, Do It Yourself) for all those who are
fans of electronics, robotics, and software/firmware that allows you to animate
any object of this type.
It is absolutely undeniable that in this field, the electronic board, Arduino, is
most used for hobby and educational purposes, but in many cases, it is also great
for professional use.
Arduino, not just "a board"
Talking about Arduino as a single board is an understatement, as with this name,
it is considered an Italian project, created in Ivrea in 2005 to reduce the
prototyping times of electronic products at an extremely low cost.
This project currently includes an entire family of boards that differ in
processing capacity, type of connectivity available, size, and software/firmware
equipment. It ranges from the "Arduino Uno," considered the entry-level of the
family, to the "Arduino Yun," which currently represents the top of the range
(with Linux on board) passing through many other different boards.
The Shield
Where the peripherals available are not enough for our projects, we can purchase
one of the numerous “shields " through which the potential of the basic
electronic board extends, for example, adding the ethernet connection, Wi-Fi,
GPRS, a reader microSD and so on. It is no coincidence that there are numerous
add-ons or completely new projects defined as "Arduino-compatible" on the net,
precisely to express the concept of compatibility with this family both from a
hardware (connector/pin correspondence) and software (possibility firmware
execution); not least is the agreement reached with Intel that released the Galileo
board, pin-to-pin compatible with all Arduino shields and able to run any
program already written for the latter.
During this guide on programming with Arduino, we will refer to the first board
born in the family or the "Arduino Uno" which has all the credentials for the
realization of any project that comes to mind; given the absence of the native
Ethernet connection, it will subsequently be necessary to use the known "
Arduino Ethernet Shield. "
For those approaching for the first time the world of development on
"embedded" systems, it should be anticipated that very often we will have to
deal with extremely small orders of magnitude in terms of RAM and storage; we
will not talk about hundreds of MegaBytes (MB) or GigaBytes (GB)
respectively but much more likely than KiloBytes (KB). During this process, we
will see how many things can be done with such extremely reduced resources,
especially trying to taste the pleasure of interacting with the outside world.
Arduino Uno
The "Arduino Uno" is a board based on an Atmel microcontroller, ATmega328,
which has all the memory and storage necessary for our programs on board
(which as we will see are called “sketches "); in particular, we have available:

32 KB of Flash memory (of which the bootloader already occupies


0.5 KB), the Flash memory is used to save our "sketch" which will be
launched in execution every time the board is started;
2 KB of SRAM (Static RAM), RAM is used at runtime (for example
for variables);
1 KB of EEPROM (Electrically Erasable Programmable ROM),
which is used to save any data and configuration parameters useful
and/or necessary for our program.
It should be emphasized that, in terms of computing capacity, we are talking
about an 8-bit microcontroller with RISC (Reduced Instruction Set Computer)
architecture (yes ... you read that right! Only 8 bits against modern 32 and 64
processors bits we hear about every day) with a clock frequency of 16 Mhz
(forget the Ghz of your PC). Although these small numbers can scare you, you
will see how it is possible to achieve anything, while still being careful of the
waste of unnecessary bytes.
The main pins of the microcontroller are made available to the "maker" through
two connectors located on the edges of the board, through which it is trivial to
connect any other external device that can be driven through our program. In
particular, there are 14 digital pins and six analog pins, as the Atmega328 is also
equipped with a 6-channel AD converter (Analog to Digital) with 10-bit
resolution.
Each of the digital pins can be driven independently by software, setting the
level 1 (high) or 0 (low), and used as a GPIO (General Purpose Input Output)
pin; however, some of these pins have additional features if properly configured
and in particular:
A TTL serial port (attention not RS232) characterized only by RX
(Reception) and TX (transmission) signals;
Two pins to signal ("trigger") an interrupt towards the
microcontroller, at which specific processing may have to be
performed;
Pulse Width Modulation ( PWM) output signals to obtain a variable
average voltage (which is not only high or low) strictly linked to the
duration of a pulse over time;
An SPI (Serial Peripheral Interface) port used for interconnection
with external devices through the SPI synchronous bus;
An I2C (Inter-Integrated Circuit) port, which as the SPI, is used on a
synchronous bus for connection to other devices. It is also known as
TWI (Two Wires Interface) as it consists of only two signals against
the four provided by the SPI;
The pin that establishes the reference voltage ( AREF, Analog
REFerence) for all analog inputs. It is necessary to establish the
range of values that the AD Converter produces based on the 10 bits
available (in practice it will provide a numerical value between 0 and
1023, corresponding to the voltage values from 0 to AREF Volts);
In addition, the board provides two 3.3V and 5V output power signals that can
be useful for powering one or more external devices with which to
communicate, a RESET signal, and above all, an on-board LED that we will use
for our first application "Hello World."
The only direct connectivity with the outside world is characterized by a USB
connector that we can use to connect to our development PC. As we will see, the
PC will have a serial port to communicate with the "Arduino Uno," thanks to the
appropriate drivers to be installed and the "USB-to-serial" converter with which
the board is equipped (in practice the microcontroller is not has a native USB
interface but always uses serial communication).
Avoid Burning the Card on the First Try
An important consideration to make, to avoid burning our board at the first
"experiment," is that the microcontroller has an operating voltage of 5V
(maximum tolerable on all pins), but we can use an external power supply
between 6 and 20V. In addition, the maximum current supported on all pins is
40mA.
The interesting thing is that being open-source hardware, and all the wiring
diagrams are available online on the official Arduino website, so the board is
absolutely "replicable" at home; in fact, there are many unofficial "Arduino-like"
boards.
How to Find an Arduino Board
As for the purchase of Arduino boards, numerous online sites have them
available, starting from the large distributors of electronic materials such as
Mouser and RS.
In particular, for the readers of HTML.it, the Robot-Domestici distributor has
made available the code “html.it" to have a 3% discount on all the material
purchased during the year.
It should be noted that the examples used in this guide are compatible with all
Arduino boards and with the Intel Galileo.
With this first part of the introduction, we introduced the Arduino project and the
first-born board in the large family of boards. In the "embedded" development,
before being able to write some code, it is necessary to have a good knowledge
of the hardware that will be used in order not to incur unpleasant
inconveniences. From the next part, we will start with the study of the IDE,
which will be our travel companion in the creation of the so-called Arduino
sketches throughout the entire book!
Arduino, the Development Environment for Sketches
In the first part, we got to know Arduino and examined the basic characteristics
of the board (those of "Arduino Uno") so that we can take advantage of on all
evolutions, such as YUN or Intel Galileo. In this lesson, we can move on to
software development by introducing the development environment (IDE),
which allows us to write, compile, and transfer our programs to the board.
Firstly, it must be emphasized that the programming language used for Arduino
is C/C ++; we can talk about both languages, as it is possible to use the support
for the classes that C ++ makes available or not. Furthermore, the compiler used
is obviously dedicated to the Atmel AVR microcontrollers and is part of a well-
defined GCC toolchain.
With a compiler and a simple text editor, it is always possible to write and
compile a program but, to increase productivity and reduce development times,
we always prefer to use a dedicated IDE (if available); luckily with Arduino, we
have this possibility!
Download and Install the IDE
The Download section is available on the official Arduino website, from which
we can download the IDE for the operating system we use (Windows, Linux,
and Mac OS X are supported). In addition to the “Arduino 1.0.5” version that
interests us (current version at the time of publication of the guide), a Beta
version is available for the "Arduino Yun" board, a dedicated version for the
Intel "Galileo" and even the sources of the environment, given the open-source
nature of the project.
In the case of Windows, which we will use during this guide, we have the option
of downloading an installer or a simple ZIP file containing everything you need.
To avoid an unnecessary installation process, the second solution is absolutely
the best; in this way, we will simply delete the folder in case we need to update
the IDE or not want to use it anymore.
Once the content of the ZIP file has been downloaded and extracted, we click on
the executable file arduino.exe located in the main folder, and after a few
seconds, we will find ourselves before our eyes the only simple but essential IDE
window completely developed in Java.
The first operation is to select which board of the Arduino family will be used
(in our case, the "Arduino Uno") through the menu Tools "Type of Arduino."
Before connecting our board to the PC through the USB cable, let's take a look at
the IDE to see the features it makes available to us.
Libraries and Examples
First, in the menu File > Example, we have direct access to all the sample
sketches that are available in the examplesIDE folder and divided by category
according to the Arduino functionality that we want to explore.
On the board, there are examples of pin management, on the use of the
analog/digital converter, on all types of connection from serial to Ethernet, and
so on. Furthermore, through the menu Sketch > Import Library, we can add to
our program one or more of the many libraries that the Arduino project makes
available to us (to access the EEPROM, the Ethernet controller, the SD, etc.).
If a library for the management of a particular component or device has been
developed by third parties (or by us), it is possible to add it through the voice
Add Library.
The import operation of a library does nothing but add all the directives
(#include) necessary for the use of the classes and functions that the library itself
makes available to us in our source file. It will be the IDE to take charge at the
time of compilation to include in the generated firmware, not only our code but
also that of the libraries used.
Compilation
Also, in the Sketch menu, there is a Check option that allows us to verify the
correctness of the code (obviously from a syntactic point of view and the
references to the functions used) and then fill it in but without immediately
loading it onto the board.
Shortcuts
Finally, in the menu, Modification finds a series of functions strictly linked to the
editor to simply perform the operations of commenting on the code, searching,
copying/pasting, and indenting.
Some of the most common operations are accessible through a series of buttons
located immediately below the menu bar and which respectively indicate:

Verification: it verifies the written code and compiles it;


Load: it loads the compiled firmware onto the board;
New: allows you to create a new sketch;
Open: allows you to open an existing sketch;
Save: allows you to save the currently open sketch.
Connecting the Card
At this point, we can move on to connecting our board to the PC through the
USB cable. Once the board is connected and powered (even only through the
USB cable), the PC should recognize the presence of the board (e.g., "Arduino
Uno") but needs drivers for correct installation.
Inside the driver's archive folder that we downloaded, you can find the two
executable files (dpinst-x86.exee dpinst-amd64.exe), which allow the installation
of the card on a 32 and 64-bit operating system respectively.
Once the installation is complete, the serial ports already available on the PC
with the one just installed and relative to the Arduino board will be visible in the
menu Tools > Serial Port; we obviously have to select the right port to which the
card is connected. To verify which is the right serial port, we can identify all the
ports installed in the system inside the control panel, where we find an Arduino
Uno (COMx) type port, which is nothing more than a virtual serial port
associated with the USB converter - serial on board.
Debugging at Runtime
A very useful IDE feature is the serial port monitor available in the menu item
Tools > Serial Monitor. As we will see, this tool will prove to be very important
for debugging our runtime programs.
Due to limitations, due primarily to the type of microcontroller, we do not have
the debugging functions that we usually use for other types of applications. So
no breakpoints, step-by-step execution, and real-time display of the value of the
variables.
Using the serial management library, we will have the possibility to send
messages on it and then view them through the monitor; only in this way could
we "debug" and know at runtime where in the program we are or what one or
more variables assume the value to be. Although it may appear a little
rudimentary, it represents the only solution in this case.
We have acquired all the necessary knowledge, from the board to the IDE, to
start developing an application for Arduino.
Enough said, now let's delve deep into the wonderful world of Arduino with
some exciting projects integrated into the chapters of this book.
Chapter One: Controlling the LED
In this chapter, you will learn how to operate the LED and how to connect to the
Arduino. You will also learn and consolidate the basic concepts of programming
(script, program, algorithm, control, condition, loop). These perform the task of
building an electronic system using the Arduino, the contact plate, LEDs, and
resistors. The task consists of pointing the learners of the new chosen pin,
assigning it in using the command pinMode (no pin, OUTPUT), and make the
LED flash (i.e., lights up for 2 seconds, go out for 1 second and repeat the
cycle).
Hardware and software required:

Computer (laptop or desktop)


Arduino IDE software (available for download at
http://www.arduino.org/downloads).
(Optional) mBlock program (available for download at
http://www.mblock.cc/download/) or Scratch for Arduino
(downloadable from the website: http://s4a.cat/).
Arduino UNO board and USB cable AB (for each participant or pair
of participants)
Contact plate,
Resistors with different values (e.g., 220 ohms, 330 ohms, 1,2k
ohms, 2.2 ohms).
Connecting cables
LEDs in various colors,
The projector and the laptop (in parts theory).
What to prepare before the project:

Install the Arduino ide


(optional): install mblock or scratch for Arduino
Check that all computers connected to the Arduino detect it,
Carefully read the script,
Refer to the additional materials (in the "pill knowledge and
inspiration"),
Make yourself tasks in the script,
At each computer station spread the Arduino kit components that will
be used for these classes,
Adjust the degree of difficulty of the task to the needs and
capabilities of the class for which the classes are organized according
to the instructions contained in the script.
Connecting Arduino IDE to run the program and provide basic information
or reminder
Warning! This part of the scenario should pursue all classes (and those carried
out by the following scenarios of II. "Create your own robot") to the extent that
is needed until the basic material will be fixed.
Arduino Connection
Arduino is programmed using a computer. So first, we have to connect the
Arduino to your computer using a USB cable. In the language and development
environment, Arduino IDE created programs which then uploads (forward by
cable) to Arduino. When the program is uploaded (it takes a few seconds), it will
be executed without a break (in the loop).
Once connected, you run the Arduino IDE. We check if any computer has
correctly detected the port that is connected to the Arduino (you need to click on
the top menu "Tools" and then "Port"). Sensitization as learners that sometimes
you may experience problems with the detection of Arduino on your computer
and should then check whether the port is active.
Then we run the Arduino IDE. On the Windows platform, you should search for
the program on the Start menu. Ubuntu Linux platform should find a program in
the Ubuntu menu in the upper left corner of the screen.
The Program Interface (if necessary reminders)
If you are not a native English user, consider using the English language
interface, because it is the language in which we write programs. Programming
languages in the vast majority are English-speaking and generally are not
translated into other languages. English is the primary language of developers,
so you should familiarize yourself with the basic terminology regarding English-
language programming. It comes with dictionaries and educational materials that
are available online. The ability to search for information and solutions to
existing problems is the basic characteristic of a good programmer.
If necessary, we can change the programming language. We make it in the
following way: click File, then Preferences, and select the Settings tab from the
list Language Editor. Generally, the other language version will be File>
Preferences> Settings> Language editor. After the change, close and restart the
program. The change will allow us to compare the messages displayed in
English, as well as switch between languages depending on needs.
After the program, we should see a window with white text, graphic elements,
and blue-green thick black stripe at the bottom of the window. At the top of the
window, we see the following menu:

File: here, you can create new projects (New), save it (Save, Save As), open
(Open, Open Recent), and view examples of ready-made programs (Examples).
Edit : edit menu, allowing you to copy and paste text, and other methods modify
it.
Sketch (Draft) : menu, allowing you to compile your code, or to translate it into
a language understandable to the computer and upload it to the Arduino.
Tools: menu of tools, among others, we can choose the type of Arduino board
that we have, and a USB port to which the plate is connected to your computer.
Help: Help menu.
Below we see the following menu buttons:

First: Verify (Verify) allows you to verify the correctness of the code. The
Arduino check if the code that we wrote is correct, that is, whether it can be
compiled (translated into computer language).
If you select the menu command: File> Examples> 01.Basic> Blink (File>
Examples> 01.Basics> Blink) and you click this button, the black box at the
bottom of the window should display various information written in white font.
This shows that the program can be compiled and sent to the Arduino board.
Second: Upload (Upload) works similarly to the Verify, with the difference that
after the successful compilation immediately sends the code to the Arduino
board when it is properly connected to your computer.
Third: New (New) opens a new empty project.
Fourth: Open (Open) opens a previously saved project.
Fifth: Save (Save) saves the project.
Sixth: located at the end on the right side opens the Serial Monitor (Serial Port
Monitor). This is the window in which we can see what information signals and
sends the Arduino board to your computer and allows us to send signals and
information to the plate. To be able to send and receive signals, we need to plate
in the first program.
Below is the window of our program. Arduino programs are called "sketches."

On the left side is our only tab. In this case, it is a sketch loaded earlier,
Examples, from the menu called Blink (blinking LED module built into the
Arduino).
On the right side is a drop-down icon that allows you to navigate through the
tabs.
Below is the code - the text of our sketch and, below, the window in which the
program Arduino communicates with us, showing errors at compile-time, or
indicate success.
Usually, in the beginning, the window is as follows:

After successful compilation window it will inform us of how much memory is


on the board.
If an error occurred during compilation, a window would show a message in
orange, telling us what mistake we made. The following example is missing the
semicolon at the end of the line:

We Write a Program on the Arduino


This scenario includes instructions on how to write a program for the Arduino.
Use the following tips to discuss the structure of the program.
We create a new project. From the File menu, choose New command, or click on
the New button in the program interface. See if a new window with the
following:
void setup () {
// put your setup code here, to run once:
} Void loop () {
// put your main code here, to run repeatedly:
}
This is the basic structure of the program, the Arduino. Part of the "setup" is
done only once, at the start of the program, and is made part of the "loop" around
the clock, in the so-called loop. If you have already studied the earlier books of
this series, then you should be familiar with the term "loop". The text that
follows the characters // are comments - here you can enter what you want.
Typically, comments are written as information for the programmer, which
carries a part of the program. Comments must be in the same line as the
characters //.
We write a program that will show us the information in the Serial Monitor.
We do this by entering the following code in the window - explanation in the
comments:
void setup () {
// Arduino says that it will be communicated to the computer using a USB
cable
// the abbreviation USB means Universal Serial Bus - hence the name of
the command "Serial":
Serial.begin (9600);
} Void loop () {
// We send the text "Hello World" or "hello world" Arduino to your
computer Serial.println ( "hello world");

// We look forward to 1000 milliseconds, or one-second delay (1000);


}
Then click the Upload button. If errors occur, they should be corrected - the
program should be prescribed very carefully and without errors. Then click the
Serial Monitor button or select the Tools menu> Serial Monitor (Tools> Serial
Port Monitor).
We should see a window which shows "hello world":
Much more convenient to start with is to use the example programs included
with the Arduino (File> Examples) (File> Examples). The programming
language is learned in much the same way as a foreign language - we learn the
words, syntax, grammar, spelling, etc.
And so "Serial" is a feature. It has its sub-functions, which can perform various
operations, for example. "Println" print line, and "begin" starts communication
with the computer. These sub-functions have their own parameters that type in
parentheses. "Println" must know what exactly is to be printed ( "hello world").
"Begin" must know how often to talk to the computer (in this case - 9600 signals
per second).
The loop program works very fast. For example, the processor plate Arduino
Mega operating frequency is 16 MHz. Hz, or Hertz, is a unit of frequency -
defines one cycle (i.e., one event) per second. MHz is megahertz - that is, one
million hertz. So for the example module, Arduino Mega can operate at a speed
of 16 million events per second.
The Task for Practice
Modify the message that Arduino sends to your computer and load the code
again onto the board. Does your message have to be in quotation marks for the
program to work?
Warning! The section on getting started with Arduino is present in all classes.
We recommend to repeat it (as necessary) for each class, to the point where you
will be able to perform basic tasks independently.
Getting to Know LED (using diodes, resistors and the contact plate)
We will start with questions referring to the introduction and the previous books
of this series, e.g.:

What we covered in the last books and the introduction


What is Arduino?
How we controlled the built-in diode?
What do I need to program the Arduino?
Throughout this book, we will focus more on programming Arduino than
electronic, because it's not just writing programs in the Arduino IDE, but also the
construction of electronic circuits. Well, if you already have a basic knowledge
of electronics (it is worth it to recognize the beginning of classes). If not, it is
worth it at this point to introduce and briefly discuss concepts such as electricity,
electric circuit, power source, guide.
After discussing the basic concepts of electronics, we think your knowledge is
sufficient, and now we can discuss sources of light. We can ask questions such
as:

What could be the source of light?


What types of lighting we use in different places (at home, in cars, in
shops, on the streets)?
The answer here should fall, that one of the light sources can be used, for
example, LEDs, in TV remote controls, flashlights, etc. At this point, the LEDs
show the Arduino kits available; in addition, you can use flat batteries 3V (e.g.,
CR2032) and place them between the leg diodes, which will make the LED light
up.
It is at this point, ask yourself the question: whether the light will shine in the
same way, if we apply the opposite leg?
Then we explain how the LED works and where we use it. It is worth noting that
LED has legs of different lengths: the longer one is the anode, and the cathode is
shorter. Plus, always attach the resistor to the anode (longer leg); otherwise, the
LED will not light.
In this part of the project, we will use the contact plate (prototype) and install a
simple system, which will be controlled by the Arduino. But at the very
beginning, we demonstrate to you how it works and how to contact plates
connected to the various elements (e.g., Diode, resistors and connecting cables).
NOTE: Learners often have a problem with connecting wires and small
electronic components. It is worth paying special attention and help yourself if
you are in difficulty with it. Most often, the contact plate systems do not work
because their components are connected incorrectly.
We explained that the additional element in our system is a resistor. But we have
not yet explained its role. It connects the system and checks if it works.
Everywhere should be lit up with LED.
At this point, it is possible to divide the lesson into two parts (the next part of the
project will be executed in the next chapter).
Control the LED Using the Arduino
Here we will no longer control the LED using the Arduino but slightly modify
the system.
Then load both the Arduino already known Blink sample program, which can be
found in the File tab> Examples> 01.Basics> Blink. We observe what is
happening, and you can ask yourself (the LED should blink, as well as the LED
built into the Arduino pin 13).
We explain that using an Arduino controls the digital outputs, in this case, the
LED, but can also control any other electronic device.
Arduino and disconnect the cable hooked to a pin 13 changing to any other
digital pin (you can choose themselves). Let's assume that it will be to pin 6.
Then modify the program in the appropriate places (replace all the places where
it is used to pin 13 6) or to load on the Arduino and see if it works. In this way,
we show you how to assign different pins on the Arduino IDE (you do not have
anything connected to pin 13).
NOTE: Before every change of the contact plate, changing wires, adding new
electronic components disconnect the power from the Arduino (remove the USB
cable AB). Thanks to avoiding accidental short circuits, which can destroy our
Arduino.
Chapter Two: Alarm Siren & Signal Light
In the first part of this chapter, you will build a simple model siren, using the
buzzer (buzzer) and outputs Arduino marked PWM (Pulse Width Modulation,
called. "Pulse Width Modulation"). To know and/or consolidate the basic
concepts of programming (script, program, algorithm, control, condition, loop).
Using the properties of the loop and the PWM regulate the brightness of the
LEDs and buzzer volume. They perform the task: build a siren with the Arduino,
which is an arrangement in which the buzzer to smoothly increase the volume of
the published sound - from silence to a maximum value.
And in the second part, you will learn to build a simple model of traffic lights
using RGB LED that can glow in any color. To know and/or consolidate the
basic concepts of programming (script, program, algorithm, control, condition,
loop). They learn to control LED RGB using the Arduino. They perform the
task: to construct a "system" traffic light with the use of RGB LEDs
programmed by Arduino.
Hardware and Software Required

computer (laptop or desktop)


Arduino IDE software (available for download at
http://www.arduino.org/downloads).
(Optional) mBlock program (available for download at
http://www.mblock.cc/download/) or Scratch for Arduino
(downloadable from the website: http://s4a.cat/).
Arduino UNO board and USB cable AB (for each participant or pair
of participants) contact plate,
220-ohm resistors,
connecting cables
LEDs of different colors buzzer (buzzer) • projector and laptop (in
parts theory).
What to prepare beforehand

install Arduino IDE


(Optional): install mBlock or Scratch for Arduino
check that all computers connected to the Arduino detect,
carefully read the script,
refer to the additional materials (in the "Pill knowledge and
inspiration"),
make yourself tasks in the script,
at each computer station spread Arduino kit components that will be
used for these classes,
adjust the degree of difficulty of the task to the needs and capabilities
of the class for which the classes are organized according to the
instructions contained in the script.
Connecting Arduino IDE to run the program and guide to the basic
information
Warning! For information on how to connect the Arduino, run the Arduino IDE
and Scratch for Arduino, as well as basic information needed to get started with
Arduino, contain scenarios 1 and 2. This part of the book should be repeated
every time the extent that is needed until basic material is fixed.
Test the PWM Output
In this section, we will show you how to work in Arduino connectors PWM
(Pulse Width Modulation). Through the use of connectors, we can simulate
PWM in microcontrollers analog outputs. In this section, you will learn how to
use this function to control various devices.
We are starting with a discussion of analog and digital devices; we can ask
questions such as:

What are digital devices?


What does it mean that a device is digital?
What you know analog devices? Give examples.
Then we explain the difference between digital devices (e.g., computer, mobile
phone) and analog devices (mechanical watch, old radio). We also explain that
by using the digitalWrite () function in Arduino, we can give the pins two states:
high (marked with the number 1 - then the current flows) or low (marked with
the number 0 - the current does not flow).
Computers operate in a similar way, which reads information stored in a binary
system consisting only of 0 and 1. In the case of an analog signal, we can assign
different values from 0 to 255 using the analogWrite () function, which
corresponds to values between 0V and 5V. For more information, refer to the
additional materials.
Two basic control functions in Arduino output pins are:
digitalWrite (0 or 1, HIGH or LOW) - with this function we give a high or
low state for pins 0-13,
analogWrite (0-255) - using this feature gives a value from 0 to 255,
which corresponds to the voltage at the output pin in the range from 0 V
(0) - 5V (255).
It is worth paying attention to the markings pins. In the Arduino pins operating
in PWM mode, they are marked with ~.

Now, we can assemble the system shown in the scheme below.

The system is very similar to that used in the scenario of LED, but it is worth
noting that here is the output pin to pin 9 (of course, you can freely select one of
the six PWM pins).
The LED has two legs of different lengths. The longer is the anode, and the
resistor attaches to it.
Then run a program called Fading (File> Examples> 03.Analog> Fading).
We compile and load both sketch programs for the Arduino. We ask you how the
LED behaves. Is this the behavior of a digital or analog? (The correct answer is
analog because the LED brightens smoothly on and off). We explain to you the
LED action in this case, and we can refer to the example scenario of LED, where
he steered digitally.
Install the System with LED
Loop "for"
In this section, we analyze the activities with how the fading program works.

We discuss, in turn, all the elements of the code. We pay attention to the loop
"for" and analogWrite function () contained within this loop. We explain how to
operate loops - here, and we introduce the concept of the "for" loop. It is worth
noting that in the main loop Arduino, there are two loops "for" succession: the
first is responsible for brighter LEDs, and the way her darker. For more
information about the "for" loop can be found in the supplementary materials.
Loop "for" works in this way that the operations contained within the loop, the
program performs a specific number of times for us. In this case, we have three
parameters. The first parameter is a variable fadeValue, which is initialized to 0,
as we begin to clear LED 0. The second parameter is the condition that
determines when the loop will work. In this case, we break the loop when we
reach the maximum value of 255.
The third parameter is the number by which raise or lower the value of the
variable fadeValue with subsequent cycles "for" loop. Here it is expressed with +
=, which represents an increase of 5 each time through the loop (i. Successively:
0, 5, 10, 15, 20, etc.). Symbol - = (second "for" loop) represents a decrease of 5
(ie. The following order: 255, 250, 245, 240, etc.).
Then we give you a task: you need to modify two parameters "for" loop and see
how it affects the behavior of the LEDs. Here is a hint, which parameters can be
changed and what is affected by:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5)
Mount Arrangement with Buzzer
When you know the action of PWM connectors and tested their effect on the
LED, it is now down to you check to see how they will operate in this mode, the
other actuators (output devices). Together with you, we assemble the following
simple arrangement on the contact plate using a buzzer (beep).

Once again, load a program from the previous point and check how the buzzer
behaves. Ask yourself the question, do you see a difference in the behavior of
the buzzer and LEDs. Or maybe there is no such difference? The buzzer should
behave the same way, or - alternately - quieter and louder sound.
As in the previous part of the chapter, we gave you a moment to independently
manipulate the parameters "for" loop testing and how it affects the behavior of
the buzzer.
The Signal Light
Hardware and Software Required

Computer (laptop or desktop)


Arduino ide software (available for download at
http://www.arduino.org/downloads).
(optional) mblock program (available for download at
http://www.mblock.cc/download/) or scratch for Arduino
(downloadable from the website: http://s4a.cat/).
Arduino Uno board and USB cable ab (for each participant or pair of
participants)
Contact plate,
220-ohm resistors,
Connecting cables
LED RGB
The projector and the laptop (in parts theory).
What To Prepare Before Starting

Install Arduino IDE


(Optional): install mblock or Scratch for Arduino
Check that all computers connected to the Arduino detect,
Carefully read the script,
Refer to the additional materials (in the "Pill knowledge and
inspiration"),
Make yourself tasks in the script,
At each computer station spread Arduino kit components that will be
used for these classes,
Adjust the degree of difficulty of the task to the needs and
capabilities of the class for which the classes are organized according
to the instructions contained in the script.

Connecting Arduino IDE to run the program and guide the basic
information
Warning! For information on how to connect the Arduino, run the Arduino IDE
and Scratch for Arduino, as well as basic information needed to get started with
Arduino, contain scenarios 1 and 2. This part of the book should be repeated
every time you need it until the basic material is fixed.
Getting to Know the RGB LED
In this part, you will learn the RGB LED that can glow in any color, as it
operates in accordance with the RGB system ®, allows for mixing and matching
different colors.
This kind of LED RGB LED consisting of three smaller LEDs:

red (R - called. "Red"),


green (G - called. "Green")
and blue (B - called. "Blue"). H
hence comes the name "RGB" - from the names of colors. The LED has four
legs, three of which are responsible for the individual colors, and the fourth is a
common anode or cathode. RGB LEDs are in the two versions, but in this case,
we will discuss RGB LEDs common cathode.
Providing a specific voltage to run the legs corresponding color.
Using the PWM connectors and analogWrite function (), we can control the
brightness of each channel. By setting different voltages on all three channels
can be freely mixed color components, thus obtaining a full RGB color palette.
We can start with the concept of colors and screens/displays.
We can ask these questions to yourself:

You know what types of displays and/or screens? Where are they
used? In what devices?
How does the display?
What is a pixel?
What happens when you mix different colors, for example. Poster
paints?
We collect and summarize all the answers. We introduce the concept of an "RGB
color palette." We order the knowledge of the formation of colors and color
mixing. We explain that almost every screen (TV, monitor, smartphone, etc.) It
contains a miniature pixel. Each of these pixels can glow in three colors (red,
green, blue), and by mixing these colors, we can get any color. For more
information, refer to the additional materials.
In this section together to connect RGB LED Arduino according to the following
scheme:
Note: for each leg, a diode corresponding to a given color of a resistor connected
in series (maybe 330 ohms). As previously mentioned, LED RGB is constructed
from three smaller diodes and each of which controls independently. However,
this LED RGB is a common cathode and thus needs only one connected to the
wire in our Arduino minus (GND pin). It should help you with pinning because
there may be problems with the distribution of feet RGB LEDs and plugging the
holes in the contact plate.
After checking all the connections on the Arduino or to load the following
program (https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-an-
rgb-led-89bcae)
const byte COLOR_BLACK = 0b000;
const byte COLOR_RED = 0b100;
const byte COLOR_GREEN = 0b010;
const byte COLOR_BLUE = 0b001;
const byte COLOR_MAGENTA = 0b101;
const byte COLOR_CYAN = 0b011;
const byte COLOR_YELLOW = 0b110;
const byte COLOR_WHITE = 0b111;

const byte PIN_LED_R = 9;


const byte PIN_LED_G = 10;
const byte PIN_LED_B = 11;

void setup() {

pinMode(PIN_LED_R, OUTPUT);
pinMode(PIN_LED_G, OUTPUT);
pinMode(PIN_LED_B, OUTPUT);
displayColor(COLOR_BLACK);
}

void loop() {

displayColor(COLOR_RED);
delay(1000);

displayColor(COLOR_GREEN);
delay(1000);

displayColor(COLOR_BLUE);
delay(1000);

displayColor(COLOR_MAGENTA);
delay(1000);

displayColor(COLOR_CYAN);
delay(1000);

displayColor(COLOR_YELLOW);
delay(1000);

displayColor(COLOR_WHITE);
delay(1000);
displayColor(COLOR_BLACK);
delay(1000);
}

void displayColor(byte color) {

digitalWrite(PIN_LED_R, !bitRead(color, 2));


digitalWrite(PIN_LED_G, !bitRead(color, 1));
digitalWrite(PIN_LED_B, !bitRead(color, 0));
}

Now we need to enter the code manually or prepare it in advance and distribute
it on our computers. After downloading the program, we observe how light
behaves. Then, we analyze the program code. We explain that each pin is
responsible for a different color. We show, at which point, where to turn on and
turn off the individual channels (where it is excessively high or low). We give
you the task to decode and place the code that is responsible for a particular
color displayed by the RGB LED. This makes it much easier to understand the
operation code and the entire system.
Recovery of the Diode RGB
We begin with a brief reminder of the material from the previous section
activities and play system constructed in the previous classes. You are
connecting RGB LEDs and reload the program.
LED Control Using PWM Connector
In this part, we will control the RGB LED using analogWrite (), on which more
information can be found in the scenario dedicated PWM connectors (Scenario
3: "Siren"). Just as in that case, here we can also assign a value between 0-255,
and thus simulate analog output. It is noteworthy that the corresponding hook
wires to the output pins Arduino. All the time, do not change the system and
leave a diode wired to pins 9, 10, 11 (terminals PWM).
Now we need to write a new program that allows simple adjust the brightness of
each channel. It is worth noting that the command digitalWrite () to change the
analogWrite ()because otherwise, we will not be able to assign analog values in
the range 0-255. Below is a sample program :
(https://www.programmingelectronics.com/tutorial-10-fade-an-led-with-pulse-
width-modulation-using-analogwrite/)
/*
Fade

This example shows how to fade an LED on pin 9


using the analogWrite() function.

This example code is in the public domain.


*/

int led = 9; // the pin that the LED is attached to


int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by

// the setup routine runs once when you press reset:


void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:


void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);

// change the brightness for next time through the loop:


brightness = brightness + fadeAmount;

// reverse the direction of the fading at the ends of the fade:


if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
Now briefly review the program code and try to see where you can
independently change the parameters and the same color mix.
Construct a Simple System of Traffic Lights
Try to create a simple traffic light simulator. RGB LED light should be the same
as the beam in the following sequence: light green, yellow, red, red, yellow,
green.
Below is an example algorithm - a sequence of lights, where you can be inspired
to create the program:
green light - yellow light 15 s - 3 s red light
- 15 s red light and yellow (simultaneously)
- 2 s
All in including the main loop and thus obtain a continuous operating traffic
light. RGB LED built into the system should be lit in different colors in the
following sequence: light green, yellow, red, red, yellow, green.
Chapter Three: MDF Robotic Arm Kit & Recording
of Micro SD Card with Arduino
In the first part of this chapter, we are going to talk about the MDF Robotic Arm
Kit. This kit consists of all the parts necessary to assemble a genuine robotic
arm, with two control axes and a claw. All movements are controlled by four
servo motors, which are not included in the kit. Servants are responsible for
controlling the movements of the arm on its different axes and the claw.
It is the ideal product for makers, electronics lovers, and anyone who wants to
assemble and have their own robotic arm. All pieces are laser cut, based on MDF
boards. It was thought to be used in projects with Arduino, Pic, ESP, and other
microcontrollers. We will show you how to program the Arduino to control the
arm satisfactorily.
MDF Robotic Arm Kit with Arduino
The MDF Robotic Arm is a typical mechanical arm developed for robotics
applications. Made of 3mm thick MDF and modular and easy to be assembled, it
is ideal for prototyping and validation projects of robotic systems. This is the
ideal equipment to be the first robotic arm for those who are starting out in the
world of robotics.
The parts are all laser cut, and the screws, nuts, and other assembly components
(except the servos) are all included in the kit. Anyone can assemble it. Just
follow the instruction manual carefully from the manufacturer.

The Figure above shows the robotic arm assembled with the four servos to
control its joints. The figure just below shows the set of parts that make up the
kit. The parts must be carefully assembled for the arm to work properly.

Servos for Motion Control


All articulations of the Robotic Arm are moved by a set of 4 TowerPro SG90
servo motors. By sending commands to each servo, it is possible to control the
position of its axis of rotation to control the joints of the mechanical arm in the
desired way. The joints perform movements of up to 180 °. In addition, the arm
also has a claw of approximately 60mm to hold and release small objects.
It is common for projects where servomotors are used that they are connected
directly to the Arduino. In this case, there are four servos, so it is necessary to
have an external power supply, as the Arduino is not able to supply all the power
for the set of 4 motors. We will use a protoboard source in our project, as will be
explained later.
Applications
The applications of this robotic arm in MDF are mainly:

School and college projects on robotics;


Prototypes of products and equipment that require a robotic arm;
Validation of concepts and products;
Automation of simple processes;
Teaching and learning robotics;
Because it is a benchtop industrial applications or commercial processes are
more restricted. Although it is a great tool to validate concepts and test
algorithms for more robust robotic arms.
Project Description
In this project, we will assemble the Robotic Arm kit in MDF and program an
Arduino UNO with a Sensor Shield V5.0 to control the four-arm servos. As the
Arduino on the USB does not supply power to all servos, we will use an external
9V source to power the servo drives. With Arduino, we will use the application
developed here on the book as a base software to control a robotic claw. The
robotic claw of this other project is different from that used in the robotic arm.
Made of acrylic and sold only as a claw (without larger components like the
mechanical arm), the claw is applied to hold and release objects and can be
affixed to different surfaces.
This base software uses a potentiometer to read the signal commanded by the
user, and in proportion to that signal modulates the PWM output applied to the
servomotor. In our project with the mechanical arm, as there are four servos, we
will expand this project to read four potentiometers, each one to activate one of
the servos of the mechanical arm.
Hardware Needed
For our assembly, we will need the following components:

1 Arduino Uno R3 + USB Cable


1 Shield V5 sensor for Arduino;
1 9V/1A source to power the Arduino;
4 9g Tower Pro Micro Servos;
4 10k potentiometers;
1 Robotic arm kit in MDF for Arduino;
1 Protoboard 400 points
Jumpers - Male/Female
With the manual available in the introductory part, there is not much secret of
assembling the project, just follow the instructions in the assembly manual
carefully. With the arm ready to be connected, we have to mount the Arduino to
control the servos. See the figure below:
Software
Our software must read four potentiometers, each one to control a servomotor.
Thus, in our firmware, we must use four analog channels to read and four PWM
channels, each for a different servo motor. Since there are many control signals
connected to the same circuit, the servos may be unstable due to noise.
Especially if the whole assembly is done on a protoboard instead of the sensor
shield. Make sure that Sensor Shield is powering the protoboard by 5V and
GND, as well as the VCC and GND of power for each pot.
In the code below, we have the definition of the reading pins, each for a
potentiometer, and the declaration of four Servo type objects. To declare objects
of the Servo class, it is necessary to include the Servo.h library .
(https://www.arduino.cc/en/reference/servo)
#define potpin1 2
#define potpin2 3
#define potpin3 4
#define potpin4 5

#include < Servant .h>

MyservoBase Servant; // Servo object to control the base


Servo myservoGarra; // Servo object to control the claw
Servo myservoAltura; // Servo object to control arm height
Servo myservoPr Depth; // Servo object for depth at arm's height

int val; // variable to read the value from the analog pin

void setup ()
{
// Associates each object with a myswebase
pwm pin . attach (3);
myservoClaw. attach (5);
myservoHeight. attach (9);
myservo Depth. attach (11);
}

void loop ()
{

val = map ( analogRead (potpin1), 0, 1023, 0, 180);


myservoBase. write (val);

val = map ( analogRead (potpin2), 0, 1023, 0, 180);


myservoClaw. write (val);

val = map ( analogRead (potpin3), 0, 1023, 0, 180);


myservoHeight. write (val);

val = map ( analogRead (potpin4), 0, 1023, 0, 180);


myservo Depth. write (val);

delay (100);
}
In the void loop function, we will always update the values read from the
potentiometers and use them as a reference to set the position of each servo.
Thus, any control mode on the knob of one of the four potentiometers will be
converted into a change of position on one of the four servos. In this way, we can
separately control the base of the arm, as well as the joints (height and depth of
the arm) and the opening and closing of the claw.
Notice how we read each analog pin directly into the map () function, passing
the result of the reading as an argument to the map () function.
With the MDF Robotic Arm kit and four TowerPro SG90 micro servos, you can
implement a robotic arm of your own. A practical aspect of the assembly is the
noise that the assembly on the protoboard and possible badly attached contacts
can cause. Leave all connections firmly and check that all components are well
referenced to the GND.
A practical tip when assembling the arm following the manufacturer's manual:
None of the screws should be tightened too much. As it is a set of moving parts,
you must use the screws only to join the parts, applying the minimum amount of
force necessary. The same goes for the screws used to secure the servo motor
“horns.” When these screws are too tight, it can happen that the servo's rotation
may even stop. Therefore, on all screws, use as little force as possible, just
enough to keep the parts fixed.
In this second and final part of the chapter, we are going to learn how to write
data and read information using a Micro SD card with Arduino. Several SD card
shields are available on the market to connect these handy memory cards to the
Arduino. In this section, we will use the Micro SD Card Adapter connected to an
Arduino Uno.
The micro SD card with Arduino allows the development of data loggers.
Devices that store data collected from sensors and other information for analysis
and graphing.
Recording of Micro SD Card with Arduino - Make your Datalogger!
SD and micro SD cards differ only in size, as the name suggests. Both are cards
with integrated Flash memories. The memory size varies a lot, and today you
can find cards with tens of GB.
The figure below shows the SD card adapter that we are going to use in our
project. There are also specific datalogger shields integrated with RTC (Real
Time Clock) for telemetry and sensor monitoring applications.
The module is efficient and compact. In addition to being practical to use and
integrate with hardware and control systems, it was developed to optimize the
work of designers, students, and hobbyists in the construction of data logger and
data storage systems.
Basically, the module has an entry for Micro SD cards with all six interface pins
available for communication with Arduino. Through the SPI pins
(communication protocol used to read and write data in the card's Flash
memory), we can turn on the Arduino and send information to be stored. It is
also possible to perform reading procedures to present the data recorded on
displays as displays or on the serial interface.
The SPI interface that allows you to read and write data to Flash memory is
based on six channels:
Pin description Other names
CS Slave Select SS, nCS, nSS
SCK System Clock SCLK, CLK
MOSI Master Our Slave In SDO, DO, SO
MISO Master In Slave Out SDI, DI, SI
VCC Positive food
GND Earth
The module specifications are as follows:

SPI Communication;
Reads and Writes in FAT32;
Supply Voltage: 4.5V to 5V;
Dimensions (LxWxH): 42x24x3,5mm;
Because the SD card can be removed and inserted whenever necessary to
transfer files to the computer and plot graphics for analysis, the module is ideal
for developing data loggers.
Applications
The applications of dataloggers are diverse. Any system in which it is necessary
to store data for future analysis are candidates to have received the integration of
a datalogger. Among the applications, we can mention:

Telemetry and monitoring of drones;


Telemetry and monitoring of vehicle prototypes;
Monitoring of sensors and machines for predictive and preventive
maintenance;
Monitoring of energy consumption;
Any other system that requires a data logger;
Project Description
For this project, we will develop the following:
”Read an ultrasonic sensor and record the distance readings (between the
sensor and an obstacle) provided by the sensor on a micro SD card.”
Hardware Aspects
From a hardware point of view, we will need the following materials:

Protoboard;
Ultrasonic Sensor HC-SR04 ;
Arduino UNO;
PIR motion and presence sensor ;
3 3K3 resistors;
3 2k2 resistors;
Jumpers for connection;
The important point is that although 5V powers the adapter module, the MISO,
MOSI, and SCK signals are 3.3V. In other words, it is necessary to use a CI to
convert the logic levels or use three voltage dividers to lower the Arduino's 5V
signals to 3.3V on the SD card side. The solution with voltage dividers, as it is
simpler and more practical, will be the one adopted in our project.
Having said that and having all the components, we can assemble the circuit as
shown in the figure below:

If you still do not know the operation and implementation of projects with
ultrasonic sensors, visit this exclusive post and learn all about the HC-SR04
sensor and how to do projects with it.
Software Aspects
Let's understand the software developed that makes the recording on the card.
See the code below:
#include < SPI .h>
#include < SD .h>
#include <stdlib.h>

// Variables for SD card


const int CS = 4;
char dataString [7];
File meuArquivo;

// Variables for ultrasonic sensor


int PinTrigger = 3; // Pin used to trigger the pulses of the sensor
int PinEcho = 2; // pin used to read the
float sensor output TempoEcho = 0;
const float SoundSpeed = 340; // in meters per second
const float SpeedSom_mporus = 0.000340; // in meters per microsecond

void setup ()
{

// configures the Trigger pin as an output and initializes with a low


level
pinMode (PinTrigger, OUTPUT );
digitalWrite (PinTrigger, LOW );
pinMode (PinEcho, INPUT ); // configures pin ECHO as input
pinMode (CS, OUTPUT );

Serial . begin (9600);


delay (100);

Serial . print ( "Initializing SD card ..." );


if (! SD . begin (CS))
{
Serial . println ( "Initialization Failed!" );
return ;
}
Serial . println ( "Initialization finished" );

void loop ()
{
float val;

// Sends pulse to trigger the sensor


Ultrasonic Pulse Trigger ();
// Measure the duration of the signal at the reading pin (us)
TempoEcho = pulseIn (PinEcho, HIGH );
val = CalculaDistancia (TempoEcho);
// add the last reading to the recording string
dtostrf (val, 5.2, dataString);

if (myFile = SD . open ( "log.txt" , FILE_WRITE ))


{
Serial . println ( "Recorded" );
Serial . println (val);
// Write on the SD card using the object meuArquivo
meuArquivo. println (dataString);
myArchive. close ();
}
else
{
// if the file doesn't open, it shows error message
Serial . println ( "Error opening log.txt" );
}

delay (2000);
}

// Function to send the trigger


void trigger UltrasonicPulse ()
{
// To make the HC-SR04 send an ultrasonic pulse, we have
// to send to the trigger pin a high level signal
// at least 10us duration of
digitalWrite (PinTrigger, HIGH );
delayMicroseconds (10);
digitalWrite (PinTrigger, LOW );
}

// Function to calculate the distance in meters


float CalculaDistancia ( float tempo_us)
{
return ((time_us * SpeedSound_mporus)/2);
}
Variable Declaration and Void Setup () Function
For this project, we need to add three libraries:

SPI.h
SD.h
STDLIB.h
The first two are to record the SD card. The last one is so that we can use the
dtostr () function, which converts a float to a string. To record the card, we
declare an array of characters and an object of type FILE, which we call
myArchive.
The other variables are related to the ultrasonic sensor and the IO settings. To
know the functions and how the part of the software related to the ultrasonic
sensor works, access this article . (https://lastminuteengineers.com/arduino-
sr04-ultrasonic-sensor-tutorial/)
In the void Setup () function, we initialize the serial port and the SD card using
the SD.begin (CS) function, where CS is the pin on which the ChipSelect signal
of the card is connected.
Void Loop () function
In the void loop () function, the procedure consists of monitoring the output of
the HC-SR04 sensor, reading its values and saving them on the SD card in a .txt
file with the name log.txt. After reading the sensor, we convert the value to a
character set using the dtostr () function, and right after that, we open the log.txt
file with the SD. Open () function and write the string to the file using the
myArchive function. .println (). After the writing procedure, we close the file
with the SD.close () function.
Putting it to Work!
See how the final result should look like:
Complete Assembly 2

Complete Assembly 1:
Log.txt file:

Serial output:

In this example, we made a simple data logger to monitor the signals from an
ultrasonic sensor. All sensor readings, which were taken at a rate of 2 seconds,
are recorded on the micro SD card using the SPI protocol. The adapter can be
easily integrated into any electronic system. The micro SD card can be easily
removed and taken anywhere else so that the data can be used to plot graphs and
build tables.
Chapter Four: Home Automation: Presence Sensor &
Automation of Irrigation System with Arduino
In the first section of this chapter, we will assemble a typical home automation
system. We will use a PIR presence sensor to turn a lamp on and off. The sensor
is connected to an Arduino and triggers a signal indicating the presence of
someone within a certain radius. Reading the signal from the sensor, we will
know if someone is nearby and turn on a lamp by activating a relay module.
Home Automation: Presence Sensor with Arduino
The PIR motion sensor we are going to use is model dyp-me003, manufactured
by elecfreaks. This sensor is capable of detecting movement of objects within a
radius of up to 7 meters, a great distance to be able to turn on lights and activate
other automation devices on site.
The operation of the sensor is extremely simple. If an object enters the detection
range, an output is activated at a high level, and if there is no movement detected
within the range, the output is at a low level. In the summer, the detection range
may be slightly less due to the higher temperatures. The datasheet provides this
and some other additional information. We strongly recommend that you know
the component's datasheet.
Operation of PIR Presence Sensors
PIR is short for passive infrared. The main component is a pyroelectric sensor.
This type of sensor has the property of detecting variations in the infrared
radiation it receives and producing an electrical signal as an output. In general,
the sensor is encapsulated next to a transistor to amplify the electrical signal
generated when variations in radiation occur in the environment.
The pyroelectric sensor captures infrared radiation through a fresnel lens, which
divides the sensitive area of the sensor into sectors with lenses of different
characteristics. The PIR sensors are stimulated only by some energy sources,
such as human and animal heat, for example. A passive sensor is said because it
does not emit any signal; it only receives the radiation and is stimulated by it.
Dyp-me003 Specifications
The elecfreak model dyp-me003 is simple and small. It is very easy to use and
very flexible for prototyping projects and residential assemblies. The sensor
module has a small yellow potentiometer to adjust the waiting time for
stabilization and also to adjust its sensitivity. Stabilization can vary between 5 to
200 seconds.
The basic specifications of the sensor are:

SENSITIVITY AND TIME ADJUSTABLE;


OPERATING VOLTAGE: 4.5 - 20V;
OUTPUT VOLTAGE: 3.3V (HIGH) - 0V (LOW);
DETECTABLE DISTANCE: 3 - 7 M (ADJUSTABLE);
DELAY TIME: 5 - 200 SECONDS (STANDARD TIME: 5
SECONDS);
DIMENSIONS: 3.2 X 2.4 X 1.8CM;
WEIGHT: 7G;
The image below shows the sensor that we are going to use turned upside down.
The two potentiometers for adjusting stabilization and sensitivity are clearly
visible, each on the side of an electrolytic capacitor.

The image below shows the main sensor element. Generally, the module is
covered with a protective film, as in the highlighted image of this post. In the
image below, the film was removed to expose the pyroelectric element.
Applications
The PIR sensor is ideal for home, commercial, and security automation projects.
It is widely used in:

Security products;
Devices with presence detection;
Automatic lighting;
Automatic activation of buzzers, lamps, and home and commercial
automation circuits;
Automation and industrial control;
Project Description
In our project, we are going to use the ElecFreak PIR sensor to drive a lamp
through a relay module. To learn more about the relay module, you can access
all other resources of the references in this book. The project consists of the
following:
“Read a PIR (Passive Infrared) sensor to detect movement within a radius of up
to 7 meters and activate a lamp if the movement is detected. After a certain time
after the last detection, turn off the lamp.”
Hardware Aspects
To assemble this project, we will need the following components:
Sensor DYP-ME003;
Relay module 4 channels and 5V;
Protoboard;
Lamp and holder;
Arduino Uno;
The assembly below shows how the circuit should be made. The relay module
does not require the use of transistors to amplify the Arduino signal to activate
the lamp. The relay module must be connected with the common pin on one of
the socket terminals, and the NA pin on one of the lamp terminals. The other
terminal of the lamp must be connected to the other terminal of the socket.

Software Aspects
The software consists of constant monitoring of the PIR sensor to find out if the
sensor has identified any infrared variation (movement of people or animations).
We declare the variables to determine the reading pins (PIR sensor output) and
output pins (activates the Relay module), and in the void loop () function we
read the PIR sensor output signal, which is digital, that is is, or is it high level or
low level.
#define Relaymodule 7
#define ThesensorPIR 8

int ReadingSensor;

void setup ()
{
pinMode ( trigger it , OUTPUT );
pinMode (LesensorPIR, INPUT );
Serial . begin (9600);
}

void loop ()
{
//
Read the presence sensor ReadingSensor = digitalRead (LesensorPIR);

// No
if motion detection (ReadingSensor == LOW )
{
digitalWrite (trigger, LOW );
}
// There is movement detected - turn on lamp
else
{
digitalWrite (trigger it, HIGH );
}
delay (2000);
}

We use a delay in the loop function and depending on the setting time you use it
will be necessary to change this time
Putting it to Work!
Let's see how the assembly is ready! The figure below shows the entire circuit
connected and assembled to light the lamp.
Mounting with focus on the PIR sensor:

Complete assembly:

With this section, you now know how PIR presence sensors work and how to
integrate them into any home automation project or any other application you
want. The sensor is simple to use and is sold in the United States.
Now in this second and final section of this chapter, we are going to talk about a
subject that interests a lot of people: Irrigation systems. From small gardens to
larger sites and areas, knowing how to automate your own irrigation system
gives you flexibility and allows you to make customized solutions for your
needs. For these systems, it is necessary to measure mainly soil moisture and
temperature. As an actuator to release water to the pivots, a valve is required.
And, of course, a microprocessor system to read the sensors and control the
valve according to the soil moisture and temperature levels
Automation of Irrigation System: Humidity Sensor and Solenoid Valve
The two main components that we will use in this project are:

1. Soil moisture sensor module ;


2. Solenoid valve for water inlet ;
The soil sensor is a probe that measures the humidity level of the earth. With it,
you can know when it is necessary to turn on irrigation to regulate soil moisture.
The solenoid valve is the actuator component of the system. We use a 12V signal
to open and close the valve, allowing water to flow or blocking it.
Soil Moisture Sensor Module
The soil sensor detects humidity variations at the location where the probe is
buried. The module has two outputs, one analog and one digital. The analog
output is the output of the sensor itself, and it varies according to the soil
moisture. The digital output is that of an LM393 comparator, which provides
only high and low levels. For higher precision controls, it is recommended to use
the analog output so that you can scale various actuation ranges for your system.
Using the digital output, you only do an ON/OFF control based on two sensor
reading limits.
The working principle is simple. The module has two rods with two long
contacts. It is a sensor whose electrical resistance varies according to the
humidity of the soil. Thus, the wetter the soil, the lower the resistance of the
sensor. The drier, the greater the resistance of the sensor.
With the digital output (D0), the basic operation is as follows: When the
humidity is low (dry soil), the output is at a high level. Otherwise (wet soil), the
outlet is at a low level. A small potentiometer embedded in the sensor is used to
adjust the reference limits. The comparator circuit can be seen in the image
below:
Ground Sensor Module Specifications
The humidity sensor specifications are:

Operating Voltage: 3.3 V - 5V;


Sensitivity adjustable via potentiometer;
Digital and Analog Output;
Led indicator for voltage (red);
Led indicator for digital output (green);
Comparator LM393;
PCB dimensions: 1.5 × 3 cm;
Probe dimensions: 2 × 6 cm;
Pinout:

GND;
VCC;
A0: Analog output;
D0: Digital output;
The analog output ranges from 300 mV to 700 mV on wet soil and from 700 mV
to 950 mV on soaked soil or pure water. On dry or slightly humid soil, it varies
from 0 to 300 mV. We connected the two outputs of the sensor module on the
Arduino to perform the readings. Based on them, we act on the solenoid valve.
We strongly recommend reading the sensor datasheet.
Solenoid Valve
The Solenoid valve is used to control the flow of water. When powered with 12V
DC, it opens and allows water to flow. When de-energized, it closes and cuts off
the flow. Its operation is based on a coil (solenoid), which, when energized,
generates an electromagnetic field responsible for moving the valve plunger.
Specifications:

Operating Voltage: 12V DC


Body material: thermoplastic;
Metallic parts: galvanized steel;
Membrane: rubber (standard);
Entrance Opening: 3/4 inch;
Outputs: 3/4 inch;
The valve is small and simple, ideal for use in gardens and small irrigation
systems. Together with the soil sensor module, it is a piece of ideal equipment
for hobbyists and makers.
Applications
The humidity sensor and valve applications are mainly for water flow control
systems, such as:

Automated drip irrigation;


Traditional garden irrigation;
Irrigation of plant pots or beds with sensitive plants;
Control of water flow;
Acquisition of data on soil for monitoring and analysis;
Hardware Aspects
For our assembly, we will need the following components:

Soil sensor module;


Solenoid Valve;
Arduino Uno;
External 12 V DC source;
Jumpers and USB cable;
5V Relay Module;
The relay module is used to activate the solenoid valve because, in addition to
the Arduino operating at 5V, it does not have enough power to supply the valve.
If you still don't know how to use the relay module, access this post on relay
modules and lamp drives with Arduino. The assembly is shown below:

Software Aspects
Let's see how the software works to monitor the sensor and activate the solenoid
valve.
We define the pins that we will use for reading and activate the relay with three
directives at the beginning of the code. In the void setup function, we only
initialize the serial port so that we can communicate and configure the inputs and
outputs. The main part is in the void loop () function. Here we are going to read
the two outputs from the humidity sensor. The analog output is read with the
analogRead function (Analog pin), and the digital output of the sensor is read
with the digitalRead function (Digital pin).
We present the reading data on the screen and then make the comparison to see if
we should close or open the valve. If the humidity sensor is at a high level, it
means that the soil is dry, so we have to activate the relay to open the valve. The
relay is then activated by sending a GND signal. If the sensor output signal is
low, it means that the soil is moist enough, and we don't need to open the valve
anymore. So, we send a high-level signal to the relay to turn the relay off and de-
energize the valve.
#define pinDigital 13
#define pinAnalog 0
#define pinRelay 7
float AnalogOutput = 0;
float voltage = 0;
int ReadingSensor = 0;

// the setup routine runs once when you press reset:


void setup () {
pinMode (pinDigital, INPUT );
pinMode (pinRelay, OUTPUT );
Serial . begin (9600);
}

// the loop routine runs over and over again forever:


void loop () {

AnalogOutput = analogRead (pinAnalog);


ReadingSensor = digitalRead (pinDigital);
float voltage = AnalogOutput * (5.0/1023.0);
Serial . println ( "Sainda analog" );
Serial . println (voltage);
Serial . println ( "Digital Sainda" );
Serial . println (ReadingSensor);

if (ReadingSensor == HIGH )
digitalWrite (pinRelay, LOW );
else
digitalWrite (pinRelay, HIGH );

delay (2000);
}
Note that we connect the relay to the valve using the COMMON and NA pins,
that is, we use the normally open contacts. If you use normally closed contacts,
your logic will be slightly different. To rectify how to use the relay module,
check our post where we explain this component better.
Putting it to Work!
Complete Assembly:

The output on the serial interface presents the following information:

Note that at the output of the serial interface above, we are reading a value of 5
mV, which means that the soil is dry, with virtually no moisture. Because of this,
the digital output is at a high level, as shown on the same interface.
With this simple assembly, you can assemble an automated irrigation system
with your own hands. You can adapt the wire sizes to make a better system for
your plants or gardens. You can also use more than one soil sensor to be able to
take readings from various points, obtaining a more accurate map of humidity
over a larger area.
Chapter Five: Flammable Gas Sensor & RFID Kit
with Arduino
In this first part, we will learn how to use a sensor to assemble a system to
identify fire spots and flammable gases. For this, we will use an MQ 2 sensor,
which identifies gases such as methane, natural gas, hydrogen, smoke, among
others. We can use this sensor to validate air monitoring systems, as well as
prototype systems for checking air quality and the presence of hazardous gases.
Although easy and practical, it is a sensor indicated for experimental and
validation purposes (use in bench and laboratory). The author and the publisher
are not responsible for any damage related to its misuse in real systems.
The MQ-2 Sensor
The main component of this assembly is the MQ 2 sensor, shown in the figure
below:

This sensor is capable of detecting concentrations of flammable gases and smoke


in the environment. It is a very small and simple module, very practical to be
integrated into home automation projects or prototypes of electronic products. A
small trimpot adjusts the maximum allowed concentration level on the module.
When any gas exceeds this level, the digital output of the sensor (D0) is
activated at a high level. At normal concentrations (below the adjusted value in
the trimpot), the output remains at a low level.
The module also has an analog output (A0), which allows measuring the
variation in the concentration of gases in the air more accurately. To use the
analog output, you need an AD converter, like the one Arduino makes available
on its analog channels.
Despite being easy and practical to use, the sensor is not suitable for use in real
fire safety systems. The manufacturer recommends it for experimental purposes
and product validation. The author and the publisher are not responsible for any
damage caused by their use. If you want to develop a real security system
against fire or dangerous gases, we recommend researching and using industrial
and more robust sensors.
MQ-2 sensor with LCD:

In the end, we will have a montage like the one above.


Specifications
The sensor specifications are as follows:

Detection of flammable gases: LPG, Methane, Propane, Butane,


Hydrogen, Alcohol, Natural Gas and others;
Smoke detection;
Concentration levels for detection: 300-10,000 ppm;
Operating voltage: 5V;
Comparator LM393;
Led indicator for voltage;
Led indicator for digital output;
The module has four pins. There are two for power supply (VCC and GND) and
two output signals, one digital and one analog:

VDC: 5V;
GND: Land/Reference;
D0: Digital output;
A0: Analog Output;
We strongly recommend reading the MQ 2 datasheet .
(https://www.pololu.com/file/download/MQ2.pdf?file_id=0J309)
Applications
According to the datasheet, the MQ 2 sensor can be used in the following
applications:

Validation of domestic gas leak identification systems;


Development and validation of flammable gas detectors;
Development and validation of portable flammable gas detectors;
Prototyping of fire protection systems;
Project Description
In this project, we will see the following:
Use an MQ-2 sensor to identify high concentrations of flammable gases or
smoke and trigger a warning alarm (buzzer). At the same time, we will show a
warning message on a 16 × 2 LCD
An interesting point is the following. There are several sensors in the MQ series.
For example, MQ-3, which detects alcohol, MQ-7, which detects carbon
monoxide, MQ-4, which detects methane gas, and several other models for
specific types of gases. All of them have similar pinouts (VCC, GND, Analog
Output, and Digital Output). Thus, the circuit you know here is extensive for all
these other sensors. Just be careful to confirm the pinout.
Hardware Aspects
Let's start with the list of components we are going to use. Are they:

Arduino UNO + USB cable;


Gas sensor MQ-2;
5V active buzzer;
16 × 2 LCD;
10k potentiometer;
Jumpers for connection in protoboard;
Protoboard;
With these components, we can assemble the circuit below. Note that we used
the MQ-3 to assemble the circuit, which does not change the design because, as
we said, it applies to the entire series of sensors.

Software Aspects
With the assembly ready, we can load the software below. If you follow the work
here on with the books of this series, then nothing in the program will be new to
you. The LCD we present and talk about its technology in this post. The MQ-2
sensor follows a scheme very similar to several other sensors used with Arduino,
such as the humidity sensor and the various other models of the MQ family.
Basically, the firmware does the following: It declares the directives are
associating strings to the pins that will be used. Configures I/Os, LCD, and serial
port. In the void loop () function, the two outputs of the MQ-2 sensor are
constantly read to assess whether any gas has been detected.
The main observation is in relation to the sensor calibration. A small trimpot
allows you to adjust the sensitivity of the sensor (the level at which the D0
output goes to 5V). Here in our tests, in a normal environment, without the
presence of gases, the analog output varies between 130 and 150. We use a stove
lighter to pollute the sensor's surroundings with natural gas. The response of the
sensor was extremely fast, going from 150 to over 700. This dynamic depends
on the density of gases in the environment, and to have an adequate adjustment,
some real tests are needed at the installation site (remember that this sensor is
turned for bench testing and validation, not for real applications)
We declare a SensorLevel variable to be used as a limit to activate the Buzzer
and send the alert message on the LCD. This value must be calibrated according
to your bacalhau tests. Interestingly, you vary this parameter to study the
dynamics of the sensor.
#include < LiquidCrystal .h>

// Hardware Links
#define Buzzer 10
#define MQ2_Analog 0
#define MQ2_Digital 2
#define SensorLevel 500
#define LCD_RS 9
#define LCD_E 8
#define LCD_D4 3
#define LCD_D5 4
#define LCD_D6 5
#define LCD_D7 6

int digital_read = 0;
int analog_read = 0;

LiquidCrystal lcd (LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6,


LCD_D7); // RS E D4 D5 D6 D7

void setup ()
{
// Configure the
pinMode IOs (MQ2_Digital, INPUT );
pinMode (Buzzer, OUTPUT );
// Initializes the serial
Serial . begin (9600);
// Initializes the LCD
lcd. begin (16, 2);
}

void loop ()
{
// Read the data from the MQ2 sensor
digital_read = digitalRead (MQ2_Digital);
analog_read = analogRead (MQ2_Analog);

// displays the readings on the


Serial serial port . println ( "Digital Output:" );
Serial . println (digital_read);
Serial . println ( "Analog Output:" );
Serial . println (analog_read);

if (analog_read> SensorLevel)
{
// Displays the data on the LCD
lcd. clear ();
lcd. setCursor (0,0);
lcd. print ( "Contaminated air!" );
// Activate the
digitalWrite Buzzer (Buzzer, HIGH );

}
else
{
// Displays the data on the LCD
lcd. clear ();
lcd. setCursor (0,0);
lcd. print ( "Normal air" );
// Turn off the buzzer and the red
digitalWrite led (Buzzer, LOW );
}

delay (2000);
}
For real applications, with more robust commercial sensors, there are standards
such as NBR IEC 60079-29-2 - Detection of gases in explosive atmospheres and
NR33 - Labor standard that regulates work in confined spaces, which establish
usage and calibration criteria that are very important. NR33, for example,
establishes several criteria for calibrating gas detectors in confined
environments.
Remember that gas detection is a serious matter, if you are developing a
commercial application, stick to the rules and legal standards and keep in mind
that benchwork (like the one presented here) should not be used in real
situations.
Putting it to Work!
Most of the wires used for the connection are for the LCD. The interface with
the sensor and the Buzzer take only a few wires. See how the system looks!
MQ-2 sensor with Arduino and LCD and Buzzer:

We hope that you will now be able to incorporate not only the MQ-2 but any
other sensor in the MQ family. These sensors can detect a wide variety of gases
and are easy and practical to be introduced in projects with Arduino and small
microprocessor systems.
Now, in this final and second part of this chapter, we will see how to build an
access control system using an RFID Kit with Arduino!
RFID cards are used in many applications in everyday life, from credit cards to
automatic identification cards for access control.
These cards have a magnetic stripe that stores digital data and can be read and
written using radio waves.
RFID stands for Radio Frequency Identification. It is a technology that belongs
to an area called Automatic Identification and Data Capture (AIDC).
AIDC methods automatically identify objects and people, collect data about
them, and enter that data directly into the software with little or no human
intervention.
In this section, I will teach you how to build an access control system using an
RFID Kit with Arduino. So, Check out next!
RFID Kit with Arduino: Access Control System
The RFID reader module based on the MFRC522 chip is used for wireless
communication at a frequency of 13.56 MHz. The company that developed the
module is NXP, one of the giants in the semiconductor sector.

It is a chip with extremely low consumption and small dimensions. Its main
application is the reading of cards that use the Mifare standard.
With the kit, it is possible to develop and validate designs of access control
systems, security systems, and other variations.
RFID tags can be used to read various information about the cardholder,
allowing their automatic identification to validate or not access.
MFRC522 Specifications

Working current: 13-26mA/DC 3.3V;


Peak current: <30mA;
Operating frequency: 13.56MHz;
Supported card types: Mifare1 S50, S70 Mifare1, Mifare UltraLight,
Mifare Pro, Mifare Desfire;
SPI Interface Parameter;
Transfer rate: 10 Mbit/s;

How Does an RFID module work?


Methods and technologies that use RFID rely on radio waves to read and write
data. RFID systems are made up of the following main components:

RFID tag + Antenna: A small integrated circuit embedded in the card


and an antenna are used to store and transmit data to the RFID reader.
The tag identification is called UID, and it is a hexadecimal number
characteristic of each RFID card or key chain;
RFID reader: The reader converts the radio waves transmitted by the
tag's antenna to a format that can be used internally on the computer;
RFID kits, like the one used in this assembly, come with all of these
components. The RFID tag and antenna are integrated into the card or in a
keychain type tag.
The reader module is also part of the kit, and it is through it that data is
written/read. In our case, the reader is based on CI MFRC522.
When the card approaches the reader module, the antenna transmits the data at
the operating frequency (13.56MHz) to the reader, which receives the data and
converts it to a format that can be processed by the IC and manipulated by an
external MCU (Arduino, Raspberry or any other system).
Applications of an RFID Module
Applications go far beyond access control. Some of the most common are:

Identification of products in logistics chains;


Tracking/identification of products in international trade;
Time measurements in races and marathons;
Elimination of registration queues at events;
Access control;
Project Description: RFID with Arduino
Check out the step by step description of our access control system project using
an RFID Kit with Arduino:

Set up a circuit to read an RFID card.


Make software with Arduino to identify the card tag and present a
message on an LCD of "Access Released" for the saved tag, or
"Access Denied," for any other tag.
A buzzer will also be inserted in the circuit to warn and will emit
beeps for each situation.
Hardware Aspects
We will need the following materials to assemble the circuit:

Arduino UNO + USB cable;


RFID KIT;
16 × 2 LCD;
10KΩ potentiometer;
Active buzzer;
Protoboard;
Protoboard jumpers;
Level Shifter to convert signals from 5V to 3.3V;
With all the components in place, you can assemble the circuit according to the
diagram below. The pinout of the RC522 with Arduino is as follows:

SDA -> 9
MOSI -> 11
SCK -> 13
RST -> 8
MISO -> 12
Remember to connect the RFID-RC522 Vcc to the 3.3V! The RFID circuit
works with the 3.3V voltage, not the Arduino traditional 5V.
Hence the need to use the bidirectional level shifter between one and the other.
Some channels are unidirectional, but since you are already going to use a level
shifter circuit, we recommend that you buy a fully bidirectional one, as indicated
in the component list.
Assembly RFID Card + LCD Display:

The LCD connections are well explained in the code below. Each pin on the
LCD is associated with a macro through which we define the connection pin
with the Arduino.
Software Aspects
The software to load on the Arduino is as the below one:
#include <SPI. h>
#include <LiquidCrystal. h>
#include <MFRC522. h>

#define LCD_RS 7
#define LCD_E 6
#define LCD_D4 2
#define LCD_D5 3
#define LCD_D6 4
#define LCD_D7 5
#define SDA_PIN 9
#define RST_PIN 8
#define CardReleased "C9 22 10 0A"
#define TriggerBuzzer 10
#define BeepsReleased 2
# define BeepsNegate 4

MFRC522 mfrc522 (SDA_PIN, RST_PIN); // Create MFRC522 instance.

LiquidCrystal lcd (LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6,


LCD_D7);

char st [20];
void initial message ();
String UID = "";
letter byte;

void setup ()
{
pinMode (TriggerBuzzer, OUTPUT);
Serial. begin (9600);
SPI. begin ();
mfrc522. PCD_Init ();
lcd. begin (16, 2);
StandardMessage ();
}

void loop ()
{

// Look for new cards


if (! Mfrc522. PICC_IsNewCardPresent ())
{
return;
}

// Select one of the cards


if (! Mfrc522. PICC_ReadCardSerial ())
{
return;
}

getUID (); // separate the string with the UID to be tested

if (UID == Free Card)


{
lcd. clear ();
lcd. setCursor (0, 0);
// Displays the message of enabled access and activates
LCD buzzer. print ("Access Released!");
BuzzerBeeps (BeepsRealesed);
delay (2000);
StandardMessage ();
}
else
{
lcd. clear ();
lcd. setCursor (0, 0);
// Shows access denied message and triggers
LCD buzzer. print ("Access Denied!");
BuzzerBeeps (BeepsNegado);
delay (2000);
StandardMessage ();
}

delay (1000);
}

void StandardMessage ()
{
lcd. clear ();
lcd. setCursor (0, 0);
lcd. print ("Ready for");
lcd. setCursor (0, 1);
lcd. print ("Reading!");
}

void getUID ()
{
Serial. print ("UID Tag:");
for (byte i = 0; i <mfrc522. uid. size; i ++)
{

Serial. print (mfrc522. uid. uidByte [i] <0x10? "0": "");


Serial. print (mfrc522. uid. uidByte [i], HEX);
if (mfrc522. uid. uidByte [i] <0x10)
UID. concat ("0");
else
UID. concat ("");

// conteudo.concat (String (mfrc522.uid.uidByte [i] <0x10? "0": ""));


UID. concat (String (mfrc522. uid. uidByte [i], HEX));
}
UID. toUpperCase ();
Serial. println ("");
}

void BuzzerBeeps (int NumberBeeps)


{
int i;
for (i = 0; i <NumberBeeps; i ++)
{
digitalWrite (TriggerBuzzer, HIGH);
delay (500);
digitalWrite (TriggerBuzzer, LOW);
delay (500);
}
}
Setup () and Lopp () Functions
In the void setup () function we do all necessary initializations:

LCD;
Serial port;
mfrc522;
Input and output pins;
In addition, we have already called the StandardMessage () function to display a
standard message on the LCD.
In the Void Loop () function, we have two if's that are present in all examples of
programs in the MFRC522 .h library .
(https://www.arduinolibraries.info/libraries/mfrc522)
In these two if's, specific library functions are called to search for a card in the
vicinity of the reader, and select/read that card if present.
After this first step, we call the getUID () function, in which we separate the
identification bytes of the card reader into a string named UID. In addition, we
present this UID on the serial port.
If you still do not know the UID of your card, the first time you run the program,
whenever you bring the card close to the reader, the access denied message will
appear, because the UID that is in the program (22 C9 0A 10) is from the card
we used to prepare the post.
Just open the serial terminal and bring the card closer to the reader, so the UID
of your card will be displayed on the serial terminal, and you can replace the flag
CardReleased in the program with your UID.
After loading the program with the updated flag, the message displayed for your
card will be “Access Cleared.”
With the UID of the card read, we do an if-else to find out if this UID is the same
as the one saved in the program (in the flag CardReleased).
If it is the same, the program displays the message “Access cleared” and triggers
two beeps with the buzzer. If it is any other card, the message “Access Denied”
is shown, and we trigger four beeps with the Buzzer.
Auxiliary Functions
We have three auxiliary functions, they are;

BuzzerBeeps (int NumberBeeps);


StandardMessage ();
getUID ();
The BuzzerBeeps function is to activate the buzzer a certain number of times.
The NumberBeeps parameter is the number of times the buzzer will be triggered
with an interval of 500ms (you can adjust the interval if you want).
The StandardMessage () function shows a standard message on the LCD, saying:
"Ready to Read";
Finally, the function getUID (), as we said above, uses the function
mfrc522.uid.uidByte [i] from the library MFRC522 .h to access the information
read from the card previously (these data were read with the function
mfrc522.PICC_ReadCardSerial ( ) at the beginning of the void loop ().
Starting to Run the RFID Project with Arduino!
The UID of the card will be displayed on the serial terminal as follows:
UID of the card that will be displayed on the serial terminal:

The assembly may be a little fuller than normal, due to the wires to connect the
RF522 to the level shifters and theirs to the Arduino.
We hope you will see something like the one shown below:

Before closing this chapter, we recommend reading the examples available in the
MFRC522 .h library.
When you download the file and extract it to your computer, a folder called
“examples” can be accessed. In it are several examples of programs with RFID
applications with Arduino.
Using the sample codes, you can create your own applications and learn much
more about this technology.
Chapter Six: Current + Energy Meter & Audio
Module WTV020-SD with Arduino
In the first section of this chapter, we will assemble an AC power meter
(alternating current) using the Arduino UNO. Energy meters are part of the daily
life of any residence, building, or business. Several models of traditional
companies such as Clamper and EDMI are available on the market with varying
price ranges.
The key components of the meter are the current and voltage sensors, and the
technology/measurement specifications will dictate the final project price; we
will use a 100A non-invasive AC sensor SCT-013.
Current and Energy Meter with Arduino: Current Sensor
The energy meter basically consists of a current and voltage sensor connected to
a microprocessor circuit, which in this case, is the Arduino UNO. We read the
two basic electrical variables and from them, we determine the instantaneous
electrical power and the energy consumed in a given time interval, which is
given by the instantaneous power integrated in the measurement time period.
If the electrical power is constant, just multiply the power by the consumption
time. Thus, a 100W lamp on for 2 hours will consume 200 Wh (watt-hour). If a
function gives the electrical power, say p (t), the energy is calculated by making
the integral of p (t) in the measurement period.
In the case we are going to see, we will measure the instantaneous power from
the current sensor. The energy will be calculated using a summation (which in
practice is what an integral does). So, let's consider a 1-second integration step.
For each step, we will measure the electrical power and find the energy
corresponding to that interval and add all these values into a variable, which
will be shown on the LCD.
We will present in an LCD the values of current and energy calculated from the
moment the Arduino is powered.
Current Sensor 100A SCT-013
The SCT-013-000 current sensor is capable of measuring AC currents
(alternating current) up to 100A RMS. It is a non-invasive sensor; that is, it is not
electrically connected to the measured circuit. In practice, it is a current
transformer with a ratio of 100 to 0.05 (in the case of the sensor used in this
example, check the spin ratio of your own specimen), that is, a current in the
primary of 100 A appears in the secondary as a current of 50 mA. This sensor is
not for DC direct current measurement, only for AC.
Always remembering that when we talk about current, we are talking about the
RMS values, that is, the peak current measured by the sensor is higher, around
142 A, which corresponds to the RMS value multiplied by 1.4142 (square root
of two). Consult your AC circuit book to review these concepts, if necessary.
The sensor has an opening through which the wire with the current to be
measured must be passed (in a house, it would be either the phase or the neutral).
This wire acts as the primary of the transformer, generating a proportional
current in the secondary, according to the transformation rate of the circuit.
An important difference is that this sensor has a current output signal and not a
voltage signal. Thus, an additional circuit is needed at the output to convert the
output current into a voltage that can be read by the Arduino (we'll talk more
about that below).
Specifications

Input current: 0-100A;


Output current: 0-50mA;
Core material: Ferrite;
Opening dimension: 13 x 13mm;
Working temperature: -25 to + 70 ° C;
The open energy monitor website has a full article on how CTs (Current
Transformers) based sensors work. Check it out here !
(https://learn.openenergymonitor.org)
Applications
Energy meters are used in any project where it is necessary to monitor the energy
consumption of installation or circuit. The current sensor 100A SCT-013 can be
used, for example:

Small home automation projects;


Development and prototyping of energy meters;
Protection systems against current and voltage surges;
Lighting systems;
Energy efficiency studies;
Project Description
This project consists of the following:
Use a current sensor and present on the computer screen the values of current
and energy consumed since the measurement circuit was switched on until that
moment.
Hardware Aspects
An additional circuit that we will use to convert the current to a voltage value
that can be read by the Arduino is explained in this reference. Basically, first, we
need to know what is the relationship between the input and the output. For this,
we only divide the input current by the transformation ratio. In our case,
100/0.05 = 2000. Thus, we know that the measured current is the output current
multiplied by 2000.
To be able to read the output signal, we have to convert the output current to a
voltage within the measurement range of the Arduino. For this, we will use a
load resistor in conjunction with a circuit. Here is a detail, the current is
alternating; that is, it has positive and negative cycles. Since the Arduino does
not read negative voltages, we must also ensure that the voltage is always
positive.
Sizing Load Resistor
To calculate the load resistor, we will determine that the maximum voltage over
it has to be 2.5V (maximum voltage read by the Arduino divided by two). To
ensure that the voltage at the Arduino pin varies between 0-5V, we will use a
small voltage divider to add 2.5V to the voltage of the load resistor. Thus, we
will have a voltage varying around 2.5V.
We must also know the peak current to which the load resistor will be subjected.
Knowing that the maximum RMS output current is 0.05A, the peak current is
0.0707 A. Thus, the load resistor we are going to use is:
Load = Vmaxsensor/Imaxsensor = 2.5V/0.0707A = 35.4Ω
The closest commercial value is 33Ω. This will be our load resistor.
At peak values, the instantaneous power dissipated by the resistor will be 2.5 *
0.0707 = 0.177 W. Knowing this value is important to purchase a resistor that is
capable of withstanding the power that will be dissipated. With these values, the
voltage in the resistor will vary from 2.33V at the positive peak (33 * 0.0707)
and -2.33V at the negative peak (33 * -0.05). And the voltage on the Arduino pin
will vary from 2.5-2.33 = 0.17V to 2.5 + 2.33 = 4.83V. That is, we guarantee that
the alternating sinusoidal current is converted into a sinusoidal voltage that
varies in the measurement range of the Arduino.
All of these values are suggested by an open energy monitor, which has
developed a library that calculates the measured current value from this voltage
signal that we just built.
We still have to find a calibration value, which is passed as an argument to the
emon1. current function (pin, calibration) that we are going to use. This
parameter is calculated as follows:
Calibration_Value = 2000/33 = 61
Where 2000 is the transformation ratio (from 100 A to 50mA, the current is
divided by 2000), and 33 is the value of our load resistor, calculated just above.
So, we are ready to use the function in our program.
Note that this is a “huge sensor,” capable of measuring up to 100A. The output
current is very small, 50 mA. This means smaller currents, like 1 A, for example,
resulted in extremely small voltage variations at the Arduino port. If we have a
current of 1A for example, the current on the secondary of the CT will be 50mA
divided by 100, that is, 0.5mA. In the load resistor, this current generates a
voltage drop of 16.5mV, very difficult to measure, and extremely vulnerable to
circuit and external noise. Thus, the SCT-103 100A is particularly suitable for
larger loads.
If you want to validate a bench design or a small power load, for example, we
recommend using an SCT with a different transformation ratio. For example,
SCT-013-020, which transforms currents up to 20A into voltages of 1V.
Important Tips:

The SCT-030 100A sensors come with the built-in Burden resistor. I
measured the value of 38 ohms. Measure the value of your sensor as
well. If you already have the Burden resistor, it is not necessary to
insert the 33-ohm resistor into the circuit. But in this way, the
calibration factor (I_calibration) must be changed to the value of 30.
The reference voltage of the Arduino ADC converter must be 5V.
Always use the external source to power your Arduino. On my
Arduino Uno, the AREF voltage = 4.98V. If you use USB to power
your Arduino, the AREF voltage should be well below 5V (4.7 to
4.8V), and therefore all voltage measurements will be incorrect.
This circuit is very sensitive to electrical interference. Keep your
hands off the circuit. If possible, use shielded cables to connect the
circuit to the Arduino.
The SCT-013 sensors were developed to measure currents up to 100
A. If you need to measure smaller currents, you can wind the AC
circuit wire more than one turn over the core. In this way, the current
value will be multiplied by the number of turns. Test and adjust the
calibration factor.
List of Components
The necessary components for the project are:

Arduino Uno;
Current sensor 100A SCT-013;
33R resistor and at least 1/4 W;
2 100K resistors;
1 capacitor of 10uF;
Circuit
An additional component that could be added to the circuit is a voltage amplifier
between the voltage divider and the load resistor. When using high-value
resistors, the load effect decreases, but ideally, to decouple the two circuits
(voltage divider and load resistor), it is recommended to use an op-amp in the
voltage follower configuration or an additional optocoupler.
Having made these reservations, the circuit is as follows:

Software Aspects
We will use the library developed by energymonitor.
#include "EmonLib.h"
#include < LiquidCrystal .h>

#define Vrede 129 // defines the network RMS voltage (value read
with multimeter)
#define InputSCT 2 // defines the analog channel for the SCT signal =
pin A2

#define LCD_RS 9 // definition of LCD pins


#define LCD_E 8
#define LCD_D4 3
#define LCD_D5 4
#define LCD_D6 5
#define LCD_D7 6
#define I_calibration 60 // current calibration factor - read my tips in the
tutorial

EnergyMonitor EnerMonitor; // Creates an instance of the


EnergyMonitor
LiquidCrystal lcd class (LCD_RS, LCD_E, LCD_D4, LCD_D5,
LCD_D6, LCD_D7);
double Irms = 0;
float Time = 0;

void setup ()
{
lcd. begin (16, 2); // configure LCD 16 columns x 2 lines
lcd. clear (); // clean LCD screen

EnerMonitor.current (InputSCT, I_calibration); // configure SCT pin and


calibration factor

lcd. setCursor (0,0); // select column 0, row 0


lcd. print ( "Irms (A) =" ); // show text
lcd. setCursor (0.1); // select column 0, row 1
lcd. print ( "Ener (Wh) =" ); // show text
}

void loop ()
{
Irms = EnerMonitor.calcIrms (1480); // RMS current calculation
lcd. setCursor (9.0); // select column 9, row 0
lcd. print (Irms); // shows current value
lcd. setCursor (9.1); // select column 9, row 1
lcd. print (Irms * Vrede * (Tempo/3600)); // calculation of Watt/hour
Time ++; // increase Time
delay (1000); // 1 second delay
}

In the code, it is worth noting the following points.

The functions of the EmonLib.h library is used through an object of


type EnergyMonitor;
For current measurement, we must initialize the object using the
function: EnerMonitor.current (pin, calibration);
To read the current, we call the function EnerMonitor.calcIrms
(1480), where 1480 is the number of samples used to determine the
current value;
To calculate the energy, we multiply the current measured by the grid
voltage (set in the Vrede variable) and by time. As the loop has a
delay of 1 second, at each iteration we multiply the power found
(Irms x Vrede) by 1/3600, to have the result in watt-hours (1 second
is equal to 1 hour divided by 3600);
In the other lines of the code, we configure the pins and the LCD to take the
readings and present the data.
Putting it to Work!
Note: The wire that must be inserted in the sensor is only one and in no way
should we pass the two wires of the load supply through the sensor, because with
the current circulating in opposite directions in each wire, the magnetic fields
associated with each wire are canceled and not provide adequate excitation of
the magnetic core of the CT.
Final assembly:

It is worth remembering that for this energy measurement, we made a manual


measurement, which was to measure the voltage of the electrical network with a
multimeter and use the value found in the software as a given value. A next step
to improve your project is to use an additional circuit to also measure the voltage
value on the bus. So, instead of using a constant that must always be checked
manually, your system will already measure the voltage on the bus and present
the energy measurement based on it.
Now in this second and final part of the chapter, we will learn how to use the
WTV020-SD audio module. With it, you can incorporate audio elements in your
projects with Arduino, such as voice messages, music, customized alarms, and
many others. With this brief introduction, you will be able to use the WTV020-
SD module easily and practically in your projects.
Audio Module WTV020-SD - Incorporating Audio Elements with Arduino
The WTV020-SD module is a microcontroller circuit for voice recording. It has
an SD card slot with a capacity of up to 1GB of storage, which gives great
flexibility to work with audio files in projects with Arduino.
With the module, it is possible to use files in WAV and AD4 (compressed audio)
formats that are in accordance with FAT formatting. WAV format files can have a
sample rate of 6KHz to 16Hz. The files in the AD4 format have a sampling
frequency of 6KHz to 36KHz. For more information on the AD4 format, visit
this article . (https://www.filedesc.com/en/file/ad4)
The image below shows the module.

The module has some operating modes. Are they:

Audio Control Mode: Play/Stop, Next, Volume +, Volume- functions;


One-To-One Control Mode: The corresponding switch activates the
voice that triggers the three voices and adjusts the volume
subtraction;
Control Mode Power-Loop: When turned on, there is no need to
activate any input or output, the recording is all directed to the SD
card;
Second-Line Control Mode: Free to play files from any address.
Combination of reproduction can be used in this mode;
The module's nominal voltage is 2.5V to 3.5V, so that we can use the 3.3V
channel available on the Arduino to power it. The ADC converter used by the
module is 16 bits.
Connecting to the microcontroller (Arduino) directly to the module, we can use
four pins for communication and control of the audio reproduction functions.
This is the Second-Line Control mode.
In Audio Mode, push-buttons are used to activate the module's pins and perform
the same music playback functions mentioned above. The other two modes are
the least used, as they relate to less common situations.
Applications
The WTV020-SD Module can be used in several applications, such as:

Car alarms;
Voice messages;
Music player;
Parking Sensor;
Smart home and medical instruments.
Any project where the incorporation of audio elements is important is a strong
candidate for the WTV020-SD module.
Project Description
The example project consists of the following:
Prepare and save two files on the SD card of the WTV020-SD module, one in
WAV format, and the other in Ad4 display a menu on the serial interface to
choose which file to play and for how long.
Hardware Aspects
The list of components for this project is as follows:

WTV020-SD module;
Arduino UNO;
Protoboard;
Speaker for Arduino;
A very lean list with components available on the market.
The pinout of the WTV020-SD module can be seen in the table below, taken
from the original datasheet. For this project, we will use the power pins (3.3V
and GND) and four other communication pins.
Pinout wtv020-SD. Source: Datasheet:
In the assembly, we will see the following connection:
Pin Module WTV020-SD Arduino UNO pin
RST (pin 1) Digital 2
P06 (pin 15/BUSY) Digital 5
P04 (pin 7/Clock) Digital 3
P05 (pin 10/Din) Digital 4

Assemble the circuit according to the diagram below:


Software Aspects
To control the module, we will use the WTV020sd library. The library was made
available in the Arduino Community. Before recording the program and running
its audio files, it is necessary to format the SD card with the FAT file system and
also save a file in the AD4 format and one in the Wav format.
To convert to WAV, there are several applications online (ex1). To convert to
AD4, we recommend this article (https://www.buildcircuit.com/how-to-convert-
mp3-and-wav-files-to-ad4-format-wtv020sd-tutorial/) that presents several
methods. The original link to the library publication has an example on how to
use the module's various functions. The program is like below:
/*
Example: Control a WTV020-SD-16P module to play voices from an
Arduino board.
Created by XYZ, August 16th, 2019.
Released into the public domain.
*/

#include <Wtv020sd16p.h>

int resetPin = 2; // The pin number of the reset pin.


int clockPin = 3; // The pin number of the clock pin.
int dataPin = 4; // The pin number of the data pin.
int busyPin = 5; // The pin number of the busy pin.

/*
Create an instance of the Wtv020sd16p class.
1st parameter: Reset pin number.
2nd parameter: Clock pin number.
3rd parameter: Data pin number.
4th parameter: Busy pin number.
*/
Wtv020sd16p wtv020sd16p(resetPin,clockPin,dataPin,busyPin);

void setup() {
//Initializes the module.
wtv020sd16p.reset();
}

void loop() {
//Plays synchronously an audio file. Busy pin is used for this method.
wtv020sd16p.playVoice(0);
//Plays asynchronously an audio file.
wtv020sd16p.asyncPlayVoice(1);
//Plays audio file number 1 during 2 seconds.
delay(5000);
//Pauses audio file number 1 during 2 seconds.
wtv020sd16p.pauseVoice();
delay(5000);
//Resumes audio file number 1 during 2 seconds.
wtv020sd16p.pauseVoice();
delay(5000);
//Stops current audio file playing.
wtv020sd16p.stopVoice();
//Plays synchronously an audio file. Busy pin is used for this method.
wtv020sd16p.asyncPlayVoice(2);
delay(2000);
//Mutes audio file number 2 during 2 seconds.
wtv020sd16p.mute();
delay(2000);
//Unmutes audio file number 2 during 2 seconds.
wtv020sd16p.unmute();
delay(2000);
//Stops current audio file playing.
wtv020sd16p.stopVoice();
}
Basically, we have a loop in which we give the option for the user to choose one
of the two ad4 files to play. We created the TocaAudio function that executes the
commands to play the selected audio for 5 seconds. Two important observations
we have are as follows:
In several forums and project sites, there are a lot of reports of
problems due to the SD card. Even with the assembly and the correct
program, some people can only put it to work with some specific SD
cards. Most of the success stories involved cards of 512MB, 1GB,
and 2GB. We recommend taking extra care to verify that the card has
been formatted correctly and that the audios have been converted
correctly to ad4. In some reports, it was noted that some files
converted with certain programs did not work, while conversions
with other programs did;
Another issue is the nomenclature of audios. The datasheet specifies
very clearly that the files must be named according to a logic
0001.ad4, 0002.ad4, 0003.ad4 and so on;
It is recommended to use a signal amplifier to be able to hear the
audio more clearly. In our example, as the output power of the
WTV020-SD is very low, you must be in a quiet environment to hear
the speaker play;
Finally, a small hardware detail. The module has three solder points,
located at the top and with two markings, one written 5V, and the
other 3.3V. Some modules already come with these soldered points,
but you may have to solder them, connecting the middle point to the
3.3V point, as in the figure below:

We will close the chapter with the saying that we believe strongly now you are
ready to use the WTV020-SD in your electronic projects.
Chapter Seven: KY039 Heart Rate Meter & Audio
Recording and Playback with Arduino
In this first section, we will learn how to use the heart rate sensor and set up a
circuit with a datalogger to store historical heart rate series. The datalogger was
the subject of this post, and in the following text, we will focus on the sensor and
heart rate measurement.
The KY-039 sensor is not the most accurate and stable on the market. It can be
challenging to mount a meter with it that is reliable. In this section, we show
how it works and an example of how to interface it with Arduino and a
datalogger. Other sensors can be used in place of the KY-039 to save data to the
datalogger with minor changes to the code.
Attention: This project is for teaching purposes only. For real applications, an
approved and certified meter must be used. This post aims to explain the
operation and show an example of how this type of sensor can be interfaced with
the Arduino, but this is not a project for real applications.
KY039 Heart Rate Meter with Datalogger
The heart rate sensor is based on an infrared emitter and receiver. The working
principle is as follows: When the heartbeats, blood pressure, and, consequently,
the volume of blood in the veins, momentarily increases. With each beat, it is as
if a small variation in volume and pressure happens. The sensor works by
emitting an infrared beam that passes through the user's finger. When the blood
pressure increases, the amount of infrared light that reaches the receiver
(phototransistor) through the finger is different from when the blood
pressure/volume is lower. This difference is translated into variations in the
phototransistor output signal.
The sensor is shown in the figure below:
Specifications

Working voltage: 5V;


Dimensions: 25mm x 22mm x 17mm;
Sensor type: Infrared (IR) reflective
An important observation is not to let artificial light (from incandescent or
fluorescent lamps) directly affect the sensor, as the oscillation (generally 60Hz)
can interfere with the value read by the infrared receiver.
In the projects available on the internet, in general, the developers had
difficulties in working with this sensor, due to the variation of output being very
small and unstable (subject to variations in ambient conditions, the positioning
of the sensor/receiver and the way the finger holds the sensor).
With the firmware and base assembly in question, it is possible to measure
variations in the sensor output, but having an accurate measurement can be
challenging. At the end of the part, we give some tips for you to increase and
improve the project. We also give indications of other sensors that can be
evaluated for greater accuracy.
Datalogger to Store Data
We will use a microSD card to store heart rate data for as long as the system is
on. So, even after we hang up, we will have a database that can be used to plot
graphs and perform analysis.
To recapitulate very briefly, we will use a microSD module that has an input for
Micro SD cards and six interface pins available for communication with
Arduino. The interface used by the module is the SPI protocol (communication
protocol used to read and write data in the card's Flash memory). Thus, we can
connect the Arduino and send information to be stored, and it is also possible to
perform reading procedures to present the data recorded on displays such as
displays or the serial interface.
Applications
Basically, the frequency meter is used to build small devices for measuring heart
rate. Depending on how you implement it, it can be equipped to use during
walks/runs, for example, or any other type of variation.
Project Description
In this project, we will pursue the following objective:
Develop and assemble a heart rate meter that saves your heart rate history to a
log on the SD card.
Hardware Aspects
As stated at the beginning, our circuit consists of two parts: the circuit for the
datalogger and the circuit for the heart rate sensor itself. In the diagram below,
we show the datalogger integrated with the heart rate sensor:

We draw your attention to the three voltage dividers that are needed to connect
the SD card pins with the Arduino (a logic level converter can also be used).
The Ky039 sensor connections are very simple. The power pins can be
connected to the Arduino 5V and GND. Pin S must be connected to A0, which
will be used in our program to take readings.
The List of Materials Needed
Arduino UNO ;
KY039 heart rate sensor ;
SD card;
Micro SD Card module ;
3 3K3 resistors;
3 2k2 resistors ;
An important tip. For effective operation, the infrared beam must be well aligned
with the receiver, as shown in the figure below:

Software Aspects
The software will be as follows:
#include < SPI . h >
#include < SD . h >
#include < stdlib . h >

// Variables for SD card


const int CS = 4 ;
char dataString [ 7 ] ;
int sensorPin = 0 ;
int period = 200 ;

int HeartRate_perSecond = 0 ;
int HeartRate_perMinute = 0 ;
int count = 0 ;
int countBeat = 0 ;
const int Calibration_Value = 10 ;

float oldValue = 0 ;
float rawValue = 0 ;

File myArchive ;

void setup ( )
{

pinMode ( CS , OUTPUT ) ;
Serial . begin ( 9600 ) ;
delay ( 100 ) ;

Serial . print ( "Initializing SD card ..." ) ;


if ( ! SD . begin ( CS ) )
{
Serial . println ( "Initialization Failed!" ) ;
return ;
}
Serial . println ( "Initialization finished" ) ;
delay ( 100 ) ;

void loop ( )
{
rawValue = analogRead ( sensorPin ) ;

if ( abs ( rawValue - oldValue ) > = Calibration_Value )


{
countBeat ++ ;
}
count ++ ;

// every 1 second makes this count


if ( count == 10 )
{
HeartRate_perSecond = countBeat ;
HeartRate_perMinute = 60 * countBeat ;
Serial . print ( "HeartRate_perSecond" ) ;
Serial . println ( HeartRate_perSecond ) ;
Serial . print ( "HeartRate_perMinute" ) ;
Serial . println ( HeartRate_perMinute ) ;
count= 0 ;
countBeat = 0 ;
savedDataLogger ( HeartRate_perMinute ) ;
}

oldValue = rawValue ;
delay ( period ) ;
}

bool savedDataLogger ( int HeartRate_perMinute )


{
dtostrf ( HeartRate_perMinute , 5 , 2 , dataString ) ;
if ( myFile = SD . open ( "log.txt" , FILE_WRITE ) )
{

// Write on the SD card using the object myArchive


myArchive . println ( dataString ) ;
myArchive . close ( ) ;
}
else
{
// if the file does not open, it shows error message
Serial . println ( "Error opening log.txt" ) ;
}
}
In the void Setup () function, we initialize the SD card and the serial port. The
code consists of the void loop () functions, in which we constantly read the
sensor's output value and try to identify variations. Experimentally, we observed
that each heartbeat causes a variation of around 10 in the value read on the
analog port. This was the value considered as a threshold to identify whether
there was a beat or not.
Every second, we call the savedDataLogger (HeartRate_perMinute) function,
passing the calculated value of frequency per minute as a parameter. This
function saves the information on the SD card, and the software returns to the
Void Loop to continue to identify variations in the frequency of beats.
This simple assembly and firmware identify the variations of the sensor and
saves the data in the SD, but to achieve stable and more accurate measurements,
improvements are necessary. In general, other projects on the internet also
feature measurements with many variations. If you really decide to use this
sensor, some possibilities are:

Use an amplifier to increase the sensor's output signal;


Implement an automatic calibration function to update the
measurement threshold (in our case, we use the value ten observed
experimentally for simplicity);
Exchange the phototransistor or infrared LED for other components
of greater sensitivity. The finger absorbs most of the light emitted by
the infrared led. Thus, a more sensitive receiver or a more powerful
transmitter can help make measurements better;
Some other interesting projects are (the second link is great to see how variations
in ambient lighting conditions alter the behavior of the sensor):

Finger Heartbeat Detection Sensor Module (KY-039);


Arduino RYW-039 Heart Rate Monitor;
Finger Measuring Heartbeat Module;
Another sensor option;
Homemade pulse sensor;
We hope the project helped to teach new content. Although KY-039 is not very
accurate and there are no examples of really functional designs with it, it is a
very didactic sensor in terms of its operation and also very simple in relation to
its circuit.
We recommend reading the other references and projects that we recommend to
find out the difficulties and solutions that other developers have encountered.
Now we will learn how to use the ISD 1820 audio recording and playback
module. The module can be used alone, using its push buttons, or with an
interface MCU (control via GPIO).
Know a little more about the module and learn how to incorporate it into your
applications.
Audio Recording and Playback with ISD1820 Module
The voice recording and reproduction module are based on the ISD 1820 CI. The
module offers playback capacity between 8 and 20 seconds and is easily
controlled by both push-buttons and a microcontroller. This means that you don't
necessarily need to have the Arduino interfacing with it, just assemble the circuit
and use the module's built-in push-buttons.
In this part, we will use Arduino, as it offers flexibility and the possibility of
integrating audio recording and playback in an automation project, for example.
The heart of the module is the CI ISD 1820. It is responsible for the process of
acquiring voice and reproducing the data recorded in memory. In addition to the
CI, a quick inspection of the module allows the identification of an electret
microphone, the power terminal, the control buttons, with the REC, PLAYE and
PLAYL functions, and also the outputs for the speaker, which is the white
connector at the end of the module.
See the figure below for the location of the microphone, the power terminals,
and the ISD 1820 IC:

To select the recording time, it is necessary to adjust/change an external resistor.


The sampling frequency is also changed using this resistor. The recording time is
8 to 20 seconds, and the sampling frequency is 4 to 12kHz. The default resistor
is 100k. As you can see in the table below, this means that, by default, the
module plays 10 seconds of audio and has a sampling frequency of 6.4kHz.
External Duration Sample Rate Bandwidth (Hz)
Resistance (seconds) (Hz)
80 8 8 3.4
100 10 6.4 2.6
120 12 5.3 2.3
160 16 4 1.7
200 20 3.2 1.3

Description of the Plate and Pinout


The pins of the ISD 1820 module are as follows:

VCC: 3.3V;
GND: Feed reference;
REC: It is an active-high input for recording signals. The module
starts recording whenever this input is activated. It is important to
note that the pin must remain at a high level throughout the recording
time. That is, it is not worth just sending a pulse, thinking that the
recording will start and end. The REC pin takes precedence over the
other two (PLAL and PLAYE), so if you gave a command with
PLAYL and then with REC, the command with REC is executed;
PLAYE: Positive pulse playback command. When this pin is
activated (low level to high-level transition identified), the module
starts playing the recording until the memory ends or an End-of-
Message is found in the recording;
PLAYL: Playback command controlled by logic level. When this
pin goes from low to high, a playback cycle starts and plays as long
as the pin remains activated;
SP + and SP-: These are the outputs for the speaker. Can be
connected to speakers with impedances of up to 8 ohms;
MIC: It is the microphone input, whose signal is applied to the on-
chip preamplifier;
FT - Feed-Through: Activating this mode, the microphone activates
the speakers directly;
PE: Mode in which recordings are played successively;
It is worth mentioning the module's supply voltage, which is 3.3V, not 5V.
Therefore, be careful not to supply the module with a voltage greater than 3.3V,
at risk of damaging it.
The recording/manual playback procedure consists of 2 steps:

1. Press/Activate the REC button (note the LED that will light up) and
keep it at a high level until the end of the recording;
2. Select the Playback mode.

a. PlAYE: requires activation only once and will play the entire
recording;
b. PLAYL starts playback and to finish it is necessary to disable
it;
c. PE: When this jumper is on, the recording is played repeatedly
until the jumper is turned off;
d. FT: When this jumper is on, everything the microphone picks
up will be played directly on the speaker;
Project Description
Now here we are going to implement an example to control the module through
the Arduino. The project will be as follows:
Whenever a TCRT5000 presence sensor detects an object, we will reproduce a
previously recorded voice command.
Thus, our test consists of two steps: Press the REC button via Arduino to record
the desired voice command, and then enter an object identification mode, in
which whenever the sensor identifies the presence of an object, the ISD module
1820 will play the recording.
Hardware Aspects
In the module, you will see a pin bar with 12 pins, six on the right and six on the
left. The default setting is to leave the two jumpers interconnecting all four
middle pins on the inside. The meaning of each pin and configuration is shown
in the image below:

When the jumpers are connected as in A (PE configuration), the recording is


played continuously. When a jumper is connected to B, there are no changes as
the two pins in the middle have no functions. When a jumper is connecting the
two pins in C, FT mode is enabled.
The circuit, together with the TCRT5000, is shown below. For module
connections, for convenience, we show only the pins used by the software.
Software Aspects
The software used is as follows:
#define exidaSensor 5
#define led 13
#define activatePlayL 3
#define activateREC 4
#define Reproductiontime 10000

int readingSensor = 0;

void setup ()
{
pinMode (outputSensor, INPUT);
pinMode (activePlayL, OUTPUT);
pinMode (activeREC, OUTPUT);
pinMode (led, OUTPUT); // Pin to activate the
pinMode led (sensor output, INPUT); // Pin to read the signal on the
collector of the
Serial phototransistor. begin (9600); // initializes the serial port with a
baud rate of 9600
MainMenu ();
}

void loop ()
{
readingSensor = digitalRead (outputSensor);

if (lSensor == 0)
{
digitalWrite (led, HIGH);
digitalWrite (activePlayL, HIGH);
delay (playtime);
digitalWrite (activePlayL, LOW);
}
else
digitalWrite (led, LOW);

delay (10);
}

void MainMenu ()
{
int controlLoop = true;
char byteRead;
Serial. println ("Type a to record or b to run the playback");

while (controlLoop)
{
if (Serial. available ()) // checks if data is available for reading
{
byteRead = Serial. read (); // readbyte latest in the serial buffer
Serial. write (byteRead); // send the received data to the computer
}

if (byteRead == 'a')
{
Serial. println ("Recording starts at 3");
counter (3);
digitalWrite (activeREC, HIGH);
Serial. println ("Recording for 10 seconds!");
counter (10);
digitalWrite (activeREC, LOW);
Serial. print ("Done!");
Serial. println ("Type b to start playback");
byteRead = '';
}

if (byteRead == 'b')
{
controlLoop = false;
byteRead = '';
}
}
}

void counter (int how many times)


{
for (int i = 0; i <how many times; i ++)
{
Serial. print (i + 1);
Serial. println ("...");
delay (1000);
}

}
In the program, two auxiliary functions were created:

MainMenu (): This function is a quick menu so that the user can
make recordings before the system enters the void loop () function;
counter (): A simple function just to show the audio recording
duration on the serial terminal;
When energizing the Arduino and with the serial terminal open, you will see
messages asking you to record new audio or proceed to playback. If you choose
to record, you can record new audio for 10 seconds (standard time). If you
choose to proceed with the reproductions, the firmware will go to the void Loop
() function. In this function, the TCRT5000 sensor is read constantly. Whenever
an object enters the reading range, the sensor output changes state, and the
PLAYL pin of the ISD 1820 module is activated for 10 seconds.
Depending on your application, you can make small adjustments to the code to
play the audio for a shorter time or use other features of the ISD 1820 module.
Chapter Eight: Digital Scale with Arduino and Strain
Gauge Cell
In this chapter, we are going to talk about a very useful and practical sensor to be
integrated with applications with Arduino. Load cells based on Strain Gauges are
the sensor elements used in digital scales of various types. The model cell that
we are going to use is capable of measuring up to 50Kg. For scales with greater
capacity, a larger number of sensors can be used. Here we will also explain what
Strain Gauges sensors are, and we will use a load cell to measure the weight of
objects up to 50Kg and present the result on an LCD.
The load sensor we are going to use is a strain gauge, one of several types of
sensors that can be used to measure weight. Multiple load sensors can be used
simultaneously to increase capacity. Our load cell is a half-bridge sensor, that is,
it uses a Wheatstone half-bridge with a reference resistance and a sensor element
whose resistance varies according to the pressure applied. See the image below.

In general, at least two load cells are used, one to measure compression and the
other to measure tension (forces applied in different directions). With two load
cells, you have a complete Wheatstone bridge. To use only one load cell, it is
necessary to complete the bridge with two other resistors.
How a Strain Gauge Sensor Works
The principle of operation of a Strain Gauge is the change in the electrical
resistance of the sensor proportional to a certain pressure or force applied to it
(hence the name “Strain”). The most common Strain Gauge sensor is made with
very small wires organized in a certain pattern (usually in the form of a
resistance bridge) so that when a force is applied in a certain direction, causing
deformation in the disposition of the wires, the resistance varies proportionately.
The sensitivity of each sensor and model is quite different and is usually
expressed by the so-called Gauge Factor (GF). This is defined as the ratio of a
change in electrical resistance to a change in length (physical dimensions)
caused by an external force.
The great difficulty with these sensors is that the deformations caused by the
application of an external force or pressure are very small, causing variations in
the scale of tenths of ohms. Due to these very small order variations, it is
necessary to use a second component, which is a signal amplifier. There are
specific business models for working with Strain Gauges. For this project, we
will use the HX711 amplifier (more information in the next section).
In addition to sensors based on strain Gauges, there are also pneumatic and
hydraulic load sensors. To work with Arduino and small electronic projects, the
Strain Gauge sensor, which is based on the variation of electrical resistance, is
the most suitable. For a quick video introduction, visit this link .
(https://www.youtube.com/watch?v=fPzUtzFJFus&feature=youtu.be)
The load cell we are going to use has the following specifications:

Dimensions (mm): 28 * 28 * 8;
Capacity (Kg): 50;
Margin of error: 0.2%;
Excitation voltage (V): 5 ~ 10;
It is an active sensor, that is, it is fed with an external excitation signal. The
sensor output is in Volts. As you can imagine, due to the small variation in the
resistance of the sensor element, the variation in the output voltage is also very
small. This output voltage signal is what we are going to connect to the HX711
amplifier.
HX711 Converter
The HX711 24-bit converter and amplifier module is used to amplify the signal
from devices such as load cells, making the interconnection between these cells
and the microcontroller. We recommend reading the datasheet .
(https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf)
Specifications:

Operating voltage: 4.8 to 5.5V DC;


Operating current: 1.6mA;
Operating temperature: -20 to 85 ° C;
SPI interface;
Dimensions: 29 x 17 x 4mm (without pins)
The module is shown in the image below:

Avia Semiconductors manufacture the module, and its AD converter is accurate


to 24 bits. The module was designed to interface directly with bridged sensors
for load measurement applications. The input multiplexer selects between two
differential channels A and B. Each differential channel can be connected to up
to two load cells (A + and A- and B + and B-, each connected to the output of a
load cell in half a bridge).
Applications
Load cells are used in commercial and industrial applications for weight/load
measurement in general.

Digital scales;
Identification of load limits;
Weighing of objects;
Any application for which load measurement is required;
Project Description
Our example project will be as follows:
Use two load cells to weigh objects and show them on the serial port.
Hardware Aspects
It is important to highlight the color pattern used in this cell. As shown in the
image, the red wire, which is usually used for VCC, is actually the output signal
(connected to pin A- of the HX711). And the wire to which the VCC must be
connected is the white wire. We recommend that you measure the resistance
between the cell wires to know which is which. The wires that give a reading of
2K are the ones that must be connected to E + and E- (generally, the white (E +)
and black (E-) wire). The wire on which you get 1K readings is the one to be
connected to A + (usually the red wire). Thus, pin A + d HX711 will be
connected to the common point between the two 1K resistors.
Load cells are generally used in groups of four, where each cell is placed on the
part of the scale. They can be used in groups of two as well, where each cell is
one of the “arms” of the Wheatstone bridge (this is the case in question). There
are also examples where one of the cells is replaced by two 1k resistors (in this
case, it has to be precision resistors). Another option for making measurements
with just one load cell is to complete the Wheatstone bridge with a 1K resistor
plus a trimpot. The resistors must be as close as possible, so traditional resistors
with a 5% tolerance are not a good idea. Using a multi-turn trimpot or 1%
tolerance metafilm resistors is more appropriate.
In the references at the end of the book, we leave some of these assemblies as an
indication.
The assembly is clearer in the assembly below:

In the image above, we see a complete resistance bridge. On each side, we will
use a load cell. Each cell has active resistance (sensor element). It is worth
noting that, for practical purposes, it is enough to connect the black wire of one
cell to the white wire of the other, and each red wire remains the signals A + and
A-.
To facilitate mounting on the Protoboard, pins can be welded to the ends of the
load cell wires. Note that the point of support of the scale surface must be on the
black arrow (upper part of the cell). The bottom of the cell must be on a flat
base as well.

The bottom of the cell must be suspended; otherwise, the pins that hold the
transducer will prevent the sensor from flexing. In this case, we used cut-out
Velcro adhesive to attach to the bottom.

The connection with the HX711 and the Arduino is shown below:
We recommend that you mainly use the circuit diagram as a reference, as it
explains the internal resistances of the cells and is a cleaner design.
Software Aspects
For our Sketches, we will use the library HX711.h, which can be downloaded for
free from Github.
The first step is the calibration of the load cells. Using the assembly with the two
50 kg cells, run the calibration program below. In my assembly, the calibration
factor was 42130 (for weighing in kilograms). Therefore, this value was inserted
into the program. After calibration, make a note of the calibration factor to be
inserted in your Balance programs with the HX711.
Calibration Steps:

Remove any weight on the load cells,


After the balance is reset by the program, place known weight on the
load cell,
Press the a, s, d, f keys to increase the Calibration Factor by
10,100,1000,10000 respectively or
Press the z, x, c, v keys to decrease the Calibration Factor by
10,100,1000,10000 respectively,
Press ENTER after typing the letter,
Repeat steps 3 to 5 until the measured weight corresponds to the
known weight,
Remove the weight again, and zero the Scale (type t + ENTER to
zero),
Put the weight back on and repeat steps 3 through 6 to redo the
calibration.
Each load cell may have a different value for the calibration factor. If any
measured weight is giving a negative value, reverse the wires of pins A + and
A-.
If your scale allows the use of two cells at the same time, perform the calibration
procedure with the two cells mounted under the base of the scale.
When the balance is adequately accurate, stop the procedure and note the value
of the Calibration Factor. Repeat the calibration process with other known
weights, if necessary.
* /

#include "HX711.h" // HX711 Library

#define DOUT A0 // HX711 DATA OUT = Arduino pin A0


#define CLK A1 // HX711 SCK IN = pin Arduino A1

HX711 scale; // define HX711 scale instance

float calibration_factor = 42130; // calibration factor for initial test

void setup ()
{
Serial.begin (9600); // 9600 Bps serial monitor
balance.begin (DOUT, CLK); // initializes the scale
Serial.println (); // skips a line
Serial.println ("HX711 - Balance Calibration"); // prints on the serial
monitor
Serial.println ("Remove the weight from the scale");
Serial.println ("After the readings begin, place a known weight on the
Scale");
Serial.println ("Press a, s, d, f to increase the Calibration Factor by
10,100,1000,10000 respectively");
Serial.println ("Press z, x, c, v to decrease the Calibration Factor by
10,100,1000,10000 respectively");
Serial.println ("After reading the weight correctly, press t for TARA
(reset)");

balance.set_scale (); // sets the scale of the scale


zeroBalance (); // zero the Scale
}

void zeroBalance ()
{
Serial.println (); // skips a line
balance.tare (); // zero the Scale
Serial.println ("Zero Balance");
}

void loop ()
{
balance.set_scale (calibration_factor); // adjust calibration factor
Serial.print ("Weight:"); // prints on the serial monitor
Serial.print (balance.get_units (), 3); // prints scale weight to 3 decimal
places
Serial.print ("kg");
Serial.print ("Calibration Factor:"); // prints on the serial monitor
Serial.println (calibration_factor); // prints calibration factor
delay (500); // 0.5 second delay

if (Serial.available ()) // recognizes letter for adjusting the calibration


factor
{
char temp = Serial.read ();
if (temp == '+' || temp == 'a') // a = increase by 10
calibration_factor + = 10;
else if (temp == '-' || temp == 'z') // z = decreases 10
calibration_factor - = 10;
else if (temp == 's') // s = increases by 100
calibration_factor + = 100;
else if (temp == 'x') // x = decreases 100
calibration_factor - = 100;
else if (temp == 'd') // d = increase by 1000
calibration_factor + = 1000;
else if (temp == 'c') // c = decrease by 1000
calibration_factor - = 1000;
else if (temp == 'f') // f = increases by 10000
calibration_factor + = 10000;
else if (temp == 'v') // v = decrease by 10000
calibration_factor - = 10000;
else if (temp == 't') zeroBalance (); // t = zero the Scale
}
}
Arduino IDE serial monitor window, with the calibration procedure:
After calibrating the load cells, you can now run the Scale program.
Change the value of the Calibration Factor in the Arduino Program HX711
Balance (enter the value found in the Calibration procedure).
float calibration_factor = 42130; // calibration factor measured in
Calibration
Remove any weight on the load cells, and press T to reset the Scale.
Insert the weight into the Scale and check the weight.

* /

#include "HX711.h" // HX711 Library

#define DOUT A0 // HX711 DATA OUT = Arduino pin A0


#define CLK A1 // HX711 SCK IN = pin Arduino A1

HX711 scale; // define HX711 scale instance

float calibration_factor = 42130; // calibration factor measured in


Calibration

void setup ()
{
Serial.begin (9600);
balance.begin (DOUT, CLK); // initializes the scale
Serial.println ("Scale with HX711 - 50 Kg load cell");
Serial.println ("Press t for Tare"); // prints on the serial monitor
balance.set_scale (calibration_factor); // adjust calibration factor
balance.tare (); // zero the Scale
}

void loop ()
{
Serial.print ("Weight:"); // prints on the serial monitor
Serial.print (balance.get_units (), 3); // prints weight on the scale to 3
decimal places
Serial.println ("kg"); // prints on the serial monitor
delay (500); // 0.5 second delay
if (Serial.available ()) // if the serial is available
{
char temp = Serial.read (); // le character of the serial
if (temp == 't' || temp == 'T') // if you press t or T
{
balance.tare (); // zero the scale
Serial.println ("Balance reset"); // prints on the serial monitor
}
}
}

Arduino IDE serial monitor window, with the HX711 Scale program (weight =
1,250 Kg) will look like:

An interesting addition to be made is to replace the serial port with an LCD.


Thus, the readings of the scale will be presented directly on the LCD,
eliminating the need for the computer to use the serial monitor. To include the
interface with the LCD, we have broad chapters in the previous books of this
series on how to integrate LCDs in your projects with Arduino.
Due to noise in connections with a protoboard and load cell, some readings may
vary outside the curve. However, measurements tend to remain around a
reference value. An important point for the quality of the measurements is how
the load cells are mounted on the scale.
The ideal is to use a flat surface on the load cells to apply the entire weight to the
cells. The mechanical structure you use to accommodate the weights can cause
the readings to vary slightly. Pay attention to this point.
With the circuit assembled, just run on the PC. Do not make wires too large to
connect the load cells to reduce interference.

Our final recommendation is that you use at least two load cells and complete
the Wheatstone bridge. Many examples found using only one load cell have had
many difficulties until getting readings that make sense.
Chapter Nine: IoT with Esp8266 WiFi Module &
Updating ESP-01 Firmware
In this first part of the chapter, we will explore the ESP8266 ESP-01 WiFi
module. It is a component that has become popular in recent years because it
makes the integration of WiFi networks and TCP/IP connections in electronic
projects easy and practical. We will cover the basic aspects of operation and
programming. In the next part of the chapter, an advanced application is
developed to control residential cargo over the internet.
The Esp8266 WiFi Module
The ESP8266 is a low-cost WiFi module compatible with Arduino and with an
integrated TCP/IP stack. One of the most interesting points of the module is that
the board is integrated with an MCU, which gives the possibility to embed codes
on the board to control its pins and operation without the need for an external
MCU.
Thus, in general, the Arduino interface is used only in the programming step.
But in real operation, ESP does not need to be connected to the Arduino or any
other control board. You can also use Arduino to expand your project's
capabilities and have more flexibility.

The ESP8266 is designed by Espressif Systems, a fabless company (without its


own factory) of wireless products in Shanghai. AI-Thinker does the
manufacturing itself. The small size and reduced price meant that the module
quickly attracted the attention of designers. With it, you can connect to a WiFi
network and create TCP/IP connections simply and practically.
Several versions of the module are produced, each with different technical
specifications. Projects using ESP8266 are not lacking. The internet has an
already quite respectable collection, and at the end of the section, in the
references section, there are some very interesting examples to go a little deeper.
Pinout of the ESP8266 Module
The version in figure 1 (introduction) is one of the simplest, with eight pins
available in the module. A more robust version is the ESP8266 NodeMcu ESP-
12, which has 30 pins on the board and reaches a little more than the simpler
models (see the figure below).

For this introductory section, we are going to use ESP-01. This module talks to
the microcontroller via the serial interface. It also has 2 GPIO pins that allow the
module to be programmed directly. The figure below shows the module and its
pinout:
The pins are as follows:

Programming and Specifications


The module is pre-programmed with the famous AT command set, which means
that you can use the Arduino or any other controller (including the module's
own) to control WiFi capabilities easily and practically.
The processing capabilities of the board are also good, considering its small size,
which allows it to integrate sensors and other equipment directly with the
module (with the necessary interfaces and conditioning whenever necessary).
Before we talk about the hardware aspects, we warn you that, like many other
components, the ESP8266 operates with 3.3V. If you have a 5V circuit, it is
necessary to use a logic converter and provide a 3.3V supply.
Another important point is that the card is independent of external RF
components. The module comes with an antenna integrated into the plate itself
(this is the square waveform trail at one end of the plate). Some versions have an
onboard ceramic antenna, and others come with a connector to connect with
external antennas and expand the range of the network.
Project Description
In this example, we will connect the ESP-01 to the Arduino and use it to send AT
commands. We will present the main commands, such as placing the module
with AP (Acess Point) and STA (Station) and sending and receiving data over
the internet.
Hardware Aspects
Hardware assembly is very simple. Follow the connections in the image below:
For convenience, we use voltage dividers to adjust the logic levels, but you can
also use a specific converter. Notice that the GPIO and RST pins are
disconnected.
Another thing is that in this assembly, the Arduino is used only as a serial
interface with the computer. See that we connect the ESP to the Arduino serial
port. You can also use your own USB to RS232 converter module, such as FTDI.
To command the module via AT commands, as we are going to do, basically,
what we need is to connect the module's serial interface with the Arduino's, so
that we can send strings with the AT commands through the Arduino IDE's serial
terminal.
Software Aspects
As the goal is just to send AT commands manually so that we can understand
how the ESP-01 talks to the microcontroller, it is not necessary to write a
specific code. With the connections we use, let's just power up the Arduino and
use the IDE's serial terminal.
Since the TX and RX pins we are using are the ones that the Arduino uses to
communicate with its own microcontroller, we were able to send the commands
directly.
If you use other pins to make the serial connection, then it is necessary to write a
small program to receive the characters and send them to the module, and also
display the response strings on the serial terminal.
So, if you did the right assembly, just open the IDE, open the serial terminal and
proceed according to the next steps. To make sure that any previously recorded
application is not using the serial port pins, we suggest that you download the
“BareMinimum” example, which can be accessed in the IDE under the File ->
Examples -> Basics -> BareMinimum tab.
One point to note is that the ESP-01 may not have the correct firmware for use
with AT commands. If you have any problems with the steps in the next section,
after checking the connections, the next step is to save the most current SDK for
using AT commands.
The process for writing new firmware to ESP is explained in this other post. It is
worth checking because the process of updating AT firmware is not so well
explained on the internet (many references use tools other than those
recommended by the manufacturer and do not explain how to identify the binary
files and the respective memory addresses to be used).
Talking to the ESP-01 Module through AT Commands
Let's start with the basic test. With the serial terminal open, type:

AT
As an answer, you should receive an "Ok." This means that ESP-01 understood
the command and that it is all right to continue to command it. The module has
three basic operating modes:

Access Point (AP);


Station (STA);
Both STA and AP;
In AP mode, ESP acts as an access point, allowing other devices to connect to it.
But that does not mean that you can, for example, access your personal website
via ESP-01 in AP mode. In this operating mode, it simply establishes a
communication channel with another device using the WiFi protocol.
In STA mode, ESP can connect to an AP, such as your home's internet modem.
This allows your device to communicate with any other equipment that is also
part of the local network.
In the third mode of operation, the module works as both AP and STA.
To set the module to operate in one of these three modes, use the command:

AT + CWMODE = X
Where X corresponds to the operating mode: STA = 1, AP = 2, Both = 3. For
example, let's set the module to operate as STA, so we must send the command:

AT + CWMODE = 1
To check which mode of operation the module is configured in, the command is:
AT + CWMODE?
See in the image below how your serial terminal should look:

How to Connect to a Network with the ESP-01


To connect to a network, there are two steps. First check if any connection is
already active with the command:

AT + CIFSR
If an IP address was displayed, it is because the module is connected to that
station. In fact, this is the module's IP address. If there is no IP (all reset), you
can connect to a network with the command:

AT + CWJAP = "NetworkName", "Password"


Simply enter the network name and password in the indicated fields of the
command. Double quotes are part of the command. If all goes well, you will
receive an ok answer.
There is also the command:

AT + CIPSTATUS
It shows the status of the connection. In the image below, the answer to this
command was 5, which means that it is not connected, as we expected.
In the image below, we connect to the “Example” network, which in this case
has no password (open network, without WPS security)

Configure ESP-01 as a Server


So far, we left the module in STA mode and connected to a local network. Now,
to configure it as a server, we first have to enable it to allow multiple
connections. The command below does this:

AT + CIPMUX = X
Where X is 0 for only one connection, and 1 for multiple connections. Then, we
configure the port with the following command:

AT + CIPSERVER = 1.80
The number 1 means that we want the module as Open Server Mode. If it were
0, we would be setting it to Close Server Mode. The number 80 is the default
number of the HTTP protocol port. If you open a browser and enter the IP
address of your ESP module, a screen similar to the one shown below will
appear on the serial terminal:

Sending Data to the Browser


With the settings made, we can send commands and display data in the browser.
For this, the command is used:

AT + CIPSEND = 0.9
The 0 indicates the channel that will be used to send the data. 5 is the number of
characters that will be sent. In our case, we will send the message “Hello
World.” After sending the command, a “>” symbol will appear. This means that
you can enter the characters you want to send.
If you receive the message “SEND OK,” the transmission was successful. For
the message to be displayed, the communication channel must first be closed.
Use the command:

AT + CIPCLOSE = 0
When sending this command, the message “Hello world” will be displayed in
the browser.
Receiving Data Sent by Cell Phone
To send data to ESP, we will use the Mobile Telnet application for Android.
Download and install the application. On the home screen, go to "Telnet
Settings" and enter the IP of your ESP01 and the port you used to configure it as
a server.
To connect to the ESP-01, enter the data as in the image below.
Click Ok after filling in the data and then open the menu tab (three dots in the
upper right corner) and select “Connect.” The screen below will be shown, and
you can now send information that appeared on the Serial monitor to which the
ESP is connected.
On the serial screen, you will receive all the messages sent.

Nice, right! It is highly recommended that you read the AT Examples from
Espressif Systems.
(https://www.espressif.com/en/support/download/documents)
In the next part of this chapter, we will make an application in home automation.
We will use the ESP-01 to control cargo over the internet. Now that you know
the module and know how the main AT commands work, everything will be
easier. For some advanced applications, there are already some developed
libraries, and we will also use them to increase the projects.
Now we will show you how to update the ESP-01 firmware. There will be two
approaches. The first will be to show how to restore the default firmware for
module AT commands. The second will be to present how to record new
firmware written by you or ready-made examples from the Arduino IDE.
The ESP-01 Firmware
First of all, this is a section for those who already have their hands on ESP 01.
The motivation to write this section came from a need for the chapter itself to
update the module's firmware to one of the original versions.
There are several examples and posts on the internet, but an impressive number
of them run into a very complicated problem from the didactic point of view:
They explain the step by step very well but do not explain what is behind each
step. This happened mainly to record the original firmware for use with AT
commands. Most guides assume that the reader knows exactly how to configure
Espressif Systems tools and how to identify the memory addresses associated
with each binary file that must be written.
Despite being a basic aspect of all research in the electronics area, users do not
always remember to read the readme files or to seek instructions from the
manufacturers of the models and sensors themselves, preferring to go straight to
tutorials that, in theory, would better explain how to put an application to run.
In the case of recording the original firmware to use the ESP-01 with AT
commands, the main recommendations to be taken into account are:

Use the manufacturer's original tools: Espressif Systems;


Download the binary files directly from the manufacturer's website:
AT Firmware bin.
Go to the bin folder, inside which will be the binaries for you to
record and two other folders: std and stdio. These two folders are the
readme file (one file for each folder). When opening each file, you
should find content more or less like the image below:

These files indicate the corresponding address for each binary file, for each type
of ESP-01 (which varies the size of the flash memory). This file is often omitted
in tutorials, but it is the main source for knowing how to use the manufacturer's
binary files correctly.
Knowing the addresses is essential as the ESP-01's official firmware update tool
saves more than one binary file at the same time, making it necessary to specify
exactly which memory address from which each file should be saved.
The other possibility of updating is to record software written by you or
someone else. In this case, there is no need to worry about the manufacturer's
binary files, and the most practical way is to use the Arduino IDE itself, as we
will show below.
Hardware Aspects
In view of what was said in the introduction, we will use the following assembly
to load the software (both the original for AT commands and other firmware you
want to record).
The assembly was done using the FTDI232 serial converter. It is a very useful
board on many projects, and it is recommended to have one when needed. The
most important points of the assembly are the following:

The FTDI232 card works with 5V or 3.3V. In this case, since the
ESP-01 works with 3.3V, you must use an external 3.3V source to
power the protoboard and select the FTDI232 jumper to the 3.3V
position. See the highlighted jumper in the image below, and it is
essential to put it in the correct position.
Two buttons are used, one connected to the ESP reset pin and the
other to the GPIO0 pin. These two keys are used to put the module
into recording mode.
As the entire circuit is powered by 3.3V and the FTDI232 has the
jumper selected for 3.3V, it is not necessary to convert the logic
levels between the two boards. But it is common in projects with ESP
that you have to use a logic level converter or voltage dividers.

In the next section, we will do the firmware update in two procedures.


Software Aspects
First, let's load the firmware to use AT commands. It is often necessary to load
this firmware to be able to work with AT commands and make tests with your
module.
Procedure 1 - Upgrading to Factory Firmware (AT commands)
The first step is to download the manufacturer's update program and the binary
files to be saved:

Recording tool ;
Binary files ;
The recording tool has the face below. Note that there are several fields to fill
with a memory address and load different binary files. As we mentioned at the
beginning of the post, you should check the readme file, which comes with the
binaries you downloaded, which is the memory address associated with each
binary.
To find out the size of your module's memory, you can do a simple test. When
running the ESP Flash Download Tool, two windows are opened: the main
screen of the program and a black screen used for logging.

Select the COM port assigned to your module.


Select the baud rate. The most common value is 115200, but
depending on the version of your module and firmware, it can be
different. Try 115200 first.
Now, with your circuit properly energized and with the FTDI232
connected to the computer, press and hold the button connected to the
ESP GPIO_0 pin, and then press and release the other button (Reset).
You will see the blue ESP led blink once.
The module has now entered programming mode. Select START in
the ESP Flash Download Tool, if everything is right, information
about the module will be shown on the right side of the program, in
the DETECTED INFO field.

Having completed the steps described above, you are ready to load the AT
command firmware. Open the folder you downloaded with the binary files and
open the readme file. identify which set of addresses and binary files to use,
according to the version of your module, and load them in the sequence shown
in the readme.
Just upload the corresponding files and fill in the address on the right, as shown
below. Then check the SPIautoSet option above the DETECTED INFO box.
Also, select the size of your module's Flash memory. Once everything is
checked, select and START and wait for the download to finish.
In the end, your module will be loaded with the firmware for AT commands. To
test if everything went well, open a serial terminal, and do a test by typing AT. If
you get an "OK," then everything went well!
Procedure 2 - Recording New Firmware with Arduino IDE
If your goal is to use the Arduino IDE to load the firmware, you wrote yourself,
and the procedure is not much different. First, you need to install the ESP8266
libraries on the Arduino IDE. In the most current version of IDE (1.8.5), the
ESP8266 package is already installed, but if you use another version or need to
install it, you can do it manually.

1. Go to File-> Preferences. In the field “ Additional Card Management


URLs,” just insert the ESP8266 package link and confirm.
2. After that, go to Tools-> Card-> Card Manager. Look for the
ESP8266 package and install it.
3. Now, when accessing Tools-> Board, several different versions of
ESP modules will be available to be selected. Choose the option
corresponding to your module.
The package link is this one:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
If something goes wrong, check if there have been any changes in the official
repository.
See the image below for the preferences screen to load the additional URL.

After adding the URL, you can install the ESP package as per step 2, as shown
below:
After doing all the steps and with your ESP module already selected for the IDE,
you can now do the firmware update. With the circuit assembled and properly
tested, go to the Arduino IDE and download the ESP8266 Blink example. With
the example open and the circuit energized, keep the button connected to GPIO0
pressed and press the reset button. You will see the blue LED flash, which means
that the module is in recording mode.
Now, in the IDE, just upload the firmware and wait for the recording to finish. In
the end, the Blink program will be loaded on your ESP. The same procedure can
be repeated for other modules.
Now that you know how to load and update the ESP-01 firmware, you can start
making your applications and writing your own programs.
Chapter Ten: RTC - Real Time Clock DS1302, 1307
And 3231
This is the last chapter of this book, and here we will talk about real-time clocks,
or as they are known, RTCs - Real-Time Clocks. We will explain the three main
models used in applications with Arduino: RTC DS1302, RTC DS1307, and
RTC3231. A project will be implemented, in which we will use the RTC DS1307
to send date and time information to an LCD, that is, we will make a digital
clock.
RTCs are small electronic devices used to incorporate date and time data into
electronic devices. RTCs use quartz crystals and assisted circuits integrated into
a chip to measure time. Virtually all devices that require precise time control
have some type of RTC.
Three models widely used with Arduino are:

1. RTC DS13002.
2. RTC DS1307.
3. RTC DS3231.
All have prices that do not exceed 20 reais and can be easily incorporated into
electronic projects. All three models are manufactured by Maxim Integrated.
Let's see a little of each one and its main differences.
RTC DS3231
The DS3231 is a high-precision, low-power RTC. The module has a factory
temperature sensor and also an oscillator to further improve its accuracy.
It works in both 12-hour and 24-hour format, and information for months less
than 30/31 days and leap years are automatically corrected by the module.
A battery is included with the module to prevent data loss if the circuit is de-
energized. An important aspect that sets it apart from other models is the
communication protocol used. In the case of DS3231, the I2C protocol is used.
Thus, there are two communication channels (pins): SCL (Clock) and SDA
(data).
The specifications are:

Operating voltage: 3.3-5V.


Computes seconds, minutes, hours, days of the week, days of the
month, months and years (from 2000 to 2099)
Temperature sensor with ± 3 ° C accuracy.
Memory chip: AT24C32 of 32K bytes that can be used as extended
RAM of the microcontroller.
Power failure detection circuit.
Consumption is less than 500nA in battery mode with an oscillator in
operation.
Dimensions: 38 x 22 x 14mm.
Weight: 8g.
Reading the datasheet is recommended.
(https://datasheets.maximintegrated.com/en/ds/DS3231.pdf)
RTC 1302
The RTC 1302 is the simplest of the three. It communicates via a serial protocol,
with a pin called CE and another SCL. It is able to provide information on
second, minute, day, date, month, and year. Months with less than 31 days and
leap years are automatically handled by the module, and it operates in 12 and 24-
hour formats.
The main specifications are:

Chip: DS1302.
31-Bytes of RAM for data storage.
Voltage: 2.0V ~ 5.5V.
Current: less than 300nA at 2V and up to 1.2mA at 5V.
Programmable output signal in the square wave.
Consumes less than 300nA in oscillator mode.
The datasheet, directly from the manufacturer's website, can be accessed here .
(https://datasheets.maximintegrated.com/en/ds/DS1302.pdf)
RTC 1307
This Real Time Clock (RTC) is a real-time clock with a complete calendar and
more than 56 bytes of SRAM non-volatile memory. Like the other RTCs, it
provides information for seconds, minutes, days, dates, months, and years. On its
board, there is a circuit that detects power failures and activates the built-in
battery to avoid data loss.
It uses I2C protocol and automatically handles cases of months with less than 31
days and leap years.
Specifications:

Chip: DS1307.
Computes seconds, minutes, hours, days of the week, days of the
month, months, and years (from 2000 to 2099).
56 bytes of SRAM.
Voltage: 4.5 ~ 5.5V.
Power failure detection circuit.
Consumes less than 500nA in battery mode with an oscillator in
operation.
Temperature range: -40 ° C to + 85 ° C.
Dimensions: 2.9 × 2.6cm.
The DS1307 datasheet can be accessed here .
(https://datasheets.maximintegrated.com/en/ds/DS1307.pdf)
Differences between Modules
The main differences between the modules concern the protocol used, size and
type of internal memory, dimensions, and power consumption. The DS1307 and
DS3231 modules use the I2C protocol, while the DS1302 uses a serial protocol.
The I2C protocol uses two pins: the SDA (data) and the SCL (synchronism
clock). The DS1302 uses three pins: SCLK (Clock synchronism), CE (Chip
Enable - to enable data transmission) and I/O (data).
The big difference is that the I2C signals the start and end of the data
transmission using changes in the logical state on the SCL and SDA pins.
Basically, if SCL is at a high level, and there is a transition from high to low in
the SDA, the DS1307/3231 recognizes it as the START of communication. Now,
if SCL is at a high level and there is a low to high transition in the SDA, the
DS1307/3231 recognizes it as the END of communication.
In the DS1302, the role played by these logic combinations is played by the CE
pin. If it is at a high level, communication starts, if it is at a low level, the data
transfer ends. That is, whenever a reading or writing procedure is performed
with the DS1302, the CE pin must be placed at a high level.
Here is important information. In the DS1302 datasheet itself, Maxim informs
that in the old datasheets, the CE pin was erroneously called Reset (RST). But
the functionality was the same; that is, it was a technical error in the writing of
the datasheet.
The supply voltages are also important differences, with the DS1302 operating at
a minimum of 2V, while the DS1307 operates at a minimum of 4.5V.
Hardware Aspects
To illustrate how to use RTC in your projects, let's do the following assembly:

Notice that the RTC DS1307 was connected directly to the Arduino. This is
possible because both works with the same voltage levels. In addition to the
RTC, we also connect an LCD to show the date and time data. If you have any
questions regarding the LCD, read this post, and learn more details.

RTC pin SDA = pin A4 Arduino


RTC SCL pin = A5 Arduino pin
From a hardware point of view, assembly is simple. If the other RTCs were used,
the assembly would be basically the same.
Software Aspects
From a software standpoint, we will use the RTClib.h library, which can be
found on GitHub.
#include <Wire.h>
#include "RTClib.h"
#include <LiquidCrystal.h>

#define InterfaceLCD 1
RTC_DS1307 rtc;
char daysOfTheWeek [7] [12] = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"};
LiquidCrystal lcd (9, 8, 4, 5, 6, 7); // RS E D4 D5 D6 D7

void setup ()
{
Serial.begin (57600);
if (! rtc.begin ())
{
Serial.println ("Couldn't find RTC");
while (1);
}
if (! rtc.isrunning ())
{
Serial.println ("RTC is NOT running!");
// set for compilation date and time
rtc.adjust (DateTime (F (__ DATE__), F (__ TIME__)));
// Set to a date you set
//rtc.adjust(DateTime(2017, 12, 27, 11, 14, 0));
}
lcd.begin (16, 2);
delay (2000);
}

void loop ()
{
if (InterfaceLCD == 1)
showLCD ();
else
showSerial ();
Serial.println ();
delay (3000);
}
void showLCD ()
{
DateTime now = rtc.now ();
// year = now.year ();
lcd.clear ();
// shows the date
lcd.print (now.year ());
lcd.write ('/');
lcd.print (now.month ());
lcd.write ('/');
lcd.print (now.day ());
// Shows the time
lcd.setCursor (1, 2);
lcd.print (now.hour ());
lcd.write ('/');
lcd.print (now.minute ());
lcd.write ('/');
lcd.print (now.second ());
}
void showSerial ()
{
DateTime now = rtc.now ();
Serial.print (now.year (), DEC);
Serial.print ('/');
Serial.print (now.month (), DEC);
Serial.print ('/');
Serial.print (now.day (), DEC);
Serial.print ("(");
Serial.print (daysOfTheWeek [now.dayOfTheWeek ()]);
Serial.print (")");
Serial.print (now.hour (), DEC);
Serial.print (':');
Serial.print (now.minute (), DEC);
Serial.print (':');
Serial.print (now.second (), DEC);
Serial.println ();
}
Note that in the software, we use two functions to display the date and time data.
The showLCD function shows the data on the LCD, and the showSerial function
shows it on the serial interface. To select which one to use, just change the
InterfaceLCD flag.
The important points to be understood in the program are:

The function rtc.adjust (DateTime (F (__ DATE__), F (__ TIME__)))


sets the RTC time to the date and time at which the program was
compiled.
The rtc.adjust function (DateTime (2017, 12, 27, 11, 14, 0)) adjusts
the RTC time to the user-defined date and time. In this case,
December 27, 2017, 11 hours and 14 minutes.
After the rtc.adjust function is called, the RTC will start from that
date, and you no longer need to adjust it (unless you want to). The
RTC will continue to count until the day the module's battery runs
out, usually after a few years.
To read the date and time data, the new object of the Datetime class
is created (DateTime now = rtc.now ()). This object reads the various
time information, as shown in the showLCD and showSerial
functions.
Load the software into your assembly and test it. Using the serial interface, you
will have something like the image below in your output:

The first time the software runs, the message RTC is not running! will be
displayed. After that, the function rtc.adjust () will be called, and the RTC will
start counting the time normally.

With everything set up, you should receive messages like the ones shown on the
screen above. Detail: To change the display, such as changing from
“Wednesday” to “Wednesday” or showing the time first, just adjust the order of
the Serial.println and lcd.print functions within the showSerial and ShowLCD
functions. This adjustment is for homework, so you can train.
To use the LCD, just do the assembly, as shown in the "Hardware Aspects"
section. If you have any questions about the LCD or want to know more
information about it, read this specific post about that component. Remember to
adjust the contrast by the potentiometer until the letters can be seen clearly.
What's more, you can now incorporate date and time information into your
projects; the same library used in this project also has support for the RTC
DS3231. For the RTC DS1302, good library options and examples can be found
in the references at the end of this book.
Conclusion
Arduino is an open-source platform for electronics prototyping based on flexible
and easy to use hardware and software. It is targeted at artists, designers,
amateurs, and anyone interested in creating interactive objects or environments.
Arduino is capable of detecting environmental conditions by receiving signals
from sensors and interacting with the environment, controlling lights, motors and
other actuators. The PCB microcontroller is programmed using the Arduino
cable-based programming language and the Arduino environment based on the
processing environment. Projects developed using the Arduino can be self-
contained or can interact with a computer to complete a task using special
software (e.g., Flash, Processing, MaxMSP).
The technology created in 2005 by the Italian Massimo Banzi, along with other
collaborators, was born to be a facilitator in the teaching of electronics for
students of design and artists.
The platform was born to be low cost because students needed to be able to
develop their prototypes while spending as little as possible. You know how it is,
right?
Another interesting point of the project was the proposal to create an open-
source platform available to the community, which helped a lot in its
development.
What are the Possibilities?
If we connect input devices, some hardware, motors, sensors, displays, antennas,
or something to the Arduino, the possibilities can be endless.
Its applications are the most diverse, from fun to art, home automation, and even
helping other people. For example, the Arduino has already been used to create a
beer cooler controlled by an iPad where it was possible to follow the flow of the
drink and obtain information about the different types of beer. In addition, the
plate also served to inform the temperature and find out who drank more.
Another team created a touch-sensitive glove that helps blind people to “see”
obstacles along the way. In the same vein, another user created a jacket using the
LilyPad version (designed to build wearable designs) of the Arduino that
informs when a cyclist will change lanes through LEDs placed on the back of the
jacket.
In this book, we listed some incredible projects that used Arduino, proving that
this is a tool that helps a lot of those who have creativity.
You can make LED cubes that generate three-dimensional images, secret knock
detectors, after all, security is never too much, sneakers that tie the shoelace for
you, like “Back to the future 2”, in fact, the prototype rolled so well that it
became a product and it was opened for commercialization ...
Accessible Technology >> Movement Maker
Having an Arduino board, the second step to start working with it is to download
the development environment on the computer and connect it to the board via a
USB cable.
Affordable technology, Arduino, as well as 3D printing, is already important not
only for testing and 'homemade creations.'
A lot of people know that the creators of Pebble - that watch that hit 10 million
dollars in their crowdfunding campaign - did not get a 2nd round of financing, so
they turned to the community (Kickstarter) to get investment. What few know is
that they used Arduino to make their prototype.
Reference and Resources
https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-an-rgb-led-89bcae

https://www.programmingelectronics.com/tutorial-10-fade-an-led-with-pulse-width-modulation-using-
analogwrite/

https://www.arduino.cc/en/reference/servo

https://forum.arduino.cc/index.php?topic=478360.0

https://www.arduino.cc/en/Guide/ArduinoEsploraExamples

https://www.pololu.com/file/download/MQ2.pdf?file_id=0J309

https://en.wikipedia.org/wiki/MIFARE

https://www.arduinolibraries.info/libraries/mfrc522

https://github.com/RuiSantosdotme/Random-Nerd-Tutorials/blob/master/
Projects/MFRC522_RFID_Reader_with_Arduino.ino

https://stackoverflow.com/questions/58863735/ trying-to-stop-multiple-activations

https://create.arduino.cc/projecthub/Elaf07
https://stackoverflow.com/questions/59362306/ i-keep-getting-a-compilation-error-on-arduino-ide-using-
mfrc522-rfid-saying-that

https://learn.openenergymonitor.org/

https://github.com/openenergymonitor/EmonLib

https://www.filedesc.com/en/file/ad4

https://www.robotshop.com/community/forum/c/letsmakerobots

https://forum.arduino.cc/index.php?topic=117009.0

https://gist.github.com/buildcircuit/5132328

https://www.buildcircuit.com/how-to-convert-mp3-and-wav-files-to-ad4-format-wtv020sd-tutorial/

https://www.instructables.com/id/How-to-use-WTV020SD-16P-with-Arduino/

https://www.buildcircuit.com/example-1-using-wtv020sd-16p-music-module-with-arduino/

https://forum.arduino.cc/index.php?topic=117009.0

http://www.electronoobs.com/eng_arduino_tut8.php

https://makezine.com/projects/ir-pulse-sensor/

https://www.instructables.com/id/Heart-Rate-Monitor-1/
https://microcontrollerslab.com/heart-beat-sensor-arduino/

https://tkkrlab.nl/wiki/Arduino_KY-039_Detect_the_heartbeat_module

http://www.utteducation.com/past-projects/ky-039-finger-measuring-heartbeat-sensor-module/

https://forum.arduino.cc/index.php?topic=368013.0

https://www.instructables.com/id/HOW-TO-USE-ISD1820-VOICE-RECORDER-AND-PLAYER/

https://www.allelectronics.com/mas_assets/media/allelectronics2018/spec/ME-63.pdf

https://www.elecfreaks.com/store/blog/voice-record-module-isd1820.html/

https://learn.sparkfun.com/tutorials/getting-started-with-load-cells

https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf

https://github.com/bogde/HX711

https://www.hackster.io/MOHAN_CHANDALURU/hx711-load-cell-amplifier-interface-with-arduino-
fa47f3

https://electronics.stackexchange.com/questions/199487/connect-hx711-to-a-three-wire-load-cell

https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide

https://electronics.stackexchange.com/questions/102164/3-wire-load-cells-and-wheatstone-bridges-from-a-
bathroom-scale

https://www.geekstips.com/esp8266-arduino-tutorial-iot-code-example/

https://maker.pro/esp8266/tutorial

https://www.instructables.com/id/ESP8266-Wi-fi-module-explain-and-connection/

https://maker.pro/esp8266/tutorial/how-to-program-esp8266s-onboard-gpio-pins

https://datasheets.maximintegrated.com/en/ds/DS3231.pdf

https://datasheets.maximintegrated.com/en/ds/DS1302.pdf

https://datasheets.maximintegrated.com/en/ds/DS1307.pdf

https://github.com/adafruit/RTClib

https://github.com/msparks/arduino-ds1302

https://github.com/iot-playground/Arduino/tree/master/external_libraries/DS1302RTC

https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview

https://www.instructables.com/id/Arduino-Real-Time-Clock-DS1307/

https://www.arduino.cc/en/Reference/RTC

You might also like