100% found this document useful (1 vote)
361 views

Arduino 3 in 1 Beginners Guide

Begrijpelijk

Uploaded by

Al K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
361 views

Arduino 3 in 1 Beginners Guide

Begrijpelijk

Uploaded by

Al K
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 451

©

Copyright 2020 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 in 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 stated 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 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 the owned by the owners themselves, not affiliated with this document.
Table of Contents

Arduino:
Comprehensive Beginners Guide to Learn
Arduino Programming Step by Step
Introduction
Chapter 1: Diving into the World of Arduino
A Brief History
What Is Arduino?
The Microcontroller Chip
Discovering Other Arduino Board
Official Arduino Boards
Arduino Clones
Chapter 2: Hardware and Tools
Power Supply
The Breadboard
Jump Wires
Needle Nose Pliers
Multimeter
Solder and Soldering Iron
Diode
LED
Electronics and Physics
Resistors color code:
The Capacitor
Arduino IDE (Software)
Installation:
Chapter 3: Working with Arduino
Preparing Your Workspace
Working with Your First Arduino
The Simple Blink Code
Altering the Blink Code
Sketch
Using a Resistor
The Physics Behind It
Continuing
More LEDs
Coding
Optimizing
Chapter 4: Diving into the World of Arduino
Further Simple Sketches
Fade
Button
The Serial Monitor
Sensors and Input
Sensors and Actuators
Temperature Sensor
Infrared Emission Sensor
Photoresistor
Sound Sensor
Knock Sensor
Pulse-Width Modulation
Switches
A Sensor Sketch
Arduino Logic
Variables
Constants
Data Types
Structures
Sketch
Arithmetic Operators
Control Structures
Boolean Operators
Comparison Operators
Functions
Digital I/O
Analog I/O
Math
Random Numbers
Bit and Bytes
Chapter 5: Circuits, Arduino Shields and Library
Circuit Diagrams
Shields
Types of Shields
Prototyping Shields and Others
Ethernet, Wi-Fi, GPS… Shields
Sound Shields
Display Shields
Motorz! Shields!
Installing Shields
Preparations
Assembly
Attaching the Header
Soldering
Testing
Soldering
Bad Joints
Plug in
Tricks
Library
Using Library Manager
Manual Installation
Chapter 6: Practical Projects
LED Cube with Arduino
GPS Tracking with LoRa Shield
To design your own PCB:
Coding:
Motion Sensitive Light Switch
Build a Personalized Alarm System
Arduino Digital Clock with RTC
Game Controller with Unity
Traffic Light Controller
Chapter 7: Smart Appliances and The Power of the Web
Connecting Arduino to the Web
Hardware Install
Making Household Appliances Smart
Controlling Arduino with a Smartphone
Wi-Fi Remote Control Using ESP8266
Chapter 8: Troubleshooting Common Problems
Arduino IDE
Drivers
Crash
Direct Connection
Auto-Reset and Bootloader
Syntax in Arduino
Error launching Arduino on Windows
Conclusion
Appendix
URL
Reference
Arduino:
Simple and Effective Strategies to Arduino Programming
Introduction to Arduino
Chapter 1: Basic Programming Concepts Needed To Get Started With
Arduino
Chapter 2: Getting Started with Arduino
Chapter 3: C Language Basics
Chapter 4: Programming with Arduino
Chapter 5: Arduino Electrical Scheme
Chapter 6: The LCD Display Function
Conclusion
Arduino:
Advanced Methods and Strategies of Using Arduino
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
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
Reference and Resources
ARDUINO

Comprehensive Beginners Guide to Learn


Arduino Programming Step by Step
Ethan Thorpe
Introduction
This book will act as a starting point for all you need to learn about Arduino
programming. We will provide links to all the software you may need to learn
Arduino programming.

This book will seek to teach all aspects of Arduino Programming to a complete
beginner with absolutely no experience writing programs. So, for those who fear
programming as head-cracking work, we will seek to dissuade you from such as
you read through this course.

Makerspaces the world over are increasingly interested in including electronics


and programming into their education. Integration of Arduino boards into their
lessons and projects is often the way they go about doing this. A lot of maker
educators often avoid Arduino because they fear programming is a difficult thing
to learn. We are here to prove them wrong.

For those more familiar with Arduino programming, there is still much you
could learn from reading this book. Each step in the programming steps will be
explained to carry everyone along.

This book will act as a starting point for all you will need to know about Arduino
programming. We will provide links to the software you may need to learn
Arduino programming.
Chapter 1
Diving into the World of Arduino

A Brief History
Ivrea is a small town that sits across the Dora Baltea River in Italia. Famous for
its underdog kings, one of which was King Arduin who was eventually deposed
by King Henry II, of Germany.

We take the name of the platform from Bar di Re Arduino, a bar popularly
frequented by Massimo Banzi. The bar’s name was inherited from the Italian
king of 1002, King Arduin.

Arduino was introduced by Massimo Banzi, David Mellis and David Cuartielles
in Italia in 2005 at the Interaction Design Institute Ivrea (IDII) to provide access
to a cheap and simple tool for creating hardware for non-engineers.

It was forked from the work of Hernando Barragán, a student at the IDII who
had created a language called Wiring for his master’s thesis. Wiring was
designed to simplify the creation of interactive electronics for artists and
designers.

What Is Arduino?
Arduino can best be described as an easy to use open-source electronic
prototyping platform based on very flexible hardware and software. Arduino
boards have a microcontroller which can be programmed to do various tasks.
They can to read various different type inputs such as; read mail, light on a
photocell, wind change, a specific sound and turn it into an output; publish a
book, turn off the light, open the door, start the coffee machine.

The Microcontroller Chip


A microcontroller is an Embedded System, which means it is many units
embedded into one chip: Microprocessor, Memory units (RAM, ROM, FLASH),
Input/Output Ports, and other peripherals.

Microcontrollers are impressive because they allow non-developers and


developers to build a functioning electrical system in a short amount of time.
Since you need not choose several parts and make sure that they are compatible
with each other.

The microcontroller chip of the Arduino makes it a truly special resource.


Arduino Uno comes with a microprocessor that has 32KB of storage, 2KB of
RAM and has an eight-bit processor that runs at only 16MHZ. It is light and
capable of handling anything you may want to do with Arduino.

Note: some boards have higher storage/RAM/processor.

There are exceptions, some chips are built with larger RAM, storage and
processor. But, most Arduino within the common price range will be within the
above specifications with some deviations allowed.

Discovering Other Arduino Board


Arduino is released under a creative commons license (open source), which
means that anyone can produce their own board. There are many different
Arduino compatible clones on the open market but only official boards have
Arduino included in their names.

Most people buy clones of Arduino because they are less expensive than official
Arduino boards. We will warn you to be careful about buying boards from
companies you are not familiar with. If you do not want to buy from Arduino,
these companies are recommended http://www.adafruit.com/ and
http://www.sparkfun.com/. Their products are less pricy but also of similar
quality to official boards.

The board you buy should depend closely on the type of project you want to
undertake. For a small form project, you should consider Arduino pro mini and
for a wearable one, you should consider Sparkfun’s LilyPad board.
Official Arduino Boards
There are many types of Arduino as we have mentioned earlier. The Arduino
you will buy depends on what you want to do with it.

Below are a few examples of the Arduino boards that you will easily find out
there.

Arduino Uno
Arduino can best be described as an easy to use open-source electronic
prototyping platform based on very flexible hardware and software. Arduino
boards have a microcontroller which can be programmed to do various tasks.
They can to read various different type inputs such as; read mail, light on a
photocell, wind change, a specific sound and turn it into an output; publish a
book, turn off the light, open the door, start the coffee machine.

Because of its cheap price and ease of use, Arduino has become very popular for
makers that want to dabble in the creation of interactive hardware.

Unlike most previous programmable circuit boards, Arduino does not require
any extra hardware (Programmer) to load new code into the board.

You can buy Arduino directly from https://store.arduino.cc/ or from retail for a
price range of $22-$24.

The Board usually appears as a blue circuit board the size of a credit card
although varying models come in varying sizes. It comes with an Atmel
microcontroller which is a tiny computer, a USB connector, a power connector
and two rows of headers. The pins of the connectors are connected to the headers
which can be connected to virtually any electronics you can imagine.

There are usually 9 digital pins (I/O) and 4 analogue input channels. The I/O
pins can be used as input pins – to connect light sensors, temperature sensors,
sound sensors, keyboard or mouse, buttons… or they can be used as output pins
– to drive motors, control lights, connect displays, LED’s, check mail…The
USB also allows you to control your Arduino with your computer or control
your computer with the Arduino.

Arduino Leonardo
Arduino Leonardo is based on the ATmega32u. It has 20 digital I/O pins. It
contains everything you will need to support the microcontroller.

Arduino Ethernet
Arduino Ethernet is based on the ATmega328. It has 14 digital Input/Output
pins, six analog inputs and a 16 MHz crystal oscillator.

Arduino Due
Souped-up clock speed and ridiculous amounts of memory are the two things
that truly make the Due stand separate from the others.

Arduino Yun
Arduino Yun is the first of a new line of Wi-Fi products that seek to combine the
power Linux with the ease of use of Arduino. Arduino Yun is the combination of
an Arduino Leonardo (based on the Atmega32U4 processor) board with a Wi-Fi
system-ona-chip that runs Linino.

Arduino Mega 2560


Mega is a special class of Arduino. Renowned for its large number of I/O pins,
the Arduino mega is the go-to for complex electronic work. It has a very much
larger memory space.

Arduino Mini
If you need to pack electronics into space not much larger than a postage stamp,
then the Arduino Mini is probably what you want.

And many other models

For this lesson, we will use the Arduino Uno model as a sample.

Arduino Clones
Some Arduino clones that you may also desire to purchase include:
NodeMCU
NodeMCU is one of a kind. It is one of the most favorite alternatives to Arduino
available right now. It has a similar size to the Arduino mini and Nano, but it
packs a meaner punch.

Teensy 3
Teensy is one of the best Arduino alternatives available right now. They are very
similar to Arduino micro and Nano, much like NodeMCU. And much like the
lauded Node, they are even better than the official Arduino versions. A little bit
more expensive at $30, its processing power surpasses almost every other
microprocessor.

MSP430 Launchpad
Power consumption often proves to be the problem of most DIY builds, this is
why the MSP430 boards are impressive. Drawing in current claimed to be three
times as low as most other Arduino boards, it is exactly what is needed for builds
meant to run for long periods.

There are many Arduino clone other types; The STM32, PocketBeagle, DIY
(Homemade)…
Caution!
Do not fry your Arduino!

It might be a good idea to read this chapter before you actually unpack your
Arduino, Bad things may happen if you do not.

1. An Arduino can only supply 40mA output per pin, so you may not
want to drive a speaker or motor directly and you cannot directly
connect a LED without a resistor.

2. Do not short an output at +5v, +3.3v or the ground pins. The


amount of current drawn from an output pin at +5v connected to the
ground will fry the board.

3. Do not put Arduino on a metal surface, it will short out the pins.

4. Do not draw more than 200mA from the total output pins altogether.
The ATmega chip supplies only 200mA total, so driving 10LED’s
will eventually kill your board.

5. Do not supply more than +5v to your input pins. Even a +0.5v
excess charge may damage your board. This also applies to
sensors… always check your voltages carefully before connecting
anything.
6. Do not supply more than the accepted voltage to the input pins. A
+5v ATmega chip has an absolute limit of +6v and +5v for a +3.3v
one.

7. The vin chip will fry if it takes in more than +12v. There is an
onboard voltage regulator that will fry if it takes more than +12v.

8. When running on external power, do not draw more than 500mA


from the +5v pin.
9. Do not draw more than 50mA from the +3.3v pin.

10. Be careful of reverse polarity. Swapping in a GND pin for the vin
or +5v pin will kill the board.

11. Do not connect a load to the vin pin while you are using USB
power.

12. Remove the carpet under your work desk to protect against static
charge.

If this seems needlessly complicated, but do not worry. Just pay special attention
to 1-5 and 10 and you will be fine.
Chapter 2
Hardware and Tools
For you to begin practicing with Arduino, you will probably need a few things to
get started with.

While you can learn Arduino programming with only the contents of your
Arduino Uno Budget Pack, please do make sure you have all the materials listed
below within the pack:

A computer running Arduino IDE


USB A-B cable, Breadboard not less than half-size and Breadboard
wires
10K potentiometer and 2 push-buttons
Bright RBG LED and 5 red diffused LEDs
10K ohm resistors and 220 to 1K ohm resistors
Plastic mounting plate for the board
Flathead screwdriver
You will also need some of the following materials:

PN2222 transistor, 1N4001 diode and a small DC motor

Precision screwdriver set

Solder and soldering iron

Wire strippers, tweezers and a multimeter

A small needle-nose plier and flush diagonal cutters

60/m RGBW NeoPixel strip (1 meter)

Solder sucker
Scientific calculator

Components of whatever device you wish to operate the Arduino


with

Some/All the above are components you will need if you are to master Arduino
programming.

The function of the above-named components if not immediately stated below,


will be described as we get further into programming your board.

Power Supply
Arduino rarely comes with a power pack. For most projects, you will use the
USB cable to draw power from your computer. However, for any mobile project,
you will need to consider a 9V AC power supply to make it independent.

The Breadboard
The breadboard is a revolutionary design when it comes to programming a
board. Before its invention, it was necessary for an engineer to perfect his entire
board design on paper before doing any form of prototyping, or spend ruinous
amounts of money soldering and unsoldering the board (the board may get
damaged). The breadboard eliminated that limitation entirely by allowing its
users to program their circuits without permanently soldering anything until they
have perfected their designs.

A breadboard allows the user to prototype and experiment with different circuit
designs before doing any permanent soldering of the board.

The breadboard contains metal clips in the holes on their plastic housing which
are connected to each other by thin strips of conductive materials. These allow
currents to flow freely between one hole to the next, mimicking a circuit.
However, since the breadboard on its own is not self-powered, it requires power
to be sent through jumper wires from the Arduino. These wires are also
sometimes used to form circuits by connecting switches, resistors and other
components.
The jump cables are connected to the breadboard through two power rails clearly
visible on it, for both power and ground connections. The rail in between the
breadboard is to enable circuits to be more easily mounted on it.

Jump Wires
Jumper wires serve the very simple function of connecting your Arduino header
pins to the breadboard. As already stated above, using these to test-drive your
circuit allows you to see if your circuit is accurate without having to solder
Arduino. You will need jumper wires, if you want to use the breadboard.

Needle Nose Pliers


This is a vital component for any electrical and computer work. It is, in fact, vital
even to non-electricians like artisans, jewellery designers… these pliers are used
to re-position, snip and bend wires and to insert them into the breadboard. They
are also used to hold wires and circuits in place while working.

Multimeter
A multimeter is a very vital part of working with electronics. It is a combination
of a voltmeter (measures voltage {AC and DC}), an ohmmeter (measures
resistance) and an ammeter (measures current). Because of the precision
required when working with Arduino, it becomes almost vital if you are to work
on the board without blowing out your board at the first attempt. It will solve a
lot of the Mathematical issues you will face when learning Arduino

Working on Arduino without a multimeter is possible. But it is not advised if


you are not already proficient in working with other electronics with tight
tolerance ranges.

Solder and Soldering Iron


These are vital for any circuit work. Maybe even more vital than anything on
this list. Solder is a small wire of metal. It has a very low melting point, which
means that it can be very quickly melted and solidified.
The soldering iron is a piece of electrical equipment that heats up rapidly to just
the right temperature to melt solder. The process of melting the solder and
cooling it in order to cement a wirehead into a circuit is called Soldering.

Soldering is done to fix the wire onto the circuit so that it is not easily removed,
as shown below.

The process is very simple,

The end of the solder wire is carefully placed on the wire

The wire is placed in the location it is to be held

The soldering iron is applied (the solder melts onto the wire) and
removed swiftly

The wire is held in position until the solder solidifies

The soldering is done.

Although soldering the way I described above is sufficient for your needs, it is
not necessarily the best way to go about it. There are a lot of different ways to
perform soldering, you will find that the method I will describe below will be the
best way to come out of the process with a functional, undamaged, neat and
well-done board.

Get a soldering station. This will allow you a certain degree of


precision when working with delicate components, and a certain
safety of temperature control over your soldering iron.

Get a brass sponge. This allows you to prevent the degradation of


your soldering iron’s tip by removing oxidation due to left-over
pieces of solder. You may also choose to simply use a wet sponge to
perform the same task, although this may shorten the lifespan of
your soldering iron tip.

Please, stick with lead-free rosin core solder if you are majorly
concerned about your health. While the lead solder is significantly
cheaper, for health reasons, it has become fairly unpopular. If you
are using a lead solder, ensure proper ventilation of your work place.

It is advised that you tin the tip of and keep your soldering iron hot
for about 20 to 30 seconds before starting with any form of
soldering. The temperature should hover around 573K.

Tinning the tip of the soldering iron involves covering the tip of the
soldering iron (360 degrees) with solder.

Once your circuit is set and your soldering iron is ready, place your
solder along the tip of your soldering iron (use a copper wire to keep
the solder stable if you wish) and after about 1 to 2 seconds it should
have melted unto the tip.

Hold the solder on the tip and support it with wire, if you need to.

Now, place the tip containing the solder on the joint between your
two circuit components. Ensure the solder is well placed and remove
your soldering tip in a move that should not take more than 3 to 4
seconds. The solder should have been left between the joint.

Wait for a few minutes for the solder to cool and check it to see if
the soldered joint is solid. Do not attempt to blow wind unto the
joint in an attempt to make it cool rapidly. Once the soldered joint is
confirmed solid and good, you may proceed.

Diode
Diodes are like transistors, a semiconductor device. One of the many interesting
properties of the diode is that they conduct electrons only in one direction.

Arduino boards have a diode in series (directly connected one after the other)
with their power input jack to prevent you from reversing the power, which will
damage the chip.

Diodes are generally built with a forward voltage drop that ranges from 0.5v to
0.7v. If you measure the voltage before the diode and after the diode, the voltage
will be 600mV higher before the diode as compared to after it.

This, of course, has its limits, if the reverse voltage surpasses the diodes limit,
the diode will break, which will cause current to flow freely in the wrong
direction. In some diodes called zener diodes, this will be controlled. Zener
diodes only conduct current if the voltage exceeds a certain value.

This value is specific and constant, so zener diodes can act as a reference in
voltage regulators.

LED
The LED is much like a diode, this means that it will connect electricity only in
one direction. This is an internal limitation deliberately built into its function.
LEDs have both a cathode (negative) and an anode (positive).

The cathode is usually the flat and shorter leg side, while the anode often acts as
the round and longer leg.

LEDs often come in various color, Red, Green Orange, Blue… and with various
forward voltages often written as VL (This will become significant later on).
Since they emit low energy light, their voltage drop is much lower than light
sources that emit UV, Blue… light.

Color Forward voltage (VL)

Red 1.7v - 2.2v


Orange 2.0v
Yellow 2.1v
Green 2.2v
Blue 3.2v - 3.8v
White 3.2v - 3.8v
This is an assumption that may not always be true for LED forward voltages.
Always confirm what your LED’s forward voltage is before using it.

Electronics and Physics


Before you begin using Arduino, there are some physics you need to know. If
you already know this, skip this topic.

Electricity is the flow of electrons (electric charge carriers) from one point to
another.

Electrons are the negatively charged sub-components of an atom.

Electrons move easily through certain materials called conductors (copper,


silver, gold). These materials themselves contain free moving electrons

Certain materials like wood, plastic, rubber… are called insulators because they
don’t have free electrons and thus cannot conduct electricity.

Any material with more electrons than protons (positively charged sub-particles)
is negatively charged, and any material with more protons than electrons is
positively charged.

Much like magnets, opposite sides attract. Electrons in a negatively charged


materials will flow freely into a positively charged material as long as a
conductor is present between the two materials. This is called an electric current.

An electric current can best be described as the quantifying value of charge per
unit of time, flowing through a medium that conducts electricity. In physics, it is
denoted by the symbol “A”, which stands for Ampere and can be denoted by:

I = C/t

Where: C is charge (C) and t is time (s).

A battery is a device that possesses potential energy due to an imbalance of


electrons within one of it’s component.

Batteries have two sides, a cathode (the negative side that contains a lot of
electrons) and an anode (the positive side that contains very few electrons).
Since electrons generally seek to move to regions that lack them in sufficient
numbers, the electrons in the cathode will seek to move to the anode, which will
generate an electromotive potential (EMF).

The EMF stored in a battery is what lites an LED and rotates a motor. This EMF
is also called the potential difference, or more popularly Voltage (V/U) and is
represented as J/C.

The amount of energy a battery can release per second varies from one design to
another. This peculiarity of batteries and other voltage generation units is
described as Power and is designated by the unit J/s, which is generally referred
to as Wattage.

When drawing a circuit, the power will be drawn as if it flows from the Anode to
the cathode for convenience. In reality, the current will flow from the cathode to
the anode (due to the difference in the number of electrons on both sides of the
divide).

Most Batteries, are built to regulate how fast this happens, and that determines
their wattage.

Resistors are represented by the symbol “Ω”. They are best described as
electronic components that limit the free-flow of electrons within themselves.
This is useful in reducing the discharge rate, which is how fast electrons move
from cathode to anode. Its also for limiting how strongly (voltage) electrons flow
through the circuit.

It is ideal for most circuits that these values (Voltage/Discharge rate) be limited
because of the delicate nature of most circuit components that come with
Arduino.

They are labelled with prefixes K “kilo”, n “Nano” …

Resistors color code:


Resistors come designed in 4 to 5 bands, all of which spots different color
combinations.

To understand the value of the resistor (1000 Ω, 200 Ω, 0.3 Ω…), it is necessary
to calculate for them using the color code.

The first 2 (or 3) bands are the 2 (or 3) first digits of the value, and the 3rd (or
4th) band is the power of ten that comes after those 2 (or 3) digits.

This is sometimes called the multiplier; it is just the number of zeros you have to
add.

The last band is the tolerance and is usually silver or gold. An example is; red,
red, red, gold (22 x 100Ω = 2,200Ω = 22 x 10² Ω = 2.2kΩ with a tolerance of
5%).

Another example will be; green, blue, black, brown, red (560 x 10Ω = 5,600Ω =
5.6kΩ, with a tolerance of 2%).

There exists a relationship between the resistance, the voltage and the current
which can be calculated using Ohm's Law.

I = V/R

where I is the current (Amps), V the voltage (Volts), and R the resistance
(Ohms).

This is the most important formula in any electronic calculation you will do for
Arduino, so please remember it!

The Capacitor
A capacitor is a small electronic component that stores electric charges for a
circuit. Capacitors are used in Arduino to give the programmer more control
over how power flows in the circuit.

Since, the capacitor is capable of storing electronic charge in an electric field, by


using them within the circuit, you can generate analogue voltages under the
program’s control with a simple “analogWrite(){” function.
Capacitors, like resistors, are by themselves useless as a part of the circuit. They
are often referred to as passive components. However, when combined with
other circuit components, they become immensely useful.

The capacitor also provides protection from overfiring relays.


Arduino IDE (Software)
Programming can generally be done with a simple notepad. It is in fact often
recommended you learn with it. We are not going to do that here.

Arduino programming is done with Arduino IDE (Integrated Development


Environment).

Download it here ( https://www.arduino.cc/en/Main/Software)

Installation:
For Windows:
Go to https://www.arduino.cc/en/Main/Software, select download
and click on Windows installer.

Click download.

Click the downloaded file to run it.

Grant administrator permission.

Agree to the License Agreement.

Select the appropriate boxes (you will need the Arduino Software
and the USB driver).
An installation folder will be requested, click on next or type in
another folder.

Click install.

You will be prompted on whether or not you wish to install the


Arduino USB Driver (device software), select install.

You will need to wait for a few minutes, and when the installion is
complete, launch the Arduino IDE.
For Ubuntu:
Go to the site, go to Download, and select the Linux version.

Click download.

Open a terminal window using this command: CTRL+ALT+T, then


run the following commands. Change the file names as appropriate

cd Downloads

run after that: tar xf arduino-1.6.11-linux64.tar.xz

run this after: sudo mv arduino-1.6.11/ /opt/arduino-1.6.11/

then run this: /opt/arduino-1.6.11/install.sh

this will add the dailout: sudo usermod -a -G dialout $USER

What the above commands do is: opens the Downloads folder, then unzip the
downloaded file, it then moves the unzipped file to “/opt/” folder, and finally, it
will run the install script.

The install script will then create a desktop file, and a MIME type file will also
be created to associate “.ino” files with the IDE. Finally, add “a = append” user
to the 'dialout' group (-G). This will allow the IDE to access the serial ports.

Upon opening the IDE, you will notice the greyed out “Tools > Port”. Upon
successfully adding your chosen ‘dailout’ group to the IDE, the option will
become enabled. You will have to close the IDE and reopen it for this to happen.

Or you can look at the installation steps as provided here:


(https://tutorials.ubuntu.com/tutorial/install-the-arduino-ide#0).

Arduino IDE + Teensyduino:

You will need the Teensyduino add-on for the Arduino IDE if you have a
Teensy board. A comprehensive installation guide can be found here
https://www.pjrc.com/teensy/td_download.html/.
Teensyduino does not support the latest versions (1.6.10 & 1.6.11) of the
Arduino IDE, for now, so you will have to download this version (1.6.9).

You may come across an error while installing Arduino: If this is the case, try
running the command

sudo chmod +x /opt/arduino-1.6.6/install.sh

This adds (+) the permission to be executed (x).

Then from the above installation steps for ubuntu, try running: /opt/arduino-
1.6.6/install.sh again.
Chapter 3
Working with Arduino

Preparing Your Workspace


Arduino is usually done on a carpet free table, but your choice of workspace also
depends on how your Arduino is to be powered. For work powered by the USB
cord, it might make sense to use your computer table. For work powered with a
battery it will make more sense to use a dry plastic/rubber covered table with
only the flooring underneath. Like I had mentioned earlier, please keep away
from materials that can generate a static charge from your workplace.

To begin using Arduino, please make sure you have all the above listed vital
components, and that you have followed the necessary steps to download the
IDE onto your computer.

Once you have done that, you may proceed to the next topic.

Working with Your First Arduino


For your first work operating your Arduino,

1. Open your Arduino IDE by double-clicking on it. There are several


options listed on the header of the application, select File, then
hover on Examples and hover over 01.Basics. From the provided
options, select Blink.

2. The next step is to tell the software the type of Arduino you will be
working with. On the header, select Tools, then hover over the
Board option and select Arduino Uno (or whatever other board
you bought).

3. The next step is to plug in your Arduino using the USB cable that
was illustrated above. Please do note carefully the port through
which your Arduino was connected. It will become relevant shortly.
The boards LED will light up upon you doing this.

4. Then you will need to select the communication port the Arduino is
connected to. Do this by selecting Tools from the header and then
clicking on Port. If your port is not already labelled with the
Arduino Uno, please unplug your Arduino from the computer, and
plug it back in again. Once your Board shows up, select the port
containing the Arduino. It should be labelled as “Arduino/Genuino
Uno”. On windows, the port will likely be labelled as “COM3” and
may be labelled as “dev/cu.usbmodem1461” on OS X.

5. Click on Upload in order to transfer the simple Blink program to


the Arduino Board. You may also use CTRL+U to upload the code.

6. This will make the Board LEDs labelled TX and RX to blink, and
the software will display the message “Done Uploading”.

7. The LED labelled as L will then begin blinking as it initially did


upon plugging in the Arduino.

8. Congratulations, you have just told your board what to do for the
very first time.

9. The Next step is thus to alter the code a little bit and see how the
modifications influence what the LED does and how it blinks.

10. The term compiling is often used to describe how the human-
readable code that you wrote is converted to a binary numbers file.
This is how Arduino reads your program (in binary). The binary file
is then uploaded to the Arduino’s memory during the upload.

Note: If the Port selected is not the one connected to the Arduino, an error
message will be displayed once you try uploading the Blink code. Refer to this
for a list of common errors on Arduino and how to solve them
“https://www.arduino.cc/en/Guide/Troubleshooting”.

The Simple Blink Code


Here, we will explain the various things that make up the code you just uploaded
and how you can alter what your board does by changing things in it.

Now to examine the code. One thing easily noted when you clicked on your
code is that some texts show up on your workspace (the wide typing space that
covers your screen when you open the software). This is the code that tells the
Board what to do.

Arduino has no programming language of its own. The codes you will write to
use your Arduino are simply combinations of the C and C++ programming
languages.

The first 14 or so lines will be lighter than the rest, and examining them closely
will show that they are placed within these signs “*/” and “/*”. This is what is
called a comment: A comment is a line of words that come before or after a code
describing what the code does or other important things to the coder, yet does
not influence what the code does.

A comment can either be multi-line or single-line, and they are almost


universally lighter in color than the actual code. The example above was a multi-
line comment, single-line comments exist and is also illustrated in line 17.
Single-line comments use the operator “//comment:” instead of “*/comment/*”,
everything on that line will be a comment, and everything after it will be normal
code again.

Comments may also be used to temporarily disable a code by simple encoding


the code in the comment tag, this allows the programmer to prevent the code
from being executed without having to delete it. Since comments are not
executed, they do not take up space on the Arduino’s limited memory and thus
only exist on your hard disk.

“void setup(){” is what we will examine next.

This is a setup routine thus it will only run once every single time the Arduino is
started.
Void is a data type whereby is no information is returned by the setup.

The two brackets shown above are something used to pass data every function.
Since setup requires no data, the brackets are empty (This will be covered better
later into the book).

Everything that exists between curly brackets in the code is code that executes
while setup itself is running. Brackets in Arduino sketches are meant to be
closed, please always make sure you do this if you do not want to get error
messages. The software should normally notify you of any unclosed code, by
highlighting the piece for you or simply highlighting the closing bracket.

“pinMode(13, OUTPUT);” The command is the first command within the code
that alters the way your board works.

You might be able to guess by the name; it has to do with the rows of pins on
your board. These pins can either be output or input as described above. We will
want to make out pin number 13 an output. The pinMode is a value already
described by the software itself, thus it is a constant. It designates that what the
values within the brackets change is the mode of the pins (output or input).
Constants are designated with a blue color in the software (if it is not modified).

The first number designates the pin number you are modifying as 13 because the
blinking LED is connected to pin number 13. The comma is to make way for
another constant to be added (the software will treat the comma as a break
between two values describing pinMode).

The output value changes the pin number 13 to an output. The value is 1 as
opposed to input, which has a value of 0. Thus “pinMode(13, OUTPUT)” can
be written as “pinMode(13,1)”.

Every Arduino IDE statement is ended with a semicolon (;), as can be noticed in
the above statement.

“voidloop(){” is the next function to be executed after the above-described setup


has finished running.
Voidloop is a little different from void setup because unlike the latter, it runs
continuously, and will repeat forever until the Arduino is restarted or another
program is uploaded.

“digitalWrite(13, HIGH)” is a command that like the similar example above


describes something that is to be done to pin 13.

What this does is designate the pin number 13 as high, therefore writing
something digitally onto the board. The high value makes pin 13 connect
internally to the 5V pin. Since the LED is now connected across the ground and
to pin 13, there will now be a 5v current passing through the LED, which makes
it light up.

Note: Do not ground the pin 13 once this command has executed. It will fry
your board.

This complimentary value to the “HIGH” value is “LOW”. This value can also
be written as “1” for the former and “0” for the latter or “true” and “false” for
the same. Should the value be “low”, this sets the pin 13 to ground, meaning no
current will now pass through it and the LED will switch off.

“delay(1000)” is the last function.

The “delay” function, like its name implies, delays the code for exactly the
stated amount of time (in milliseconds: 1000 = 1sec), before allowing the
Arduino to execute the next command.

Once the Arduino reads to line 29 (the end of the “void loop(){”), it starts over
at line 25 again because of the loop you have created.

Interpreting the code shows that we are telling the LED to switch on and the
switch off for 1second (delay), before coming on again and repeat the steps
again. This causes the witnessed blinking that happens.

Note: if the position of “13” within the code is instead written as “led”, you will
see the variable “int led = 13;” written before the rest of the code. This tells the
IDE to let you code “13” as “led”. Therefore, for the rest of the code “led” will
mean “13”. This line of code is called a declaration.

Altering the Blink Code


You will be able to alter what the Arduino does by doing small modifications to
your code by altering the value in the “delay” function. By altering it from say
1000 to a value like 500 (or 200 or 2000). Uploading the new code will change
how fast your Arduino blinks from once about every second to once about every
0.5seconds (or 0.2seconds or 2seconds).

Sketch
On Arduino, A sketch is just another name used to describe what might be a
code when working with anything else, not Arduino. The sketch tells the board
how to behave, and what functions it needs to perform.

Using a Resistor
As you really get into Arduino programming, it gets more complicated. To be
honest, making what passes for a small bulb blink is not something really
impressive. That’s why you will learn how to add a resistor here.

The Physics Behind It


Before you begin connecting anything to your board, you should probably
unplug it from your computer. Next, you will need to know some things about
your board. You’ll need to know: your total resistance, the voltage of your LED,
and its current.

Using this formula R = .

The more LEDs you connect to your Arduino, the greater the true value of your
current and power distorts. This means you will need to know the total resistance
your LEDs will give the Electricity flow within the board.

You will connect the resistor in series with the LED (one resistor connected
directly to the LED). Since we know the voltage of the Arduino output pin is
+5V, adding the voltage of the LEDs to that of the resistors (VL + VR) should
give a value not exceeding 5V.

This means VR = 5V – VL.

Since the current passing through the resistor is equal to the one through the
LED; IL = IR.

This means that we can say: R = VR/IR = (5V – VL)/IL.

This will let us calculate the value of the resistor that should be connected to the
LED (R).

Most Arduino work uses a 10K ohms resistor.

Note: substitute 5V for 3.3V if you happen to be using a 3.3V Arduino. Your LED
datasheet will tell you what your LEDs voltage and amperage is (VL and IL).
Your amperage must not exceed 20mA, anything higher will fry your LED as
cautioned in chapter 1. Your calculated R will not be exactly what you have, so
take the resistor with the next higher value to it (it should not exceed +1Ω, or
your LED may light up weakly).

You will also calculate the resistance of your LED using the above method or
online using this application (https://play.google.com/store/apps/details?
id=it.android.demi.elettronica&hl=en) or this tool
(http://led.linear1.org/1led.wiz).

Continuing
The resistor can be connected to either the anode or cathode of the LED without
affecting the circuit, as long as it is in series with the LED.

You will now need to connect a red jumper cable from pin labelled
as 5v to the positive horizontal rail on the breadboard.

Similarly, a blue cable will be used to connect from a pin labelled


ground to the negative breadboard horizontal rail. This is a
configuration you will use again and again for Arduino work.

Your next step is to plug a yellow pin into pin 13 and the other end
should be plugged in any of the labelled 10 rows on the breadboard
(c10).

You will next need to connect another blue wire from your negative
ground rail to any other row on the breadboard (c18).

The next step is now for you to plug your resistor into row d18 (the
row next to the one you chose above), with the other leg plugged
just under your yellow cable in c11.

Finally, you will need to connect your LED’s cathode to the resistor
at d11 and connect the Anode to the yellow wire at d10.

Uploading your new program will light up your LED again. The
current runs through the resistor, into your LED and back into the
Arduino in a loop with a delay value (????).

Arduino sketch examples in your Arduino IDE are a great way to learn Arduino
programming. Just load the examples, and compare it to your own code
(debugging) to fix any problems that may come up.

Note: You may need to trim the legs of your resistor in order to reduce the
chances of any open leg coming in contact with other wires and shorting the
board.

More LEDs
This is something very easily done with Arduino and a small breadboard. This
will be done similarly to what was done with the resistor, but a little differently.

Connect the two pair of rails on the breadboard together using


jumper cables. (positive to positive and negative to negative). The
widely used method is using a red cable for the positive rail and a
blue cable for the negative rail. This makes it easy to distinguish
which is which without retracing your steps. It allows power to flow
to both sides of the breadboard.

The next step is similar to what you did in the one LED example
(connect the 5V pin to the bottom of the first positive rail using the
red wire, connect the ground pin to the bottom of the first negative
rail using the blue cord. Connect pin 13 with the yellow cable as
shown before). Repeat the rest of the first tutorial to add the other
blue cable, resistor and LED.

We start adding more LEDs by connecting a resistor from the


ground (the other negative rail) to h12, and a LED with the shorter
end (negative) at g12 (same row as a resistor) and the longer one
(positive) at g11.

Add the remaining LEDs with the same pattern as the first slowly
going down.

Now you are to change the position of the yellow wire on pin 13 to
pin 6 and add another yellow connecting from pin 5 to f11 on the
breadboard.

Do the same for the remaining pins, slowly going from pin 4 – 3.

Congratulations, you are finished with your Arduino board. Now


it’s time to code.

Coding
The first step to coding is to perform certain declarations you may need to use in
the rest of your code.

You can start by declaring “int timer = 200;”, this tells the
compiler that an integer called “timer” should have a value of
“200”.
Declare the “void setup() {”, then unlike before within the “{”, you
will declare;

for (int thisPin = 3; thisPin < 8; thisPin++) {

pinMode(thisPin, OUTPUT);

} and close it with another “}”.

What this means is that the setup will configure the pins 3 to 7 as
output, as the code had declared that “let “thisPin” be 3, let
“thisPin” be < 8, let “thisPin” be all values (integers) greater or
equal to 3 but less than 8, now set “thisPin” as output.

This short piece of code together with the set the code into a
changing mini loop. Each time the loop repeats, the value of
“thisPin” is increased by 1. Thus, by the next loop instead of 3, the
value of “thisPin” will now be set to 4. This will repeat itself over
and over again until the loop is complete.

To continue with the rest of the code, you will now need to set the
digitalwrite(thisPin, HIGH);” together with the rest of the blink
code. If you followed the blink example, then you already know
what that does.

There is an inclusion though. Since the “void loop(){”s “for”


declaration changes value, you will need to declare

“for (int = thisPin = 3; thisPin < 8; thisPin++) {”

This tells the loop to execute the command once before changing the value of
“thisPin” to the next one.

Since we don’t want to have the LEDs turn on one after the other
before turning off, we will include “digitalwrite(thisPin, LOW);”
after declaring the “delay(timer)”. This makes the LED turn off
after the delay.
However, since the value of “thisPin” changes as the loop repeats,
the LED changes as the light flashes. This causes the LEDs to flash
one after the other in a smooth row, from the one connected to pin 3
to the one connected to pin 7.

This is a simple method of connecting multiple LEDs and an


example of how to code such a thing. We will explain more as we
cover more topics.
Note: this code can also be done by writing it as:
for (int thisPin = 7; thisPin >= 3; thisPin- -) {
pinMode(thisPin, OUTPUT);
}.

This does exactly what the above code does, but instead of increasing the value
of “thisPin” as the mini-loop runs, it decreases it till it gets to 3, before starting
again. “>=” means greater or equal to (the value will include the integer), “<=”
means lower than or equal to (the value will include the integer), “<” means less
than ( the value does not include the integer), “>” means greater than (the value
does not include the integer).

Optimizing
The above code is an example of optimized code. It does everything you need it
to do while requiring only the shortest amount of code.

Optimization in coding is the process of reducing the code to the bare minimum
required for it to carry out the exact function needed. An optimized code is one
containing no extra words that can be done in another way to make it a shorter
code.

There are many ways to write code. The blink code for multiple LEDs, as shown
above, could be written in a different way. Another way to write this code is:

void setup() {
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
void loop() {
for (int thisPin = 3; thisPin < 8; thisPin++) {
digitalWrite(thisPin, HIGH);
delay(timer);
digitalWrite(thisPin, LOW);
}

This does exactly what the above code does. However, it is almost twice as long.
This is an unoptimized code.

The mark of a good programmer is the ability to write a code in the shortest
amount of words possible without affecting its action.

Another advantage of optimized codes is that they run faster than normal code
since the computer reads all the declarations faster. This might have no effect on
the speed of the light coming on, but as the code gets larger, the effect slowly
compounds and the code runs slower.
Chapter 4
Diving into the World of Arduino

Further Simple Sketches


Fade
Turning on multiple LEDs is a little bit more impressive than doing so with a
single LED. How about something more challenging, like making the LED fade
out? This is possible to do with Arduino. We will be using the function:
“analogwrite() ;”. What this does is simulate the appearance of brightness
between the on and off stage using something called a PWM (pulse width
modulation).

Connect the LED again much like when you practised the blink
example, but change the pin position of the yellow cable to pin 9
from pin 13. Everything else will be the same. Connect you Arduino
back into the system and make sure your port is selected correctly.

int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30);
}
What the code does is:

1. Set the value of led to represent 9, the value of brightness as


0 and the value of fadeAmount as 5

2. The void setup declares pin number 9 as an output.

3. analogWrite then sets up pin 9 to whatever brightness is


given at the time

4. Next is the fadeAmount function that sets how much the


brightness increases as 5

5. Next, the if statement checks if the brightness is less or


equal to zero or if it is greater or equal to 255

6. Thus, the code executes to increase the brightness until it


reaches 255

7. Once this is done, the code again increases the brightness by


a negative 5, until it reaches zero

8. The delay declaration is to prevent the code from running so


fast that you do not see the fading effect

Upload your code and restart your Arduino. The LED will start
fading in and out.

Like we mentioned earlier, this is in truth a manipulation of how the Arduino


interprets the code. Arduino can normally only generate digital signals.

Button
Connecting a button to Arduino is not very difficult. It is different from what
you have been doing so far because instead of just doing output code, for the
Arduino to function, you will need to do input. The Arduino will read the input
from the Button and interpret what to do based on the code you uploaded.

Much like you did with your first Arduino, connect the blue and red
cables to the power rails of your breadboard. Then connect the
yellow cable to pin 13 and d6.

Connect both rail sides of your breadboard together, connecting two


positive sides together and two negative sides together.

Connect your resistor to the negative rail (we are not using another
cable to connect to the breadboard) and to d5.

Connect your LED to e5 and e6 using what you have learned so far.

Another Yellow wire will be used to connect pin 2 to b18 and a


resistor will lie between a18 and a positive breadboard rail.

Finally, the button should lie between e16-e18 depending on your


button type and f16-f18. Then g16 will be connected to the negative
power rail on the other side as illustrated above.

Now that you have to code what your board looks like into your IDE

const int buttonPin = 2; // declaration of “buttonPin” {it is connected to pin


2} to represent the value 2:
const int ledPin = 13; // declaration of “ledPin” to represent the value 13:
int buttonState = 0; // declaration of “buttonState” to represent the value 0:
void setup() {
pinMode(ledPin, OUTPUT); // declares the LED as an output:
pinMode(buttonPin, INPUT); // declares the pushbutton as an
input:

void loop() {
buttonState = digitalRead(buttonPin); // reads the state of the
pushbutton:
if (buttonState == LOW) // checks if pushbutton is currently pressed:
{
digitalWrite(ledPin, HIGH); // The LED turns on:
}
else // if the pushbutton is not pressed”:
{
digitalWrite(ledPin, LOW); // The LED turns off:
}

The interpretation for this code is fairly obvious. The Arduino reads the code
top-down, so if the button is pressed (current flows through the button, thus, it is
called HIGH), the LED turns on. If it is not pressed (no current flows through
the button, thus, it is called LOW), the LED goes off. This is the function of the
attributes “if” and “else”.

The Serial Monitor


This is a tool used by programmers used to check in on different spots of their
code on the computer. It uses the same circuit build like that of the previous
button tutorial, without the LED. The code has the following design:

int pushButton = 2; // the name pushbutton is given to pin 2:


void setup() {
Serial.begin(9600); // initializes serial communication at 9600 b/s:
pinMode(pushButton, INPUT); // declares the pushbutton pin as an
input:

void loop() {
int buttonState = digitalRead(pushButton);
//reads the state of the pushbutton:
Serial.println(buttonState); // prints out the state of the button:
Delay(3); //this is purely for stability:

Once the code is uploaded and the Arduino compiles it.

You can also do this by opening your file header link in the IDE following these
steps:

File -> Examples -> 01.Basics -> DigitalReadSerial. This opens a similar code to
the one above.

Once this has been done, a window opens up on your IDE at the upper right
corner. The number within the code “serial.begin();” is called the data speed in
bits per seconds.

By changing the values described, you can easily see what is actually happening
on the board, whether the pin 2 is actually HIGH or if it is LOW or if pin 13 is
actually output or input. This makes the serial monitor code a very handy thing
when troubleshooting your Arduino.

Sensors and Input


Configuring the LEDs was a simple function of output. To use input, we need a
set of components called sensors.

Sensors and Actuators


A good definition for a sensor would be “an object with the purpose of detecting
events and changes in the environment while producing a corresponding output”

A sensor can thus “listen” to the physical environment and interpret it in order to
produce digital data. The actuator on, the other hand, is a device that converts
energy into movement. Both devices are just two sides of a coin. An actuator
converts digital data into output and a sensor converts environmental factors into
an input.
Using the example of a heater, the heater will be designed to increase the
temperature to say “300K”. How does the heater however, know when the
temperature is 300K? This is done by a sensor that will have been included in
the heater’s design.

Arduino is capable of dealing with both Analog and Digital inputs but can only
handle digital outputs. Sensors usually communicate in analog, but most have a
small circuit that is capable of translating analogue into a digital value. This is
because while digital information is presented in binary, analog information is
presented as amplitude variations. Thus, analog pins on Arduino are input.

Temperature Sensor
A temperature sensor does as its name implies; it senses changes in temperature.
A popular basic program is to connect a temperature sensor to an LCD and
Arduino to make it display the current temperature. Most large appliances use it
to monitor their own internal temperature changes to prevent damaging rises in
temperature.

Infrared Emission Sensor


This is used to transmit light at a frequency of 38KHZ (infrared). The actual
emission frequency depends mostly on the model. It is used to send code from
one Arduino to another or to even control a TV. It is also referred to as an
“infrared emitting diode”.

Photoresistor
This is basically a light-dependent resistor. Its resistance varies with the intensity
of the light to which it is exposed. This is used as a sensor to build equipment
that only works when there is light, or that shuts down when there is light, like a
light-sensitive coffeemaker.

Sound Sensor
This has proven to be very popular with makers of voice changers. The sensor is
capable of detecting changes in the surrounding sound, and it interprets these
changes as data. It usually has adjustable sensitivity.

Knock Sensor
This is used to build knock sensitive locks. They detect the sound of a knock.
For most builds, they are connected to LEDs that turn on when the sensor detects
someone knocking.

There are many other sensor types available, and we cannot list them all.

Pulse-Width Modulation
Pulse-Width Modulation is a type of digital signaling that has proven incredibly
useful to programmers everywhere. It is used by engineers and circuit designers
to create circuitry with sophisticated controls.

It is very common and useful to people who work with Arduino.

PWM allows the programmer to change how long Arduino pin spends at HIGH
in analog at a consistent interval.

PWM is used by Arduino programmers to effect fine control over circuit


components that cannot normally perform at such fine levels. It is especially
popular for controlling the brightness of display units (RGB LED, LCD…), fine-
tuning the grip of a robot arms, etc.

The term duty cycle is generally used to describe this difference in the amount of
time a signal is high compared to when it is low. This is calculated in
percentages. The “on-time” describes when the signal is high.

Thus, if a signal (5V) has a duty cycle of 50%, you are getting only 2.5V of
electricity in reality.

Apart from dimming LEDs, this is also used to the reduce power consumption of
Arduino by altering digitally how much current is supplied without actually
touching the board.

Switches
A switch is a mechanical device that is capable of either breaking a circuit or
connecting it. It is just one small pushbutton in a completed board. However, its
importance is not depicted by its small size. Any Arduino board that was built
for use must have a switch, this is to give a degree of control to the user,
allowing him/her to control whether the device should be currently working or
not.

A Sensor Sketch
This will be an example using an actual sensor. We will be demonstrating this
using a potentiometer. The attempt is to build Arduino that is capable of sensing
sound waves.

An ultrasonic sensor emits sound at a frequency of 40,000HZ. This sound


bounces back to the sensor, which records the time as data. The sensor interprets
the data using the relationship between time and velocity.

VCC, Echo, Ground and Trig are the four pins that can be found in an HC-SR04
Ultrasonic module. To make Arduino that can sense distance, we connect the
shields VCC pin to the 5V pin on Arduino, the Ground pin connects to the other
Ground pin, while the Trig and Echo pins connect to pin 9 and 10 on the
Arduino.

The code will be found here. The comments within the code explain what the
various code sections do.

https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/

The distance is calculated by multiplying the duration by 0.034 and dividing the
result by 2. This is a fairly simple example of a sensor sketch.

You can freely experiment by using different sensor types.

Arduino Logic
void setup( ){
statements-1;
.
.
.
statement-n;
}
void loop ( ){
statement-1;
.
.
.
statement-n;
}
The above is a simple example of what an Arduino code should look like. Most
Arduino codes will follow this simple basic design. There are two blocks to
Arduino programming, the Preparation and the Execution. Each block is
always enclosed in curly braces. The setup (), is the preparation block. Loop () is
the execution block, and everything contained within it is what the Arduino
reads to determine its function.

The setup function starts serial communication. It is where you declare whether
your pin is to be output or input as we had explained above. Once setup has been
declared the board starts reading pin numbers and setting them as input/output.

void setup ( )
{
pinMode (pin-number, OUTPUT); // this will set the ‘pin-
number’ as an output
pinMode (pin-number, INPUT); // this will set the ‘pin-
number’ as an input
}
The codes in-between the loop are executed continuously. The code runs from
the beginning of the curly bracket to the end of it, before returning to the
beginning to start again, until the Arduino is switched off.

Void loop ( ){
digitalWrite (pin-number,HIGH); // this will turn ON the
component connected to the ‘pin-number’
delay (500); // this makes the board keep its current configuration
for 0.5s
digitalWrite (pin-number, LOW); // this will turn OFF the
component connected to the ‘pin-number’
delay (500); // this makes the board keep its current configuration
for 0.5s
}
Declaration sometimes comes before the setup, but it is always read as part of
the setup. These usually take the form of the int attribute, which means integer.
They are used to change certain functions about how the code is interpreted once
it starts executing.

All statements in a code ends with a semicolon.


int led = 9;
int brightness = 0;
int fade = 3;
void setup( ){
}
There are literarily thousands of Arduino syntaxes out there. It is impossible for
us to go through them all. We will examine some, however.

Variables

Constants
Floating Point Constants: This variable is similar to integer constants. They
are used to make code readable. They allow the use of scientific variables like e
and E.

Integer Constants: This variable consists of numbers. They are automatically


treated as base 10 but can be modified with modifiers like; 10 (decimal), 2
(binary), 8 octal.

HIGH | LOW: These variables specify the two values of a pin (HIGH/LOW).
For Input: HIGH is reported when the voltage at the pin is greater than 3.0V for
5V boards and 2.0V for 3.3V boards OR for Output: HIGH is reported at 5V
for 5V boards and 3.3V for 3.3V boards.

For Input: LOW is reported when the voltage is at 1.5V for 5V boards and 1.0V
for 3.3V boards OR for Output: LOW is reported as 0V for both 5V and 3.3V
boards.

INPUT | OUTPUT | INPUT_PULLUP: This function changes the electrical


behaviour of a pin with “pinMode()”. Pins configured as INPUT; make
extremely small demands on the circuit they are on. For INPUT_PULLUP;
This is the same as input, but instead of external resistors being used to reduce
voltage demands, the circuit will use its own internal pull-up resistor. For
OUTPUT; This makes the pin into power demanding conductors on the circuit,
allowing the board’s full voltage to flow into them.
LED_BUILTIN ; This variable stipulates the pin to which the on-board LED is
connected to. This is usually pin 13.

true | false ; These are Boolean constants. False is defined as 0 and true is
defined as 1. Any integer that is non-zero is true, but true is often used to
represent a true statement. It is typed in lower case, unlike the other variables.

Data Types
Variable datatypes that exceed their maximum or minimum capacity are said to
overflow. This causes unpredictable results. To avoid this problem, some
programmers use unsigned datatypes like “unsigned int, unsigned long,
unsigned char”.
String(val); String(val, base); String(val, decimalPlaces); This constructs an
instance of the string class. It will return a single instance of the string class. It
allows multiple data types.
array ; This is variables in a collection that can be accessed with an index
number. Examples are;

int my[6];
int myT[] = {2,4,6,8};
int myTs[6] = {2,4,-8,3,
Char message[6] = “hello”;

All the above methods are valid for the declaration of an array.

Arrays are accessed by declaring;

myT[0] == 2, myT[4] ==8,…

This means that the last declarable index for an array is “n-1”. C++ does not
check if the array you declared is legal or not. Be careful not to exceed the
number of arrays you declared if you do not want errors.

bool: This holds one of two values (true/false).


boolean: This is a non-standard term for bool in Arduino
byte:This stores an 8-bit unasigned number. It is from 0-255.
char: This is used to store character values. Only use this datatype to store
characters. It occupies 8 bytes
double: It is implemented like float and occupies 4 bytes. It is a double-
precision floating number.

float : This is a datatype for numbers with decimal points. It is popularly used to
approximate analog and continuous values due to their greater resolution as
compared to integers.

Float should be avoided in mathematical calculations because they can only


contain 6-7 characters, their absolute values are different and they run slower
when compared to integer math. Float will be treated as integer unless you add a
decimal point.

int: These are the primary datatype. It is a number storage and stores a 2-byte (2
bit) value. They store negative numbers by “2’s complement math” and the
highest bit is called the “sign” bit.

long: these are variables that store 4-byte (32 bit), they are extended size
variables for number storage. L is added to at least a number when doing real
math with integers.

short: This datatype is 16 bit.

string: There are multiple versions string constructs but they can all be
represented in two ways. A string can be made out of a datatype or from an array
(made from type char) and simply null-terminate it. Examples for the first type
will be described in function. Strings are normally automatically terminated
with a null character “ASCII code 0”. This allows the function “serialPrintln()”
and others like it to tell where a string ends and terminate it there. Strings have
one more character than the text it contains.

char str1[15];
char Str1[8] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’};
char str7[8] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘\g’};
char str8[] = “Arduino”;
char str9[8] = “Arduino”;
char str5[15] = “Arduino”;

All the above strings are correct and will run without error.

Note: Strings are always defined in a double quote (“bvc”) while characters are
in a single quote (‘fds’).

void: This is used only for function declarations. They signify that the function
is not to return any information to the function it was called from.

word: This datatype stores unsigned number of 16 bits (2-byte).


Structures
Sketch
setup(): This is what is called to start a sketch. It is used to initialize
variables, pinModes… It runs only once.

loop(): This does exactly what its name says. It runs after setup and does so
forever and without end. It is what actively controls the board.

Arithmetic Operators
% (remainder) : This calculates the remainder after an arithmetic division
operation. It does not work on floats and is useful in keeping variables
within range. If its first value is negative, the result will be negative.

* (multiplication) : This operator multiplies two values together. It often


causes an overflow because it is easy for the result to exceed the datatype in
this type of operation.

Should any of its datatype be float or double, floating point math will be
used to obtain the result.

+ (addition) :

- (subtraction) : This operator finds the difference between two datatypes. It


can easily overflow should the result be smaller than the datatypes range.
Much like with multiplication, floating point math is used should one of the
data be of type float or double.

/ (division) : This operates on two datatypes to produce a division of the


lower data from the upper data. Float point math will also be used for the
result if one of the datatype is floator double.

= (assignment operator) : This tells the microcontroller to evaluate the


variable or datatype on the right of the assignment operator and store said
data on the left.
Control Structures
break : This is a structure used to exit conditional statements. It can also be
used to exit a switch case. The break statement bypasses the normal loop
condition.

continue : This structure skips the rest of the loops current iteration. It is a
conditional statement containing conditions like (for, while…). The Arduino
checks the condition and proceeds if said condition is met.

do...while : This does the same thing as the while structure, but it will run
after the loop, thus, making the loop run at least once even if it does not
meet the required condition.

else : This allows for the grouping of multiple tests. It will only be executed
if the “if” statement result yields “false”. The tests will carry on until it
yields “true”. If none of the conditions report “true”, the default operation is
carried out. It is normally used with the “if” statement, to grant a bit more
control to the statement.

for : This statement repeats a block of statements. It uses an increment


counter to terminate the loop. It is useful for any repetitive operation and
often appears with arrays operating on collections of data.

goto : This will transfer the program flow to a specified point in the
program. It allows the Arduino to skip certain codes. It lets the programmer
place his code without having to worry about where it is.

if : This structure is used to check for a condition and the proceeding


statement will be executed if the condition is “true”.

return : This is used to terminate a function and return the value of that
function should it be called.

while : This is used to loop a statement infinitely until the statement


condition eventually proves “false”. It only applies to test variables that
changes while the code is running.
Boolean Operators
! (logical not) : This reports as “true” only if the operator is “false” and
“false” only if the operator is “true”

&& (logical and) : This is a logic operator that reports “true” only if both
conditions are “true”.

|| (logical or) : This reports as “true” if even one of the 2 operator is “true”.

Comparison Operators
!= (not equal to) : It compares variables from both sides and reports “true”
if they are not the same, otherwise it reports “false”. You should only
compare variables of the same datatype, otherwise you may get
unpredictable results. Negative numbers are less than positive ones.

< (less than) : This compares variables on both sides of the operator. It will
return “true” if the operator on the left is less than that on the right. Negative
numbers are less than positive ones. You should only compare variables of
the same datatype, otherwise you may get unpredictable results.

<= (less than or equal to) : This compares variables on both sides of the
operator. It will return “true” if the operator on the left is less than or equal
to that on the right. Negative numbers are less than positive ones. You
should only compare variables of the same datatype, otherwise you may get
unpredictable results.

== (equal to) : It compares variables from both sides and reports “true” if
they are the same, otherwise it reports “false”. You should only compare
variables of the same datatype, otherwise you may get unpredictable results.
Negative numbers are less than positive ones.

> (greater than) : This compares variables on both sides of the operator. It
will return “true” if the operator on the left is greater than that on the right.
Positive numbers are greater than negative ones. You should only compare
variables of the same datatype, otherwise you may get unpredictable results.
>= (greater than or equal to) : This compares variables on both sides of
the operator. It will return “true” if the operator on the left is greater or equal
to the operator to the right. Positive numbers are greater than negative ones.
You should only compare variables of the same datatype, otherwise you may
get unpredictable results.

For further reading on the types of functions and syntaxes in Arduino, please
visit (http://arduino.cc/en/Reference/HomePage/). This is an Arduino reference
page that lists all the different types of functions for controlling the Arduino
board. Use this to code when coming up with your own projects that may not
have functions already listed in this book.

Functions
Functions in Arduino represent a modular series of code that performs a defined
task and then returns to the area of code from which the function was called. It is
like writing a mathematical equation in the code. For programmers
accomplished in the use of BASIC, functions allow the utility of subroutines.

Functions codify one action in a single place so that, the code only has to be
perfected once. This allows you to debug a single code and use that function an
unlimited amount of times without having to worry about errors.

Functions also influence your coding by making it modular. This makes the
program more readable and gives the programmer significant freedom in time
when coding, since a large part of the code would have been done as functions in
a previous work.

There are two required functions for Arduino to work, “setup()” and “loop()”.
All other functions must be created outside the curly brackets of these two
functions.

Examples:

int myMultiplyFunction(int x, int y) {


int result;
result = x * y;
return result;
}

The above code is a function. It allows for the multiplication of two integers “x”
and “y” and save the result into memory. We declared “myMultiplyFunction”
to be an integer containing two values “x” and “y”. Then, within the declaration,
we declare another integer “result”. By giving result a value of “x * y” (a
multiplication of “x” and “y”), the function is to return the result of that
multiplication and assign it to whatever contains the “myMultiplyFunction”.

To use the function, we can do this:

Voidloop() {
int h = 2;
int g = 3;
int z;
z = myMultiplyFunction(h, g);
serial.print(z);
delay(3);
}

In the above code, we use the function we had declared by equating “z” to be
“myMultiplyFunction”, this mean that the values of “g” and “h” will substitute
for “x” and “y” in the above declared function and return “z as 6”. The
remaining code does serial print for the Arduino so that we can physically
observe the result.

The “myMultiply function can be declared above or below the rest of the code.
While it is preferable to declare a function before you use the function, it is not a
rule.

A complete code will look like this:

int myMultiplyFunction(int x, int y){


int result;
result = x * y;
return result;
}

void setup(){
Serial.begin(9600);
}

void loop() {
int g = 2;
int h = 3;
int z;

k = myMultiplyFunction(g, h);
Serial.print(z);
delay(500);
}

Do not leave spaces in the declaration of names within your function. Arduino
will only accept 0-9, A-Z and the underscore (_), a function is not allowed to
start with a number.

A functions body must be contained within braces as we have seen with the
“voidloop(){” and “void setup(){” examples. The type of function is declared
first (int, void, const). The name of the function usually follows
(myMultiplyFunction, setup, loop). After this is to be the body of the function
contained within curly braces.

Within a functions body, a return type must always be present, even if it is void
like in “void loop”. The function must be called within the “void setup()” body,
by either simply declaring the name as in the above example or for those that are
not integers;

void DashedLine() {
serial.println( “----------” );
}
void loop() {
}
void setup() {
serial.begin(9600);
DashedLine();
}

As you will notice the function is called without any preceding “int” call. This is
because so far, we had been dealing with integers (numbers), but because the
new function is simply letters, we can call on it without preceding it with any
data type.

Note: we used “serial.println” and “serial.print”, both attributes do the same


thing, with the exemption that “serial.println” does this on a new line while
“serial.print” does it on the same line.

There are many different functions out there, we will list a few.

Digital I/O
digitalRead(pin, value) : This function reads the value of a specified digital pin
(HIGH/LOW).

digitalWrite(pin, value) : This function writes a value (HIGH/LOW) to a


digital pin.

pinMode(pin, mode) : This function configures the specified pin to behave as


either input or output.

Analog I/O
analogRead(pin) : This function reads the value from the specified analog pin.
analogReference(type) : This function configures the reference voltage for
analog input (DEFAULT/INTERNAL/EXTERNAL/INTERNAL1V1…)
analogWrite(pin, value) : This function writes an analog value to the specific
pin (PWM pins).

Math
abs(x) : This calculates the absolute value of a number. It returns +x if >= 0 and
-x if < 0.

constrain(x, a, b) : This function constrains a number within range. X will be


the constrained number (all data types), a is the lower end of the range (all data
types) and b will be the upper range (all data types). It will return x - if within
range, a – if less than a and b – if greater than b.

map(value, fromLow, fromHigh, toLow, toHigh) : This re-maps a number


from one range to another. It returns the mapped value

max(x, y) : This calculates the maxima of two numbers. It returns the larger of
the two numbers

min(x, y) : This calculates the minimum of two numbers. It will return the
smaller of the numbers.

pow(base, exponent) : It calculates the value of a number raised to a power.


Used to generate curves… It returns the exponent result. The data type for
exponent is float, for base is float and for return is double.

sq(x) : This will calculate the square root of a number. It returns the number’s
square root as data type double.

sqrt(x) : This calculates the square of a number. The datatype of the return is
double.

Random Numbers
random(min, max) ; or random(max) : This will generate pseudo random
numbers. It will return a number between min and max-1 with datatype long.

randomSeed(seed) : It initializes pseudo random number generator. The seed


data type is usually unsigned long.
Bit and Bytes
bit(n) : This computes the value of a specified bit. It returns the value.

bitClear(x, n) : This clears a bit of an assigned numeric variable.

bitRead(x, n) : This reads a bit of a number. It returns the bit’s value.

bitSet(x, n) : This will write a 1 to a bit of variable.

bitWrite(x, n, b) : This will write a bit of a numeric variable.

highByte(x) : This will extract the leftmost byte of a word. It will return the data
type byte.

lowByte() : This extracts the rightmost byte of a word. It returns data type byte.

There are hundreds of other functions that can be found at


(http://arduino.cc/reference/HomePage/). Please visit at your discretion.
Chapter 5
Circuits, Arduino Shields and Library

Circuit Diagrams

We discussed resistors and voltages earlier. There is a lot more to learn if you
are to become proficient in Arduino.

A simple electric circuit, as can be seen, has a battery (supplies power), a resistor
(controls the current) and a LED (lights up to signify the circuit is on. More
components can be easily added to this circuit, like more resistors, LED, a
capacitor, a potentiometer, a switch…

The load of a circuit is the total amount of power all the components of the
circuit will need to function. If the power supplied to the circuit is smaller its
load, the circuit will not work (or will work slowly/weakly).

Arduino circuit diagrams looks a little different however.


The large rectangles represent the Arduino

The labels had already been explained in a previous topic, please


refer to it.

The “-/\/\/\/\-” represents the power source (battery)

The lines represent cables and connections linking to each other.


Any label not linking to another represents a label that was not
employed

The “-/ -” represents the switch and the rest of the symbols
represent what they stand in for in a normal circuit.

Shields
They are modular circuits that can piggyback on your Arduino to give it extra
functions. Arduino shields are a must if you want to do something more than
light up a LED and print a few things on your computer. While you may be able
to rotate a motor with your Arduino, what if you wanted to connect to twitter
with it?

Shield were built in the same spirit as that of Arduino. Easy to use, cheap, small
and functional are the best words to describe Arduino shields. Much like
Arduino itself, they come in various shapes, sizes and functionalities.
It is possible to add more than one shield to Arduino, in fact, the only thing that
limits the number of shields that can be added to Arduino is the circuit load.

Shields often come with a library or an example sketch. This makes working
with shields a very easy thing to do. For an experienced Arduino user, it is
possible to connect Arduino to a shield and get it working in just 5 minutes.

Arduino shields are built with a similar form as Arduino boards themselves.
Power and ground pins will be on one eight pin header, and there will be other
analog pins on a six-pin header next to the eight pins. Digital pins will usually
occupy the other side, an eight-pin header that is seperate from another ten-pin
by some spacing.

Some shields will require another connection to the Arduino's ICSP header as
shown above (the2- 3 pins at the vertical left). Most Arduino shields will use
every pin available on the board, although some take only a few.

Some shields are capable of communication using SPI, I2C or serial, while others
use analog inputs or Arduino’s interrupts.

Note: Do not use overlapping pins when using multiple Arduino shields.

Types of Shields
Prototyping Shields and Others
Protoshield Kit
This Shield works as a big prototyping area. It is the most popular prototyping
shield. A breadboard can be connected to it, or you can just solder directly to the
board.

Go-Between Shield
This shield solves the issue of overlapping pins by sitting between two shields
and swapping the pins of the top shield.

ProtoSrew Shield
This is a useful tool for linking Arduino to external motors and heavy-duty
sensors. It is similar to the ProtoShield, but each pin is linked to a new screw
terminal.

Danger Shield
This shield typically contains everything from potentiometers, to display, to a
couple of other impressive sensors. The danger shield allows you to mess around
with your Arduino by warning you of danger. It is very important when learning
the ins and outs of using Arduino.

Joystick Shield
This is used to turn the Arduino into a control tool. It contains what might be a
controller, thus allowing you to use your Arduino to control things like robots.

MicroSD Shield
Because of the limited space typical in most Arduino, it might make sense to
connect a microSD shield to the board. This will allow you to input a microSD
in your board and use its memory space for extra storage functions. It typically
comes with an SD library.

Ethernet, Wi-Fi, GPS… Shields


WiFly Shield
Called Wifly shield by SparkFun, this is a mainstay shield that equips your
Arduino with the ability to connect to wireless networks (802.11b/g). It is
capable of acting as both the web client or server and even both.

Arduino Wi-Fi Shield


This is one of the classic shields. It allows the Arduino to connect to a Wi-Fi
router and allow it to host web pages and surf the web.

Arduino Ethernet Shield


This is just Arduino Wi-fi with wires. It is a bit more popular than the Wi-fi
shield though, because of its ease of use. It imbibes your Arduino with the
capability to surf the world wide web freely and comes with a very large library.

XBee Shield
XBee provides Arduino with the ability to communicate wirelessly. While it
cannot connect to world wide web, it can be used to wirelessly start sprinklers,
lights, and coffee machines. It is also very cheap and easy to use.

w/ SM5100B Cellular Shield


This basically turns your Arduino into a cellular phone. It allows you to send
text messages and receive messages. Just connect a microphone and speaker to it
and you may just have yourself another phone.

GPS Shield
Like its name suggests, this shield allows you to use the Global Positioning
system with Arduino. With this, you will always know where you Arduino is.

Electric Imp Shield


This is quite a unique shield, and doesn’t deserve its low position on this list at
all. It looks like a microSD. This shield also allows the programmer to use Wi-Fi
(host web pages, surf the net, etc), but it is significantly more powerful than
anything else on this list.
Sound Shields
VoiceBox Shield
This is a sound alteration Shield capable of altering the voice of anyone speaking
to it. It is used to give the user’s voice a robotic, mechanical sound.

Music Instrument Shield


This shield was designed to be able to make a variety of sounds. It uses the
MIDI protocol to, when connected to Arduino, turn it into a bank of musical
instruments. It is capable of making a library of sound effects like piano sounds,
drums, etc.

Mp3 Player Shield


This turns Arduino into an Mp3 player. It comes with a library. By simply
adding speakers, microSD you can transform your Arduino into a sound machine
of whatever specificity you want.

Spectrum Shield
This allows Arduino to listen to various sounds and turn them into frequencies,
before presenting it in a graphic equalizer display.

Display Shields
Color LCD Shield
This is a small screen component that allows you to display text and pictures
with a 128x128 cell phone color LCD.

CMUCam Shield
This will turn Arduino into a camera. This component is a small camera that
allows the user the option of vision. It is especially useful to users who may be
using their Arduino to control small robots by allowing the user to visually track
it.
Motorz! Shields!
PWM Shield
As I had mentioned earlier, pulse-width modulation can also be used to drive
servo-motors, beyond just dimming LEDs. This shield allows Arduino a fine
range of control over servo motors.

Monster Moto Shield


This allows the user to drive servo motors much like the PWM shield, but this
shield can handle much beefier ones than the other shields could handle.

Ardumoto Motor Driver Shield


This is the most popular of its class. It is the classic when it comes to driving
servo motors with Arduino.

Installing Shields
Preparations
Many shields are made without headers attached. This allows the user a degree
of freedom to alter how the headers are used (Straight male headers rather than
stackable headers or the other way around).

Attaching a header is a simple process with very few steps. You will need a few
things from your kit however. You will need solder, soldering iron, wet sponge,
Arduino board and 4 headers (the original ones or the new R3 ones). You may
also optionally have a soldering iron stand, solder wick and maybe a third hand.

Before you begin, make sure the headers you have match your Arduino footprint
(use the new shield header for R3 layouts and the old headers for Arduino with
that type of header layout).

There are two types of headers. If you will be stacking shields, it is advisable to
use the stackable header and the male header tor single shield works. Male
headers make a lower-profile stack when used to stack shields compared to
stackable headers, but, stackable headers allow you to still insert jumper cables
into the Arduino when the shields are stacked.

Note: stick to headers that have straight, rectangular and male pins for now.
They are easier to work with, and most Arduino components come adapted for
male header pins.

Assembly
Attaching the Header
Headers should be inserted into the shield first. Orientation is of utmost
importance. The headers should face the correct direction. Male pin headers
should enter the top of the shield and extend downwards. Solder the pins only
once you have the header facing the right direction.

Once the headers are inserted properly, flip the board so that the female side
rests on the flat work-table. Align all headers carefully so that they rest
perpendicular to the Shield.

Soldering
Carefully solder a single pin on each inserted header, this ensures that the
headers remain perpendicular to the shield (in the event of a shake). Ensure the
solder is not too much for each pin.

Testing
Carefully Align the Shield with Arduino and plug it in. This ensures that your
Shield headers are properly aligned. If it is not an immediate fit, please realign
the board and perform the above steps again until the fit is exact.
Soldering
Once your shield headers pass the above test, then solder the rest of the pins to
the shield. Once all your pins are soldered, please check for bad solder joints.

Bad Joints
There are possible mistakes when soldering. Please check that your solder
doesn’t link two pins together if you do not want a short-circuit. Also check for
cold solder joints (they are not soldered but look like they are).

Plug in
It is good practice to disconnect your Arduino before working on it. Now plug in
the Shield by matching Arduino headers to the ones on your shield. Please be
careful not to bend your header pin while doing this.

Congratulations, you have connected your shield to Arduino.

Tricks
A known trick is to use an old shield to aid in aligning the header.

Aligning a male header is significantly easier to align than stackable headers.


This is because you can just plug your pin directly into the Arduino first before
carefully laying your shield on it.

Solder away.

Be careful not to burn your header by leaving the soldering iron on the pins for
too long.

Library
Arduino libraries are useful when a programmer needs to make a complex task
as simple as possible. These are contained as part of the extensive add-ons
available to all Arduino users. An example is writing a code to capacitive touch
sensing, while we could spend a few days writing and perfecting the code on our
own, we could just get a code from a great library and implement it into our
Arduino.

You can learn all about how to download and install libraries at the official
Arduino library website. It comes with great instructions about using the
Arduino IDE library manager. (https://www.arduino.cc/en/Guide/Libraries/).

Using Library Manager


Already listed in Arduino 1.5 version and greater is a large collection of
libraries. It contains almost anything you may need to use your Arduino for.
Open the library manager and install any library you want to use with a single
click.

You may also click on “Add .ZIP library” to install any “.zip” library you have
from elsewhere.

Users of older versions of Arduino may follow these steps:

Manual Installation
First, you will have to download the library from the web

Locate the “.zip” file on the computer and double-click to open it


and extract the folder contained inside

In most library folders, there will be a “.h” and a “.cpp” file.

Copy the whole file.

Open your Documents folder, in it will be an Arduino folder, open


it.

Navigate to libraries and past your copied file in that folder.

Edit the name of your pasted folder to remove any symbol that is
not A-Z and 0-9. If you do not do this, you will not be able to use it.

Restart your Arduino if it was already open and by navigating to the


examples folder, you will see the contents of your library there. You
may now open it.
Chapter 6
Practical Projects

LED Cube with Arduino


The aim is to make a LED cube that pulsates at regular intervals and while
visually compelling, it is a simple project. We’ll will need to utilize multiplexing
to reduce the power draw.

This is a very good project where you will get the much-needed practice on
soldering.

You will need to obtain the following hardware:

Arduino UNO

64 LEDs (3.3V)

10 resistors (the resistor value will depend on the voltage of your


LED)

Craft wire

Prototyping board

Drill of the same size as LED

Crocodile clips

A wooden holder in a 4x4x4 cubic configuration

Because of the limited number of pins available on Arduino UNO, we will build
the 4x4x4 cube using multiplexing. This allows us to break down to 4 layers.
This means that we only need to control just 16 LEDs directly.

We simply need to activate a layer and the control pin to light a specific LED,
meaning that we can control all the 64 LEDs with just 20 pins total.
Each layer will be built with a common cathode which will lead to a single pin.
Each LED will be linked to the one above and below it, and since we have 16
layers of positive and 4 layers of negative LED pins, we can do this easily.

The directions are:

Fold the LEDs short leg and drill the needed holes in your wooden
placeholder. It needs to be very tight. The holes should be
equidistant from each other and the folded legs should be of the
same size. Follow the directions as shown in the picture.

Solder the short legs (cathode) on a thin craft wire as shown above.
Test the above configuration using the blink code by connecting a
resistor and ground to cathode (1 pin for all four), and 5V to each
anode and run it. It should light up all the LEDs. If not, all LEDs
light up, check your connections again.

Now do the same for all the remaining 60 LEDs and ensure the
connections are solid.

Then arrange all the 4 LEDs in a cube configuration and ensure the
vertical legs (anode) are soldered together while the cathode is
similarly linked per layer.

If you cannot get a perfect fit for anodes, use a clip to hold them
together and keep them at appropriate height. And ensure anode
only connects to anode. You may snip any out of place wire/leg to
ensure a smoother build.

Once you have your cube, connect the resistors to your prototyping
board and your board to the cube wire frame in what order you want
(LED to board first before resistor or resistor to board first before
LED).

Once your pins are finally connected (the 4 cathode layers to analog
pins 2 to 5, 16 LED anode pins to digital pin 0 to 13 and analog 0
and 1), and we are done.
Upload your code:

https://github.com/brucetsao/eLedCube/blob/master/LED_1cube_4x4x4_Blank_Show_/LED_

Now you can see what it does. You can modify the code by using
“plane(layer)number” to choose the LED you want to command. Ensure that
all other planes are HIGH before commanding a LED otherwise everything will
light up.

GPS Tracking with LoRa Shield


With the proliferation of satellites in todays’ world, the ability to know where
someone is, is in popular demand. Are you the suspicious husband, the worried
father, the sophisticated stalker…? the GPS has become an asset everyone
wants.

As an Arduino fan, the question should be, can you can build your own GPS
tracker with Arduino? Yes, you can. In this project, our aim is to build an
Arduino based GPS tracker.

We are using LoRa because of its low power requirement and long-distance
operation.

To build this, we will need the following Hardware:

NEO-6M GPS module, a transmitter, a 16x2 LCD, 433MHZ LoRa module (or
whichever one is legalized in your locale), 433MHZ LoRa antenna, connecting
wires, Arduino Uno and the Arduino LoRa shield.

To build the LoRa shield we will be using this circuit diagram:


The Arduino shield consists of a 12V jack whose purpose will be to regulate the
3.3V pin for the LoRa module and to power Arduino through the vin pin. The
regulated 5V will thus be used in powering the 12x6 LCD. The two resistors R1
and R2 will act to fix the voltage of the LM317 regulator. An external regulator
is more reliable than the Arduino’s own internal voltage regulator. Included
within the shield will be a potentiometer with the purpose of regulating the
LCD’s brightness.

To design your own PCB:


Download the PCB design software, install it, open it and format
your PCB tracks.

Go to (https://www.pcbgogo.com/?code=t) and log in or sign up.


Enter your PCB dimensions in the prototyping tab.

Select “quote now” and change whatever parameters you want. It


costs about $5 and will be delivered in 2-3 days.

Upload the Gaber file generated by the PCB software and once your
file has been verified, you may use whichever payment option you
want.
Once you get the PCB, you may start assembling the board.

Download the LoRa library (https://github.com/sandeepmistry/arduino-LoRa).

You will need two shields for this project, one for transmission and the other as a
receiver. The receiver will be the one with the LCD attached.

Now that you have the transmitter module ready, you may connect your GPS
module.

Connect the pins D4 to RX and D3 to TX, and ppower it with the 5V pin.

You will need to download the TinyGPS++


(https://github.com/mikalhart/TinyGPSPlus/archive/master.zip) Library to
interprete the data sent from the GPS module (NMEA sentence).

Coding:
Ensure that you have downloaded and installed the two libraries in your IDE
before proceeding.

To program the transmitter, we use the following code:

https://circuitdigest.com/microcontroller-projects/lora-based-gps-tracker-using-
arduino-and-lora-shield

Once our codes are uploaded, power up the transmitter and the LED on the PCB
will start blinking. The receiver will similarly turn on and display the welcome
message we typed in the above code.

Once the transmitter receives data from the satellite, the LCD will immediately
display it.

The next step is to put the transmitter where you want; car, bag, etc. and you will
be able to track whoever is currently carrying the transmitter with the receiver.

Motion Sensitive Light Switch


This type of project has many advantages. Using a motion sensitive light, it can
be a security system that detects intruders in the compound to wake up the
resident, it can be used as a responsive night light (lights on when the resident is
wake) or any other number of ways.

The motion sensor will detect the movement of a trespasser and automatically
switch on for 40 seconds. How you code it depends mostly on how you want to
use it.

The hardware we will need are:

Arduino Uno, PIR motion sensor, a 5V relay module, a breadboard, a 100Ω


resistor, a power supply and LED.

***Note: you will be connecting your project directly to the mains (230-240V).
Touching any live wire directly will can kill you. Be extra careful.***

The circuit diagram will follow these steps:

We will connect an LED to Arduino’s pin 13 and the PIR data OUT
pin to Arduino’s pin 8. The LED will indicate that the light has
turned on or off.

Pin 9 of Arduino will connect to IN1 pin of the relay module and a
bulb will be connected to the mains of the Relay (one to mains
supply and the other wire to NO relay contact).
COM of the relay will link up with the other wire of main.

The sensor will link up with pin 8 on Arduino and its ground pin to
ground. Its main pin must be connected to the Arduino’s pin 13
through the breadboard.

Please be careful when connecting to mains (240V AC), if you are


not sure, examine the circuit diagram again.

The code below will then be loaded into the Arduino IDE:

https://www.maxphi.com/pir-motion-sensor-light

Once someone enters the range of the sensor, the sensor detects the movement
through infrared, it’s OUT pin changes from LOW to HIGH, and alerts the
Arduino which changes its configuration from relay pin HIGH to LOW.

This will cause the light to come on.

Once the intruder leaves, the sensor no longer detects motion and changes its
configuration back to LOW from HIGH. This in turn causes Arduino to assume
a HIGH command at the relay pin.

This design is easily applicable as: Garage Lights, Bathroom Lights and Security
Lights.

Build a Personalized Alarm System


The previous project was about making use of a light bulb to warn you of an
intruder in your home, and its numerous other uses. This new project will make
use of a buzzer to make a fully functional home alarm system to keep you safe at
night.

This project will make use of:

Arduino UNO, buzzer and PIR motion sensor.

From the short list of required hardware, this may very well be the easiest and
least demanding project you will do in this chapter.
From your Arduino board to your sensor, connect VCC to 5V pin
and GND to the GND pin.

Connect the Arduino’s pin 2 (digital) to the output signal pin on the
sensor.

Connect Arduino’s GND pin through a breadboard or directly to the


buzzer’s negative terminal.

Connect Arduino’s digital pin 9 to the positive terminal of the


buzzer.
The circuit follows the diagram below.

We can then upload our code:

https://maker.pro/arduino/tutorial/how-to-build-an-arduino-powered-motion-
sensor-alarm

The above code, once uploaded and the Arduino, sensor and buzzer set in a
position of our choice, will make the buzzer sound whenever someone is within
6-7m of the sensor.

The Arduino’s digital pin 2 is written as HIGH OUTPUT and this will cause the
condition for “intruder_detect()” to start running.

The “siren()” code functions using PWM signals of varying frequency to


simulate an alarm sound.

Intruder detected will be printed on the serial monitor and after a minute of the
intruder leaving the sensor range, the buzzer shuts down.

Sensitivity and time can be modified as liked within the code based on the sensor
type being used and its range.
Arduino Digital Clock with RTC
Much like the above project, we will need a few things:

Arduino UNO
2 LED

DS1307 RTC

330K and 4 120K resistor

The circuit uses a multiplexing technique to reduce the number of wires that are
used to link with Arduino while similarly reducing the power consumption
significantly.

The RTC module, keeps track of the time and compensates for drifts like leap
years. We only need hour and minute information though, so that is all we will
extract from it.

The circuit makes extensive use of the breadboard to link multiple pins to the
same Arduino pin. The colored chart describes what is linked to what.

To set the time, open the IDE include the library “DS1307RTC” you have
downloaded, ensure the time is correct and run the serial monitor.

Once that is done, we upload the code found here:

https://electronics-project-hub.com/arduino-7-segment-display-clock-with-and-
without-rtc/

The libraries can be found here: (https://github.com/PaulStoffregen/Time)


(https://github.com/PaulStoffregen/DS1307RTC)
(https://github.com/DeanIsMe/SevSeg).

The next thing to do is to power up the module and watch it display the time.
The RTC though, is still vulnerable to temperature variations. For high accuracy,
you will need an RTC with inbuilt temperature compensated crystal.
Game Controller with Unity
The aim is to design an awesome game controller with very few steps. This
tutorial seeks to design a game controller powered by Arduino UNO with the
Unity game engine. The controller will be tested by using it to avoid objects.

For this project we will need the following hardware:

A breadboard

Arduino Uno

Unity game engine

An Uniduino plugin

10K resistor and potentiometer

Hook-up wires

You may purchase an Arduino starter kit that contains most of this from here
(https://www.makeuseof.com/tag/4-best-starter-kits-arduino-beginners/).

Building the controller will follow this circuit diagram:

Once you have your circuit built as described above, open the code
StandardFirmata<Firmata<Examples found in files of your IDE.

Upload what you get and open Unity.

Look for the plugin in the asset store and buy it. It is fairly cheap.
While it can be done without the plugin, you may want to go
(http://www.alanzucconi.com/2015/10/07/how-to-integrate-arduino-
with-unity/) here for that.

Follow the video to make sure everything is working right.

Now, set digital pin 2 to INPUT and analog pin 5 to ANALOG.

You can use unity to program a simple game that you can test your
controller with.

Go to Assets>Uniduino>Prefabs and drag the prefab into your


hierarchy on a new scene.

Choose in your hierarchy Create>Sphere and transform it to the


bottom of the game.

You will now need add a new script into the hierarchy by heading into Add
Component < New Script.

Next, you should rename the C Sharp object and add the new script to the
GameObject by clicking on Create < Add.

Type in the codes in the link into your new script:

https://www.makeuseof.com/tag/make-custom-game-controller-arduino-unity/

Read the above code and note the comments to understand what it does.

Save the script and exit back to editor. There you will change the values for pot
pin number to 5, button pin number to 2, left edge to -9.5 and right edge to
9.5.

Add:
void Update ()
{
//We assign the value the arduino is reading from our potentionmeter to our
potValue variable
potValue = arduino.analogRead(potPinNumber);
}

To SphereMover script’s update. Check back to the Uniduino option in


Hierarchy and ensure the port is still accurate/there. If not, change port name
to that of the Arduino.

Now select play for the sphere in hierarchy.

So that we will not have to calibrate and calculate out potentiometer values, we
can add:

https://www.makeuseof.com/tag/make-custom-game-controller-arduino-unity/

To the C#Script<Create<Project panel. This is an extension method built into


the Unity plugin.

Heading back to the script, we will use the remap functions to convert the pot
values into useable ones for our game.

Under our typed in pot value, add:

mappedPot = potValue.Remap();

and we can enter our values into the code by:

mappedPot = potValue.Remap(0, 1023, leftEdge, rightEdge);

Click on save and the Mapped Pot values will now change with movement of
the potentiometer.

Now, open the script and assign your new values thus;

//Assign the mapped pot value to the sphere's x position


transform.position = new Vector3(mappedPot, transform.position.y,
transform.position.z);

Now, you can click on play and the movement of your potentiometer will
correspond to your game character.

Traffic Light Controller


Our last project will be the very simple traffic light controller. Like it’s name
suggests, our aim is to build an Arduino that can control signal lights.

Hardware components:

10K resistor

Breadboard and Arduino UNO

Connecting wires and three LEDs (green, red and yellow)

A pushbutton switch

Six 220Ω resistor

Below is the circuit diagram we will be using for this project.

The resistors will connect to the LEDs cathode on one end and to D8 to D10 on
the other end. The LEDs on the other end are connected to both the resistor and
ground (cathode), and also connected to the 5V pin on the anode leg.
Once we have our circuit up and running, you can find the code here:
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
As can be seen from the code, it is very similar to blink a single LED.
With the exception of the “changelights()” function, the rest of the code is
almost the same.
The traffic lights can be changed in several ways to satisfy our own timing by
simply changing the values in the code.
And now, we have our traffic light controller.
A fairly nice way to round off right? Wrong.
Why don’t we alter the code to allow someone else to choose when it turns
RED without altering the code?
You would have noticed from the above that you did not use all the hardware
you were told to get.
Follow the circuit below:

The difference between the two circuits is academic. The button in this circuit is
connected to pin D12 and the switch now has a resistor attached to it (10K).

The code can be found here:

https://www.makeuseof.com/tag/arduino-traffic-light-controller/

What the new code does is wait for 15 seconds after the button is pushed before
the light changes. This allows someone to control the lights by pushing the
button.

Why don’t we also add a junction to our traffic lights controller?


Just follow the circuit below:

The original LEDs are connected as in the previous examples and the
pushbuttons have been removed. The new LED sets are connected to D11- D13
using a similar method to the earlier examples.

Upload the following code:

https://www.makeuseof.com/tag/arduino-traffic-light-controller/

Unlike the previous examples, when one set of lights is red, the other will turn
green and vice versa.

This is the same method that most street traffic controllers use.

However, since they do this over a large area without any wired input, they must
be communicating over the web.

Arduino can also do this. We will explore this avenue in our next chapter.
Chapter 7
Smart Appliances and The Power of the Web

Connecting Arduino to the Web


With the rapid adoption of internet services around the world, it has become
necessary for new electronics producer to make products that can be used
wirelessly. It is almost impossible for a single person to learn the limits of what
is possible with Arduino. We will be practicing connecting Arduino to the
internet by converting it into a weather monitoring station that can upload data to
an online cloud service.

We will be using Arduino boards and the free web services (http://freeboard.io/)
and (http://dweet.io). After this lesson, you should be able to build your own
internet of things dashboard for household automation applications.

You will need; Arduino Uno, DHT11 sensor (or DHT22), 4.7K resistor,
photocell (with 10K resistor), CC300 Wi-Fi chip (Adafruit CC300),
breadboard and finally, jumper cables.

You will also need to get the following libraries:

DHT sensor library (https://github.com/adafruit/DHT-sensor-library)

Adafruit CC300 library (https://github.com/adafruit/Adafruit_CC3000_Library)

Finally, create an account on freeboard using the earlier link.

Install the library using the methods you learned above.

Hardware Install
Connect the Arduino 5V pin to the positive rail on the breadboard,
and ground the board by connecting the ground pin to the negative
rail.
Place the CC300 board and the DHT sensor on the breadboard.
Connect pin 1 of DHT to the positive rail on the breadboard and pin
4 to the negative one.

Connect the sensor’s pin 2 to Arduino’s pin 7, and connect the 4.7K
resistor between pin1 and pin 2 of the sensor to complete that part of
the circuit.

Connect the cell in series with the 10K resistor on the breadboard
and connect the ground the other end of the resistor.

The common pin on the photocell should then connect to analog pin
A0.

Connect the Wi-Fi module by linking it’s IRQ pin to Arduino pin 3,
CS to pin 10 and VBAT to pin 5.

Connect SPI pins to Arduino by linking MOSI to pin 11, MISO to


pin 12 and CLK to pin 13.

Finally connect Vin to Arduino 5V (positive rail) and ground to


ground (negative rail).

Testing the sensors:

// Libraries
#include "DHT.h"
// DHT sensor
#define DHTPIN 7
#define DHTTYPE DHT11
// DHT instance
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
// Initialize the Serial port
Serial.begin(9600);

// Init DHT
dht.begin();
}
void loop()
{
// Measure from DHT
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Measure light level
float sensor_reading = analogRead(A0);
float light = sensor_reading/1024*100;
// Display temperature
Serial.print("Temperature: ");
Serial.print((int)temperature);
Serial.println(" C");
// Display humidity
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%");
// Display light level
Serial.print("Light: ");
Serial.print(light);
Serial.println("%");
Serial.println("");
// Wait 500 ms
delay(500);

}

The above code is a simple one designed to test if the sensors are working or not.
As you can see, the code is explained using comments. The complete code is in
the library mentioned earlier.

Upload the sketch and the data will display something like:
Temperature: 25 C
Humidity: 36.00%
Light: 83.79%

Now that the sensors are working, we need to make it capable of connecting
electronically to Wi-Fi. Dweet has “things”, this is a place where you upload
data through http requests. Should you upload data to a new thing that has not
been created before, it would be instantly created.

The code below automatically connects to the freeboard server and uploads the
data.

// we state the Libraries we want to use


#include
#include
#include "DHT.h"
#include
// Define pins that CC3000 are connected to
#define ADAFRUIT_CC3000_IRQ 3
#define ADAFRUIT_CC3000_VBAT 5
#define ADAFRUIT_CC3000_CS 10
// DHT sensor
#define DHTPIN 7
#define DHTTYPE DHT11
// Create an CC3000 instance for the chip
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS,
ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIV2);
// DHT instance
DHT dht(DHTPIN, DHTTYPE);
// WLAN parameters enter your own details into all parameters
#define WLAN_SSID "yourWiFiNetwork"
#define WLAN_PASS "yourPassword"
#define WLAN_SECURITY WLAN_SEC_WPA2
// give a name to your thing, it’s advised to used a very complicated one
#define thing_name "yourThingName"
// Variables to be sent
int temperature;
int humidity;
int light;
uint32_t ip;
void setup(void)
{
// We initialize the CC300 chip
Serial.begin(115200);

Serial.println(F("\nInitializing..."));
if (!cc3000.begin())
{
Serial.println(F("Couldn't begin()! Check your wiring?"));
while(1);
}
// Connect to local WiFi network
Serial.print(F("Connecting to WiFi network ..."));
cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
Serial.println(F("done!"));
// if the sketch hangs, this code will reset it. It is called a watchdog
wdt_reset();
/* Wait for DHCP to complete */
Serial.println(F("Request DHCP"));
while (!cc3000.checkDHCP())
{
delay(100);
}
}
void loop(void)
{
// Measure from DHT
float t = dht.readTemperature();
float h = dht.readHumidity();
temperature = (int)t;
humidity = (int)h;
// Measure light level
float sensor_reading = analogRead(A0);
light = (int)(sensor_reading/1024*100);
Serial.println(F("Measurements done"));
// Start watchdog
wdt_enable(WDTO_8S);
// Get IP
uint32_t ip = 0;
Serial.print(F("www.dweet.io -> "));
while (ip == 0) {
if (! cc3000.getHostByName("www.dweet.io", &ip)) {
Serial.println(F("Couldn't resolve!"));
}
delay(500);
}
cc3000.printIPdotsRev(ip);
Serial.println(F(""));
// Reset watchdog
wdt_reset();
// Check connection to WiFi
Serial.print(F("Checking WiFi connection ..."));
if(!cc3000.checkConnected()){while(1){}}
Serial.println(F("done."));
wdt_reset();
// Send request
Adafruit_CC3000_Client client = cc3000.connectTCP(ip, 80);
if (client.connected()) {
Serial.print(F("Sending request... "));
client.fastrprint(F("GET /dweet/for/"));
client.print(thing_name);
client.fastrprint(F("?temperature="));
client.print(temperature);
client.fastrprint(F("&humidity="));
client.print(humidity);
client.fastrprint(F("&light="));
client.print(light);
client.fastrprintln(F(" HTTP/1.1"));
client.fastrprintln(F("Host: dweet.io"));
client.fastrprintln(F("Connection: close"));
client.fastrprintln(F(""));
Serial.println(F("done."));
} else {
Serial.println(F("Connection failed"));
return;
}
// Reset watchdog
wdt_reset();
Serial.println(F("Reading answer..."));
while (client.connected()) {
while (client.available()) {
char c = client.read();
Serial.print(c);
}
}
Serial.println(F(""));
// Reset watchdog
wdt_reset();
// Close connection and disconnect
client.close();
Serial.println(F("Closing connection"));
Serial.println(F(""));
// Reset watchdog & disable
wdt_reset();
wdt_disable();
// Wait 60 seconds until next update
wait(60000);
}
// Wait for a given time using the watchdog
void wait(int total_delay) {
int number_steps = (int)(total_delay/5000);
wdt_enable(WDTO_8S);
for (int i = 0; i < number_steps; i++){
//Serial.println(F("Waiting for 5 seconds ..."));
delay(5000);
wdt_reset();
}
wdt_disable();
}
Let’s now go into the details of the code. It starts by importing the required
libraries:
#include
#include
#include
#include "DHT.h"
#include

The above code can be modified to suite our own needs as noted by the
comments scattered through it. Now that the data has been sent to freeboard,
Arduino will consistently send code over to the server.

To display the data graphically, we use freeboard.io to create a new dashboard


and display our data in human understandable visuals.

Making Household Appliances Smart


A possible use of the above topic, is the ability to switch on or off household
appliances without having to physically touch it. We will demonstrate below.

We will be doing this using a 5V relay to switch a power outlet on and off. The
Arduino will use a sensor to determine when to switch the relay.

While it is possible to switch on the device alone directly, due to the dangers of
leaving an unmonitored switch on, it is always better to just control the switch
relay alone. Not to mention, the ability to use a single Arduino to switch on
multiple devices.

The plan is to install a 5V relay inside a power outlet box using a grounded
extension cord.

We will need the following hardware parts for this project:

Arduino UNO, electrical outlet box, electrical outlet, power strip, Signal, VCC
and ground wires, SRD-05VDC-SL-C 5V relay, electrical outlet box cover plate
and a 3/8” NM/SE connector.

Now for the assembly:

Cut the power strip to determine which of the three wires in it


connect to each prong on its plug (ground, live and neutral). You
may use a continuity tester to determine this.

Remove a knock out plugs from the outlet box, and install the
NM/SE connector in its place.

Remove some of the outer sheathing of the cord and feed it into the
electric outlet box through the connector (3-4”).

Carefully off 4” of the live wire and remove about ¼” of the cut off
live wire insulator and insert it in the NO terminal of the relay, and
connect the ground, signal and VCC wires to the relay.

Connect the remaining live wire into the C terminal of the relay and
ensure it is a fit.

Secure all the wires and the relay in the box and make sure they can
all fit well.

Secure the live wire from the NO relay terminal to the hot terminal
of the power outlet (the one with the smaller slot) with the gold
screws.

The neutral wire from the power cord should also be secured to the
neutral terminal of the outlet (left side with larger slots) with the
silver screw.

Also, secure the ground wire to the ground terminal outlet (D-
shaped) with the green screw.

Screw the outlet into the box and ensure it fits, then cover it up and
screw in the cover.

We now have an outlet that can be easily controlled by Arduino. All that
remains, is to connect the pins to your Arduino and upload code, and we are
done.

The connections should follow the above design. The USB will lead to the
computer, or you may attach a battery to it using one of the examples given
previously. The bulb can be anything, from your coffee machine to your washing
machine.

We will connect a DHT11 humidity and temperature sensor to Arduino so that


the bulb turns off when humidity exceeds a certain level. To upload the code,
connect Arduino to your computer, and upload this code.

#include <dht.h>
dht DHT;
#defines DHT11_PIN 7
int pinOut = 8;
void setup(){
Serial.begin(9600);
pinMode(8, OUTPUT);
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
// DHT.humidity can be changed to DHT.temperature
if (DHT.humidity <= 40){
// the value <= 40 can be changed to any humidity or temperature
digitalWrite(pinOut, HIGH);
} // tells the pin to allow current flow. The bulb turns on
else {
digitalWrite(pinOut, LOW);
} // tells the pin to prevent current flow. The bulb goes off
delay(500);
}
The above code is similar to the one we uploaded previously to send data to the
web. It takes in the humidity and temperature data and tells the power outlet to
switch on when humidity reaches 40%. This can also be done to tell the bulb to
turn on when temperature is below 300K by changing the values as noted in the
code.

Controlling Arduino with a Smartphone


We talked about getting Arduino to send data to the web in the previous topic,
now we will talk about using your android phone to control a higher voltage
device.

We will explain in this tutorial, how to control Arduino directly from your phone
and with a web browser

To accomplish this task, we will need to purchase or build the following:

An Arduino robot

HC-05 Bluetooth Module

Android with OS 2.2 or 2.1 and above.

A Google account and a Bluetooth controller App.

The Bluetooth Module will have its 5V pin connected to Arduino’s


5V pin and it’s ground pin connected to that of Arduino.

You may connect the Bluetooth TX pin to Arduino’s RX pin only


since there is no data to be received from Arduino.

You may completely remove the distance sensor from the Arduino
if you wish and connect pin 9-12 of Arduino to IN1-IN4 of the
Motor module as above, and the Enable pins should connect to 5V
using a jumper.

The Bluetooth module may be placed above or below the chasis.

The following code will then be uploaded.

You may download the code here. https://roboindia.com/tutorial-


content/arduino_code/Stepper_Motor_Arduino.zip

The code is explained using comments. From what we had done above and a
little experimentation, the code becomes clearer still.

The next step is to open the Bluetooth controller application. The application can
be gotten on google play.

Configure the control keys in app paying attention to how you configured it in
code.

When say the forward key is pressed, Arduino receives the data through
Bluetooth communication as 1 and Arduino will thus make IN1 and IN3 HIGH
while IN2 and IN4 will become LOW. This achieves a forward motion. The
same system will be used for the other motions, granting free command over the
motions of the robot.

This is unfortunately not as useful as a Wi-Fi module because, the range is 10


meters. There must also be sufficient power provided to the Bluetooth module to
prevent it from shutting down.

Wi-Fi Remote Control Using ESP8266


Controlling Arduino with Wi-Fi is a very straightforward process. You will hope
to learn how to use the Wi-Fi module under this topic. As can be seen from
examples in the previous tutorials, there has been a certain common method to
codes and circuits we have been building. From the examples above, we know
which pins transfer which information.

As with the Bluetooth example where we did not connect the TX pin because it
was not needed, the same is true for all modules. The circuit you will build with
a module is highly dependent on what you want to do with it, and thus, the kind
of information it will transmit.

The plan for this last project of ours is to build a Wi-Fi controller to any device
with Wi-Fi access using a Wi-Fi nunchuk that has been made from an ESP8266.

While it is possible to program the ESP8266 itself, it is generally preferable to


program Arduino and have it control the Wi-Fi module.

While the aim of this tutorial is to produce a serial terminal data, it is very easy
to use another Arduino to read the serial string output and act on it.
We will need the following hardware:

Arduino Mega (this is because it has two serial ports, since using UNO might
make the Arduino impossible to reprogram as the module will assume control of
the programing port once it is running), ESP8266 Wi-Fi module, jumper wires,
breadboard, FTDI chip or another Arduino and battery.

There are many ways of connecting ESP8266 to Arduino, however, we will be


using the following method:

Connect a red jumper to the 3.3V power pin, a brown one to the
3.3V pin (enables chip), a white one to TX, a grey one to RX and a
black one to ground.

The TX jumper cable will be connected to RX1 on ArduinoMega


and the RX cable will lead into TX1 on ArduinoMega.

Since nunchuk communicates using i2c, most Arduino will come


with an inbuilt i2c bus (they also have their own connection plugs,
but you can just use jumper wires and A breadboard or jumper wires
only). Connect the nunchuk. SDA pin - analog 4 and SCK - analog
5. (Do not buy off-brand ones, stick to Nintendo nunchuk.

To set up a server to communicate with the ESP8266, we use the code on this
instructable page (https://github.com/splatspace/ esprelay/). It allows the
communication of two devices to log on to any computer that is running the
code.

You will need to install Python 2.7 on your PC in order to run the code.

Follow the above steps to setup a receiving ESP8266. It will


diagnosis if the Wi-Fi module is not running well. An FTDI chip is
connected to the model so that a USB port can be used to receive
serial data. This data is then examined on the PC.

Add a battery to the model because the FTDI module is not built
with a sufficient power source. This will cause the ESP8266 to
restart regularly if it isn’t fixed.

You may add another Arduino in the place of an FTDI chip if you
wish to use the Arduino to control something.

Load the terminal program you are using. The strings from the
nunchuk will be seen scrolling down the screen as they are received.

Use the code below to setup the ESP8266 typ:

AT+RST

AT+CWJAP="this will be occupied by your Wi-Fi’s SSID", "This


will be occupied by the password of your Wi-Fi"

AT+CIPCLOSE

Type the codes below to enable communication with the transmitter of the
nunchuk;

AT+CIPSTART="TCP", "This will be your IP", 54321

AT+CIPSEND=n (this tells the ESP8266 that ascii characters


should be expected. The n represents the number of characters to
accept.)

ascii string with no quotes\r\n

AT+CIPCLOSE

You can now control what you want over the Wi-Fi.
Chapter 8
Troubleshooting Common Problems
There are a lot of steps to getting Arduino to do what you want, and should any
step be done wrong, it might fail to work/upload. There are a variety of problems
that crop up when using Arduino, yet, most of these problems can often be
traced to a handful of root causes.

The boards physical connections

Microcontroller fuse settings

Access to the serial ports by the code

The drivers for the board

Firmware on 8U2

The bootloader

The board itself

The list of problems that may arise while using your Arduino is too long to list.
So, we will try to go through the most common problems that occur and
recommend ways with which you may quickly fix these issues.

Here are a couple of things to check first, if your Arduino is messing up.

Arduino IDE
The first step to dealing with any problem is to just reinstall Arduino IDE and
reupload your code. If this doesn’t work, you may check the following within
your IDE:

Ensure you correctly selected the right board in the Tools > Board
menu. This is because of differences in the ATmega chips in
differing Arduino types. See
(https://www.arduino.cc/en/Guide/Environment) for more
information on properly selecting your Arduino type.

Make sure that you selected the correct port to which you connected
Arduino. As I had mentioned earlier, unplug and re-plug Arduino to
the computer and carefully monitor the option that appears, if you
did not initially see your Arduino listed under Tools > Serial Port.

If you cannot find Arduino still, then follow the next steps.

Drivers
Drivers are what allows the IDE on your computer to communicate with the
Arduino. What happens when a USB cable is plugged into a system for the first
time is that, the computer accepts drivers that are stored on the board and installs
them. These drivers provide a virtual serial port. Most Arduino use USB CDC
(standard drivers) provided by the operating system while some use FTDI.

If your Arduino type does not appear in the Tools > Serial port menu, then the
driver was not installed.

For windows 7, connect the board again, open the device manager
and update your drivers for Arduino. Right click on the board and
point windows to the “.inf” file. It will be in the drivers/directory
of the IDE file.

For Linux, symlink from /dev/tty/ACM0 to dev/tty/USB0. Then you


may run
sudo usermod -a -G tty yourUserName
sudo usermod -a -G dialout yourUserName

After which you should logout and login for the changes to occur. Open Arduino
again and your port should appear.

Crash
Should the software crash at launch or work unnaturally slowly, or the Tools
menu seems to open too slowly.
Disable Bluetooth serial ports and that of any other networked COM
ports using Device Manager. Since Arduino IDE scans all the COM
ports on the computer upon startup and whenever the Tools menu is
open, these networked ports often cause delays and crashes

Ensure that the only program that scans all serial ports currently
open on your task manager is Arduino IDE. Some Applications that
do this are; virtual daemon tools, BlueSoleil, PDA sync apps…

Ensure the computer is not running a firmware that disables access


to serial ports (ZoneAlarm)

Quit processing, vvv… should you be using them to read data from
the USB cable to Arduino

For Linux, you can try to run the IDE as a root file, and see what
changes

If this doesn’t fix the issue, proceed to the next step.

Direct Connection
Sometimes, the problem arises from physical disconnections from
the board.

Ensure that the Arduino LED is on.

Ensure you are connected directly to both Arduino and the


computer. It there is a USB hub connection, please connect the two
directly and test for changes.

Change the USB cord. Sometimes, this works.

While the code is uploading, disconnect digital pins 0 and 1, and


reconnect them after the upload.

Try disconnecting everything else from the board and uploading the
code.
Ensure Arduino is not touching anything metallic or conductive. As
we had earlier explained, it may ground the board.

The above steps should solve your problems. If they do not, proceed to the next
step.

Auto-Reset and Bootloader


Please do note that some boards do not support this function. On some
computers, you may need to physically press the reset button before uploading,
while on others you will need to upload before pressing reset. It is advised that
you press reset with two to 10 seconds interval using both ways to see which one
your Arduino supports.

This error may be displayed on the IDE.

[VP 1] Device is not responding correctly

This means that you need to try again.

The best way to check if your Arduino comes with a bootloader is to press reset.
If your Arduino LED blinks when you plug it in again, you have a bootloader. If
it doesn’t, then you do not have one.

If none of the above options work for you, the you may need to visit the Arduino
help Forum (http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?
board=troubleshoot). Please use the code tags in the forum toolbar to ensure the
output is in the proper format.

You will need to know, your operating system, Arduino type (with a picture if
possible), your exact problem (can’t upload to the board) and the error message
you receive when you try to upload after enabling verbose output (File >
Preferences > Show verbose output).

Syntax in Arduino
The most common error in Arduino syntax is due to the semicolon at the end of
a statement. The second most common error is due to a missing curly bracket.
Look for incorrect spellings, typos, wrong names for declared values, unallowed
lettering uses and wrong cases. Arduino code is case sensitive. If there’s an error
in your code, the software usually highlights the lines with such errors.

“java.lang.StackOverflowError”
This error often occurs because certain strings can confuse the IDE. Arduino
IDE does preliminary processing by manipulating code on the sketch using
regular expressions.

Look for certain sequences that have certain functions like double quotes, single
quotes, comments or backslashes. Some of these codes, while correct, may
confuse the IDE. An example is ‘“/’, or /”.

at com.oroinc.text.regex.Perl5Matcher._match(Perl5Matcher.java)
at com.oroinc.text.regex.Perl5Matcher._match(Perl5Matcher.java)
or

java.lang.StackOverflowError
at java.util.Vector.addElement(Unknown Source)
at java.util.Stack.push(Unknown Source)
at
com.oroinc.text.regex.Perl5Matcher._pushState(Perl5Matcher.java)

Sketch does not start while you’re powering the board


while using an external power supply
This happens most often because of the disconnection of the RX pin. The
bootloader will see garbage data inflowing without end, thus, it never actually
gets to running your sketch.

Try connecting the TX pin directly to RX, or ground it with a 10K resistor.

Arduino IDE freezes when you attempt uploading a


program
Open Task Manager and check if “LVPrcSrv.exe” is running, if it is, kill it and
reupload the program. This is because the Logitech process sometimes conflict
with Arduino IDE.

Arduino does not light up (the power LED) when


plugged in
Make sure the jumper is on the correct pins.

For the external battery, the jumper should lie on 2 pins closest that are closest
the power plug.

For USB powered projects, it should be the 2 pins that are closest to the USB
plug.

Error launching Arduino on Windows


Arduino has encountered a problem and needs to close.
Should you get the above message when trying to run Arduino.exe on windows,
please try launching with the “.bat” file (It may take a few minutes).

"Could not find the main class." error


Java Virtual Machine Launcher: Could not find the main class. Program will
exit.

If you get the above error on your attempt to launch Arduino, ensure the
“Arduino.zip” files were correctly extracted. The lib directory should contain
“pde.jar” and be directly inside the Arduino directory.

“UnsatisfiedLinkError” in Arduino Library


Uncaught exception in main method:
java.lang.UnsatisfiedLinkError: Native Library
/Users/anu/Desktop/arduino-0002/librxtxSerial.jnilib already loaded
in another classloader

The above is an error caused by loading an old version of Arduino


communications library.

Find “comm.jar or jcl.jar” in the directories in your CLASSPATH or PATH


environment variables (“/System/Library/Frameworks/
JavaVM.framework/”).

Cygwin conflicts
6 [main] ? (3512) C:\Dev\arduino-0006\tools\avr\bin\avr-gcc.exe:
*** fatal error - C:\Dev\arduino-0006\tools\avr\bin\avr-gcc.exe: ***
system shared memory version mismatch detected -
0x75BE0084/0x75BE009C.

The above error displays when you have “Cygwin” running while you are using
Arduino. You can also just delete “cygwin1.dll” from your Arduino directory
and then replace it with “c:\cygwin\bin\”.

Sketch too big


The most common causes of large code is the use of floating point calculations.
We had stated earlier that you should be careful to use as much integer math as
you can get away with in your code. Also you can delete any “#include”
statements made in your code to libraries you will not use for the code. Go
through your code again and look for any code that can be written in shorter
ways. Your chip can only contain 16KB of code.

Advanced troubleshooting problems can be solved by visiting


(https://www.arduino.cc/en/Guide/Troubleshooting).
Conclusion
This may be the end of this book, but it is just a beginning in your journey to
learn Arduino programming.

Are you interested in learning more?

Are you hungry to handle more Arduino projects?

Do you wish we had added more practical examples?

Arduino is the new kid in town, and everybody wants to know how it works. It is
our hope therefore, that having read through this book and participated in most if
not all of the projects, that you would have grasped what Arduino is all about.

Stay tuned for more on Arduino programming.


Appendix
This Appendix contains a list of URLs referenced in this book, and a list of
reference materials that were used to complete this work. You may find them
useful.

To learn more about Arduino, you may visit the following websites:

Arduino’s official site: https://www.arduino.cc/en

Autodesk, Inc: https://www.instructables.com/


URL
Arduino’s official site for buying boards: https://store.arduino.cc/
Adafruit (Arduino clones): http://www.adafruit.com/
SparkFun (Arduino clones): http://www.sparkfun.com/
Arduino IDE (Download): https://www.arduino.cc/en/Main/Software
Ubuntu Arduino IDE installation guide:
https://tutorials.ubuntu.com/tutorial/install-the-arduino-ide#0
Teensy Board installation guide: https://www.pjrc.com/teensy/td_download.html/
Arduino Troubleshooting: https://www.arduino.cc/en/Guide/Troubleshooting
Electrodroid Application to calculate resistance:
https://play.google.com/store/apps/details?
id=it.android.demi.elettronica&hl=en
LED Calculator Tool to calculate resistance: http://led.linear1.org/1led.wiz
Arduino syntax and function homepage:
http://arduino.cc/en/Reference/HomePage/
Arduino library for capacitive sensor:
http://playground.arduino.cc/Main/CapacitiveSensor/
Arduino libraries: https://www.arduino.cc/en/Guide/Libraries/
Arduino guide on Arduino types: https://www.arduino.cc/en/Guide/Environment
Arduino troubleshooting forum: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?
board=troubleshoot
Common Arduino troubleshooting problems:
https://www.arduino.cc/en/Guide/Troubleshooting
DHT sensor library (https://github.com/adafruit/DHT-sensor-library)
Adafruit CC300 library (https://github.com/adafruit/Adafruit_CC3000_Library)
Turn PC into server: (https://github.com/splatspace/esprelay/)
TinyGPS++ library:
(https://github.com/mikalhart/TinyGPSPlus/archive/master.zip)
LoRa library: (https://github.com/sandeepmistry/arduino-LoRa)
PCB order page: (https://easyeda.com/order)
Smoke detector shield PCB design:
(https://easyeda.com/circuitdigest/Smoke_Detector_Arduino_Shield-
kEQca75rN)
Digital clock libraries: (https://github.com/DeanIsMe/SevSeg)
(https://github.com/PaulStoffregen/DS1307RTC)
(https://github.com/PaulStoffregen/Time)
Uniduino plugin: (https://www.assetstore.unity3d.com/en/#!/content/6804)
A sensor sketch code:
(https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-
sr04/)
Self-controlled robot code:
(https://gist.githubusercontent.com/jamesabruce/b2eb4698754ae10e492e/raw/de60648a
robot-test.ino)
LED 4x4x4 code:
(https://github.com/brucetsao/eLedCube/blob/master/LED_1cube_4x4x4_Blank_Show_
LoRa code: (https://circuitdigest.com/microcontroller-projects/lora-based-gps-
tracker-using-arduino-and-lora-shield)
Motion sensor code: (https://www.maxphi.com/pir-motion-sensor-light)
Alarm code: (https://maker.pro/arduino/tutorial/how-to-build-an-arduino-
powered-motion-sensor-alarm)
Smoke detector code: (https://lastminuteengineers.com/mq2-gas-senser-arduino-
tutorial/)
Game controller code: (https://www.makeuseof.com/tag/make-custom-game-
controller-arduino-unity/)
Traffic controller code: (https://www.makeuseof.com/tag/arduino-traffic-light-
controller/)
Reference
Arvind Sanjeev, use a PIR motion sensor to build your own intruder detection
system (2018).

Aswinth Raj, Lora Based GPS Tracker using Arduino and LoRa Shield,
CircuitDigest (2019)

Bekathwia, Arduino Class, Autodesk Inc (2019).

Build an Arduino controlled power outlet; (http://www.circuitbasics.com/build-


an-arduino-controlled-power-outlet/).

Gerald Recktenwald, EAS 199A, Lecture 5: Arduino Programming Part 1,


Portland State University (2010).

https://blogs.umass.edu/Techbytes/2014/01/14/turkeybytes-arduino/

https://electronics-project-hub.com/arduino-7-segment-display-clock-with-and-
without-rtc/.

Ian Buckley, How to Make a Custom Game Controller With Arduino and Unity,
Makeuseof (2016).

James Bruce, How To Make a Pulsating Arduino LED Cube That Looks Like It
Came From The Future, Makeuseof (2012).

Joe Coburn, Arduino Programming for Beginners: Traffic Light Controller Project
Tutorial, Makeuseof (2019).

Miguel Grinberg, Building an Arduino Robot, Part VI: Remote Control,


https://blog.miguelgrinberg.com/post/ (2013).

NCKiwi, Wi-Fi Remote Control Using ESP8266, Instructable circuits (2019).

RAVI, Automatic Room Lights using Arduino and PIR Sensor,


https://www.electronicshub.org/ (2018).

RAVI, Bluetooth Controlled Robot using Arduino,


https://www.electronicshub.org/ (2018).

Rudra P. S. Celebrating Arduino Day (2014)

Ryan Turner, Arduino Programming: The Ultimate Beginner's Guide to Learn


Arduino Programming Step by Step, Kindle (2019).

Tttapa, A Beginner’s Guide to Arduino, Autodesk, Inc (2019).

Vividz, Make Your Own Smoke Detector Circuit Using Arduino, Autodesk Inc
(2017).
ARDUINO

Simple and Effective Strategies to Arduino


Programming
Ethan Thorpe
Introduction to Arduino
Arduino is an open-source platform which provides a low cost, simple interface
to create microcontroller based projects. It’s a great place to start learning and
understanding the real-world application of embedded systems and how
electronics work. its is extensively used for prototyping due to its low cost and
easy connections to the microcontroller. The boards are versatile and have the
peripherals for programming the microcontroller built-in, so no external
programmers are required to program the microcontroller.

Arduino boards and Arduino IDE are open-source, meaning they are licenced in
a way that anyone can use their designs and manufacture the boards which had
led to competition and hence the low cost. It also ensures faster development of
the boards and the IDE.

What is Arduino?
Arduino platform consists of various Arduino boards and the Arduino IDE
(Integrated Development Environment), which consists of code editor to write
the programs, a compiler to compile programs, and it is also used to program the
Arduino boards.

Arduino ecosystem has grown many folds over the years and currently has many
boards for all types of applications. Arduino boards are small microcontroller
boards with other peripherals that have a number of connection sockets (GPIO),
which can be used to connect different sensors and actuators to the board. The
microcontroller is essentially the brain of the board, and it can be programmed to
make any control system. The board also has a Universal Serial Bus plug (USB)
to connect it to the computer. The board can be powered through this plug by
computer or can be powered externally by a 9 volts battery. This port is also
used to program the microcontroller on the board through the computer. The
sensors and inputs, like the buttons, are essentially the things that help the
microcontroller sense the environment; based on these inputs, the
microcontroller take actions as per the program and changes its output.
Chapter 1
Basic Programming Concepts Needed To Get
Started With Arduino
In this chapter, we will introduce the basic programming concepts needed to get
started with Arduino, as well as other types of similar embedded systems. To
learn what you can build with these systems, see chapter 2. Since you want to
learn about Arduino and embedded systems, explore all the chapters one after
another of this book.

Here we will explain programming concepts from the start, and you don't need to
know anything about Arduino or computer programming to get started. If you
already have previous programming experience, this chapter may add some extra
to your knowledge.

We will learn how a simple program works by making some modifications to it


throughout the chapter. If you have access to an Arduino, you can use it
throughout the chapter to practice the concepts learned, making the experience a
lot nicer. You just need an Arduino, original or compatible, and nothing more.
So go ahead.

This chapter is divided into the following parts:


Overview
Computer
Computer program
Programming language
Algorithm (Program)
Variable
Data Type
Assignment
Operator
Function
Function Call
Return Value
Parameters
Comments
Control Structures
While
For
If
If-else
Libraries
Conclusion

Overview
The purpose of this chapter is to quickly and easily present the basics of
programming so you can start using Arduino in your projects without having to
read many programming books or articles. The subject of "software
development" as a whole is very broad, so let's focus only on the concepts that
are important for Arduino and embedded systems in general.

There are many other things to learn about software that we won't cover here. In
the next chapters, we have added information for you to follow to learn more
advanced concepts or software concepts that are not widely used in embedded
system programming.

Let's start by explaining how a computer works (remember that Arduino is, at
the bottom, a computer).

Computer
A computer is simply a machine that processes instructions. These instructions
are processed in the "brain" of the computer, which is called a microprocessor.
Every computer has at least one microprocessor. Arduino, for example, is
nothing but a very small computer, and it uses an ATmega microprocessor.
Some microprocessors, such as ATmega, are also called microcontrollers.
Computer Program
A computer program, or software, is a sequence of instructions that are sent to
the computer. Each type of microprocessor (brain) understands a different
instruction set, i.e. its own "language." We also call this language machine
language.

Machine languages are, at the bottom, the only languages that computers can
understand, except that they are very difficult for humans to understand. That's
why we use something called the programming language.

For systems like Arduino (so-called embedded systems), software that runs on
the microprocessor is also called firmware.

Programming Language
We human beings need to convert our ideas into a form that computers can
process, that is, machine language. Today's computers can't (yet) understand the
natural language we use every day, so we need another special "language" to
instruct the computer to do the tasks we want. This "language" is a programming
language, and there are actually many of them.

These programming languages are also called high-level programming


languages. The programming language used in Arduino is C ++ language (with
minor modifications), which is a very traditional and well-known language. This
is the language we will use throughout this book.

To convert a program written in a high-level machine language, we use


something called a compiler. The action of turning a program to machine
language is called compiling. To compile a program, usually using a
development environment (or IDE, English Integrated Development
Environment), which is a computer application with an integrated compiler,
where you can write your program and compile it. In the case of Arduino, this
development environment is the Arduino IDE.
Text containing the program in a high-level programming language is also
known as the program source code.
Algorithm (Program)
An algorithm, or simply a program, is a way of telling a computer what it should
do, in a way that we humans can easily understand. Algorithms are usually
written in high-level programming languages. This applies to virtually any
computer, including Arduino, where an algorithm is also known as sketching.
For simplicity, from now on, we will refer to algorithms, programs, or sketches
simply as "programs."
A program is made up of a sequence of commands, usually written in a text file.
For this chapter, we will use the commands from the simpler Arduino program,
Blink, which simply turns on and off an LED, and we will wreck it throughout
the chapter. See below the source code of Blink:
int led = 13;
void setup () {
pinMode (led, OUTPUT );
}
void loop () {
digitalWrite (led, HIGH );
delay (1000);
digitalWrite (led, LOW );
delay (1000);
}
Variable
A variable is a feature used to store data in a computer program. Every computer
has some kind of memory, and a variable represents a region of memory used to
store certain information. This information can be, for example, a number,
character, or text string. In order to use a variable in an Arduino program, we
need to make a variable declaration, such as:

int led;

In this case, we are declaring a variable of the type installed led. Next, we will
talk more about the data type of a variable.
Data Type
The data type of a variable means, as its name implies, the type of information
that can be stored in that variable. In many programming languages, such as C
++, it is mandatory to define the data type at the time of variable declaration, as
we saw in the variable declaration above. For Arduino modules that use ATmega
processor, the most common types of data we use are:
boolean: true ( true) or false ( false) value
char: a character
byte: one byte, or 8-bit string
int: 16-bit signed integer (-32768 through 32767)
unsigned int: 16-bit unsigned integer (0 to 65535)
long: 16-bit signed integer (-2147483648 through 2147483647)
unsigned long: 16-bit unsigned integer (0 to 4294967295)
float: real precision single number (floating point)
double: double precision real number (floating point)
string: string
void: empty type (no type)

For all data types supported by Arduino, see the "Data Types" section on this
chapter.

Assignment
Assigning a value to a variable means storing the value in it for later use. The
assignment command in C ++ is the =. To assign the value 13 to the variable led
we created above, we do this:
led = 13;

When you store a value in a variable right at its initialization, we call it a


variable initialization. So in our example program, we have:
int led = 13;

The purpose of this line of code is to say that Arduino pin 13 will be used to
light the LED, and store this information for later use throughout the program.
Fixed values used in the program, such as the value 13above, are called
constants because, unlike variables, their value does not change.
Operator
An operator is a set of one or more characters that serve to operate on one or
more variables or constants. A very simple example of an operator is the
addition operator, the +. Let's say we want to add two numbers and assign them
to a variable x. For this, we do the following:

x = 2 + 3;

After executing the above command, the variable x will contain the value 5.

Each programming language has a different set of operators. Some of the most
common operators in the C ++ language are:
Arithmetic Operators:
+: addition ("more")
-: subtraction ("minus")
*: multiplication ("times")
/: division ("divided by")
Logical Operators:
&&: conjunction ("e")
||: disjunction ("or")
==: equality ("equal to")
!=: inequality ("different from")
!: denial ("no")
>: "bigger then"
<: "less than"
>=: "greater than or equal to"
<=: "less than or equal to"
Assignment Operators:
=: assigns a value to a variable, as we saw above.
As you develop your projects, you will gradually become familiar with all of
these operators. For a complete list, see this Wikipedia page.
Function
A function is roughly a sequence of commands that can be reused multiple times
throughout a program. To create a function and say what it does, we need to
make a function declaration. See how a function is declared in our sample
program:

void setup () {
pinMode (led, OUTPUT );
}

Here we are declaring a function with the name setup(). What it does is execute
the commands of another function pinMode(). The action of executing
previously declared function commands is called a function call. We do not need
to declare the function pinMode()because it is already declared automatically in
the case of Arduino.
Function Call
Calling a function means executing the commands that were defined in your
declaration. Once declared, a function can be called multiple times in the same
program so that its commands can be executed again. To call our function
setup(), for example, we would use the following command:

setup ();

However, in the case of Arduino, we do not need to call the function


setup()because it is called automatically. When we compile a program in
Arduino IDE, it calls the function setup()once and then calls the function
loop()repeatedly until Arduino shuts down or restarts.
Return Value
The keyword that comes before the function name in the declaration defines the
type of the function's return value. Every time a function is called, it is executed
and returns or returns a certain value - this is the return value, or simply return of
the function. The return value must have a type, which can be any of the data
types mentioned above. In the case of our function setup(), the return type is
void, which means that the function returns nothing.

For example, let's create a function that returns something, for example, an
integer. To return a value, we use the command return:

int f () {
return 1;
}

When called, the f()above function always returns the value 1. You can use the
return value of a function to assign it to a variable. For example:

x = f ();

After declaring the function f()and calling the assignment command above, the
variable x will contain the value 1.

Parameters
Another important feature of a function is the parameters. They serve to send
some data to the function when it is called. Let's create, for example, a function
that adds two numbers:

int soma ( int a, int b) {


return a + b;
}

Here we just define a function called soma(), which accepts two integers as
parameters. We need to name these parameters, in which case we choose a and
b. These parameters act as variables that you can use within the function.
Whenever we call the function sum(), we need to provide these two numbers.
The command returns a + b; simply returns the function with the sum of the two
numbers. Let's add 2 + 3 and assign the result to a variable x:

x = sum (2, 3);

After the above call, the variable x will contains the value 5.
Comments
A comment is a piece of text in your program that only serves to explain
(document) the code without executing any kind of command in the program.
Often, comments are also used to disable commands in code. In this case, we say
that the code has been commented.

In the C ++ language, a comment can be written in two ways:

Line comment: starts with the characters //, making all the rest of the
current line a comment.

Block Comment: Starts with characters /*and ends with characters


*/. All text between the beginning and the end becomes a comment
and can consist of several lines.

For ease of viewing, development environments often show comments in a


different color. For Arduino IDE, for example, comments are displayed in gray.
Let's then explain what the sample program does by inserting several
explanatory comments in it:

/ *
Programming for Arduino - Getting Started
Sample Program: Blink
* /
/ *

Led Variable Statement

Indicates that the LED is connected to Arduino digital pin 13 (D13).

* /
int led = 13;
/ *

Setup () Function Statement

This function is called only once when Arduino is started or restarted.


* /
void setup () {
// Call the pinMode () function that sets a pin as input or output
pinMode (led, OUTPUT ); // Set the LED pin to output
}
/ *

Declaration of the loop ()

function After the setup () function is called, the loop () function is called
repeatedly until

Arduino is turned off.

* /
void loop () {
// All following lines are called parameter passing
function // Functions are executed in sequence to make the LED light up and
off
digitalWrite (led, HIGH ); // Assigns high logic level to LED pin, lighting it
delay (1000); // Wait 1000 milliseconds (one second)
digitalWrite (led, LOW ); // Assign low logic level to LED pin, deleting
delay(1000); // Wait 1000 milliseconds (one second)

// After finishing the loop () function, it is executed again and again,


// so the LED keeps flashing.
}
Control Structures
Control structures are blocks of instructions that alter the code execution flow of
a program. With them, you can do things like execute different commands
according to one condition or repeat a series of commands several times, for
example.

The following are some of the most common control structures used in general
programming languages. We will also modify our test program to exemplify
better how these structures work.

While
The while loop is a structure that performs a set of commands over and over
again as a certain condition is true. While in English means "while," and
pronounced "wow-ou." It follows the following format:

while(condition) {
...
}

So let's make a modification to our program to better illustrate how while works.
Our goal now is to make the LED flash three times, then wait five seconds, flash
three more times, and so on. We will change the content of the function loop()to
the following:

// Variable to count the number of times the LED flashed


int i = 0;

// Flash the LED three times


while (i <3) {
digitalWrite (led, HIGH ); // Assigns high logic level to LED pin, lighting
it
delay (1000); // Wait 1000 milliseconds (one second)
digitalWrite (led, LOW ); // Assigns low logic level to LED pin, deleting it
delay (1000); // Wait 1000 milliseconds (one second)
i = i + 1; // Increase the number of times the LED flashed
}

delay (5000); // Wait 5 seconds to flash the LED again

First, we declare a variable i. This variable will count how many times the LED
has flashed since the beginning of the program or since the last pause of five
seconds. We will initialize this variable to zero because at the beginning of the
function loop(), the LED has not flashed once under these conditions.

Next, we enter the command while, which must be followed by a condition


defined in parentheses. As long as this condition is true, the entire command
block between characters {and } is executed repeatedly. In the case of our
program, as long as the number of LED "flashes" (represented by the variable i)
is less than three, we continue to execute the commands that make the LED
flash. This is represented by the expression i < 3within the parentheses.

Between the characters {and }, we put the code that makes the LED blink, as
before, but we must not forget to add 1to the variable that counts the number of
"blinks." This is done in the following line of code:

i = i + 1; // Increase the number of times the LED flashed

Note that after executing all commands between {and }, we will always have in
the variable i the number of times the LED has flashed since the start of the
function loop(). Let's go through the sequence of steps executed each time the
function loop()is called:

1. We assigned 0the variable i: the LED has not flashed once.

2. We compare if i < 3: as 0is smaller than 3, we execute the


commands between {and }:

I. We execute the commands to turn the LED on and off.

II. We add 1to the variable i, making it 1: we know that the LED
flashed once.

3. We go back to the beginning of while and compare if i < 3: as it 1is


smaller than 3, we execute the commands between {and }again:

I. We execute the commands to turn the LED on and off.

II. We added 1the variable i, making it 2: we know that the LED


flashed twice.

4. We go back to the beginning of while and compare if i < 3: as it 2is


smaller than 3, we execute the commands between {and }again:

I. We execute the commands to turn the LED on and off.

II. We added the 1 variable to i to make it 3: we know that the LED


flashed three times.

1. We go back to the beginning of the while and compare if i < 3:


since 3 it is no smaller than 3, we no longer execute the commands
between {and }and proceed to the next statement.

2. We waited five seconds through the call delay(5000).

After these steps, we reach the end of the function loop(), and as we already
know, it is called again by the Arduino system. This restarts the cycle by
performing the above steps indefinitely.

Run the modified program with the instructions above on your Arduino and try
to vary the number of "blinks" and the number

For
Now that we have learned the while command, it is very easy to learn the for
command, as it is almost the same thing. Let's modify the content of the function
loop()as we did above, but using the for instead of while:

// Variable to count the number of times the LED flashed


int i;

// Flash LED three times


for (i = 0; i <3; i ++) {
digitalWrite (led, HIGH ); // Assigns high logic level to LED pin, lighting
it
delay (1000); // Wait 1000 milliseconds (one second)
digitalWrite (led, LOW ); // Assigns low logic level to LED pin, deleting it
delay (1000); // Wait 1000 milliseconds (one second)
}

delay (5000); // Wait 5 seconds to flash the LED again

The first modification we made was to declare the variable i without initializing
it with the value 0. We can do that because the command will do it for us. It
follows the following format:

for(boot; condition; finishing) {


...
}

Let's describe each item separately:

Condition: is a repeatedly verified expression, identical to the


condition in parentheses of a while. As long as it is true, commands
enter {and }continue to execute.

Initialization: This is a command executed only once at the


beginning of the command for.

Termination: is a command executed repeatedly at the end of each


command execution between {and }.

We can then verify that for nothing is more than a while plus a boot command,
and a terminate command. For our test program, these commands are
respectively:
i = 0: Initializes the count of the number of "blinks."

i++: sum 1to the variable i at the end of command execution


between {and }; in this case it is equivalent to the command i = i +
1. The operator ++is called the increment operator, and is widely
used in the C ++ language.

If we run the above program on Arduino, we will see that the result is the same
as we got with the program we did earlier using a while.
If
The if is one of the basic structures in general programming. If stands for "if" in
English, and that is exactly what it does: it checks an expression and, only if it is
true, executes a set of commands. In natural language, he executes a logic like, "
If this is true, then do that."

To illustrate, let's modify our sample program so that it does the same thing we
did with while and for above, but let's do it using one if, which follows the
following format:

if(condition) {
...
}

The logic is very simple: whenever the condition is true, the commands enter
{and } are executed, otherwise the program proceeds without executing them.
Let's see how the function looks like loop():

// Variable to count the number of times the LED flashed


int i = 0;
void loop () {
digitalWrite (led, HIGH ); // Assigns high logic level to LED pin, lighting it
delay (1000); // Wait 1000 milliseconds (one second)
digitalWrite (led, LOW ); // Assigns low logic level to LED pin, deleting it
delay (1000); // Wait 1000 milliseconds (one second)

i ++; // Increment the number of "blinks"


if (i == 3) {
delay (5000); // Wait 5 seconds to flash the LED again
i = 0; // Reset the number of "blinks" counter
}
}

Here the logic is a bit different: we will keep the function loop()flashing the
LED as in the original program, but we will insert an additional 5 seconds wait
after every 3 flashes. For this, we create a variable i outside the function loop();
it must be declared from outside the function in order to retain its value between
each execution of the function loop(). We call this the global variable. When
the variable is declared within the function body, it does not retain the value
between each execution and is restarted each time the function is re-executed.
We call this the local variable.
We will then use this global variable i to count, again, the number of times the
LED went on and off. In the variable declaration, we initialize it with the value
0to indicate that the LED has not lit up yet. The function loop()then starts
executing by turning the LED on and off. To count the number of times the LED
flashed, we added the following line of code:
i ++; // Increase number of "blinks"

We then use the if to check if we have just lit the LED for the third time. For
this, we use the expression i == 3in the condition of ìf. If this expression is true,
that is to say, that the LED has already lit 3 times, then we insert an additional 5
second pause with the call delay(5000) and restart the number of "blinks" again
with the following command:
i = 0; // Reset the number of "blinks" counter

From then on, the function loop()continues to be called, and the cycle starts
again.

If-else
The if-else, also known as if-then-else it can be seen as an extension command
if. Else in English means "otherwise,"and he does exactly what the name says:"
If that's true, then do that, otherwise do something else." It follows the following
format:

if(condition) {
...
} else {
...
}

To illustrate, let's use the program is that we show up, but this time we will make
the LED on and off four times before giving a five-second pause. Then we will
make the third of each of these four "flashes" light up for a shorter period.
Within the function loop(), we will have the following:
// Variable to count the number of times the LED flashed
int i;

// Flash the LED three times


for (i = 0; i <3; i ++) {
if (i == 2) {
digitalWrite (led, HIGH ); // Assigns high logic level to LED pin,
lighting it
delay (200); // Wait 200 milliseconds (one second)
digitalWrite (led, LOW ); // Assigns low logic level to LED pin, deleting
it
delay (1800); // Wait 1800 milliseconds (one second)
} else {
digitalWrite (led, HIGH ); // Assign high logic level to LED pin, lighting
it
delay (1000); // Wait 1000 milliseconds (one second)
digitalWrite (led, LOW ); // Assigns low logic level to LED pin, deleting
it
delay (1000); // Wait 1000 milliseconds (one second)
}
}

delay (5000); // Wait 5 seconds to flash the LED again

Here what we do is, every time we turn on the LED, check if this is the third
time this happens, by command if with the condition i == 2. If this expression is
true, it means that we have already lit the LED twice and are about to light it for
the third time; In this case we change the time that the LED is random to a
smaller value of 0.2 seconds (a reduction of 0.8 seconds) and the time it turns off
to a larger value of 1.8 seconds (increase of 0 seconds). , 8 seconds).
But what if this is not the third time the LED has been on? This is where o else:
If the condition of if is true, the command block between {and }after if is
executed, otherwise the block between {and }after else is executed. This means
that for the first, second, and fourth "blinks," the default time of one second will
be used.

Libraries
The things we learned in the previous sections are important for implementing
the logic of your Arduino program, but you will usually want to do more than
just light a LED. When you do more complex tasks or use some other circuit
connected to your Arduino, a very important feature is libraries.

A library is basically made up of additional source code that you add to your
project through the include command. Let's see how to add, for example, a
library for controlling a liquid crystal display (LCD):

#include < LiquidCrystal .h>

An Arduino library usually presents itself as one or more classes that have
functions, methods, to trigger devices, configure them, or perform some other
task. Continuing with the example of the LCD display, to use it in your program,
you must first initialize it. What we do in this case is create an object to access
the LCD (technically, this is called instantiating an object). Let's see how this is
done:

LiquidCrystal LCD (12, 11, 5, 4, 3, 2);

When we do this, lcd it becomes an object of the class LiquidCrystal. This is the
equivalent of creating a variable of type LiquidCrystal. The parameters that are
passed in parentheses serve to initialize the configuration of this object, in which
case they correspond to the pin numbers that were used to connect the LCD to
the Arduino.

Arduino libraries almost always have a method begin(), which serves to make
the initial configuration of the device being controlled. To call the function
begin()of the object lcd we created, we do the following:
lCD begin (16, 2);

This method begin()is usually called from within the function setup(), i.e. during
program startup. The method parameters in begin()this case correspond to the
number of columns and the number of rows of the LCD, respectively.

After these steps, we can now write a text on the LCD. We do this using the
print()object method lcdwhenever we need it throughout the program:

lcd print ( "Hi!" );

The method print()is just one of several methods available in the library
LiquidCrystal. To know all the methods provided by a particular library, you
need to refer to the documentation provided with it.

This is the basic process of using libraries in Arduino. For more information,
read the documentation provided with the library you are using.

Classes, objects, and methods are object-oriented programming concepts. We


won't explain everything in detail here, but if you want to learn more about it,
follow the related links at the bottom of the page.

Conclusion
In this chapter we look at the basic programming concepts required to program
an Arduino or even other embedded hardware platforms. But this is only the
beginning, and there is still much to learn, both in hardware and software.
Through the next chapter of this book, there are interesting sections and lessons
so you can learn more advanced concepts and expand your possibilities.
Chapter 2
Getting Started with Arduino
If you work with electronics, you probably know or have heard about Arduino
before you start reading this book. If you are from some other area, say art and
design, you have probably heard about this open-source development platform
as well. The Arduino is a project that has become popular throughout the world
because of its practicality, ease of work and competitive price.

In this chapter, we'll introduce what your hardware and software aspects are,
how they came about, as well as a step-by-step lesson to set up an initial desktop
and implement your first project with Arduino.

By the end of this chapter, you are expected to be able to explain and understand
what the Arduino system consists of and also be able to start developing your
first applications. Move on!

Arduino UNO Rev 3 Platform.


What Is Arduino and Why Use It?
In a nutshell, Arduino is an electronic project development platform (or
electronic prototyping, as it is also commonly said), consisting of both hardware
and software, and which is available under the Creative Commons Attribution-
Share-Alike license.
This means that all Arduino project design files are freely available on the
internet and that their software is open source. Also, the platform may be used
for both personal and business purposes, provided that credits are attributed to
the Arduino brand, and project files are also made available under the same
license.

The project emerged in Italy in 2015 from a group of developers led by Massimo
Banzi. The initial purpose was to create a low-cost, easy-to-work platform that
could be used by students to develop their prototypes efficiently and cheaply. It
was also thought to assist in the teaching of electronics to art and design
students, particularly to create interactive environments, something very much in
vogue within contemporary design and arts.

The main reasons for using the Arduino platform in your projects are as follows:

Low-cost prototyping

Free simulation software available

Easy to program

A large number of tutorials, articles, and projects ready on the


internet

Extensive community of developers and hobbyists

No experience or extensive prior knowledge of


electronics/programming required (however, it is advisable to know
the basics at least)

Arduino is not the only electronic prototyping platform on the market. There are
other projects and development kits, the most common being Raspberry Pi and
BeagleBone. Each uses a different microcontroller and has hardware design with
its own characteristics. Prices also vary widely, and some other platforms are not
as popular.

The choice of which prototyping kit to use depends on the demands and needs
your project imposes. Certainly, given the reasons cited above, Arduino is a
strong candidate for most of its projects.

An Overview of Arduino
Arduino is a prototyping platform that enables the development of various
robotic projects, acting as a type of simplified programmable electronic brain,
with several ports for connections to modules and sensors.

It is designed using a specific programming microcontroller with analog and


digital input and output pins, as well as pins for power and I2C protocol, for
example.

Arduino was so successful after its inception that within a few years, it became
known in schools and universities around the world, becoming a low-cost,
extremely functional global fever.

It is noteworthy that since its inception was implemented as open-source, i.e.,


has a free hardware concept, which in practice means that it can be modified and
improved in various ways.

In short, Arduino is an open-source electronics prototyping platform and free


hardware very easy to use and use. It has been designed through a specific
programming microcontroller with power and signal input and output pins that
can be easily applied to the most diverse electronic and electrical projects.

Who Invented Arduino?


Arduino was invented by Massimo Banzi, the co-founder of the prototyping
platform, together with 4 other researchers: David Cuartielles, Gianluca Martino,
David Mellis, and Tom Igoe in 2005.

At this time, professor of electronics and programming Massimo wanted to teach


his students of the design course basics of electronics and programming in order
to stimulate the development of robotics, interactivity and art projects, but soon
came across a problem, not There were affordable plates, let alone simplified
layouts for students who were just entering this area.

From the beginning of the project development, the founders' main objective was
to create a cheap electronic device with great functionality, and at the same time,
that could be easily programmed.

This explains the great success that the Arduino has achieved, appearing in low,
medium, and high complexity robotic designs, allowing the integration with
electronic modules and sensors of the most diverse types.

Some scholars in the area say that the microcontroller was named after Arduino
after King Arduin, who ruled northern Italy in the year 1002 and was a striking
figure. Massimo still had a bar in the town of Ivre called Bar di Re Arduino,
already inspired by the king.
How does Arduino Work?
Arduino works from programming codes, where it can be freely used for various
types of functions and can control everything from electronic sensors to highly
complex modules.

The programming is done through the IDE program Arduino, which can be
downloaded directly from the official website arduino.cc, in addition, the
connection to the computer is made via USB cable, allowing the commands
defined in the program to be correctly transferred to board.

After recording the codes according to the chosen sensors, it can be installed at
random locations using power supplies or even batteries if it needs to be in an
isolated location.

It is important to mention that the sensors can be connected directly to their


communication ports using jumpers or on test plates, known as protoboards.

Both hardware and software are designed to assist designers, hobbyists, hackers,
artists, novices, and anyone interested in creating interactive equipment and
environments. Arduino can interact with sensors, motors, cameras, shields, and
most known electronics.

The Arduino Uno is the best-known model, with 13 digital ports, 6 analog ports,
3 GND ports, a 5V port, and a 3.3V port, as well as other configuration and
power pins.

Among the Arduino digital pins, it is worth remembering that there are some
pins that differ from the others because they have their own characteristics such
as PWM pins that have a "~" before the number and have the ability to vary the
output signal to control motors, for example, pins 0 (RX) and 1 (TX) which are
communication pins.

As for power, it can be done through the USB port, with the possibility of the
programmer choosing to use an external source with a direct connection to the
Arduino p4 jack.
How to Program an Arduino
Arduino programming is done via software on the computer or directly on an
android phone; in any case, the program needs to be downloaded from the
manufacturer's website and installed directly on the machine.

After that, you need to connect the card with the USB cable, which is usually
included, and select the desired card, and then you have to upload a ready-made
code or create one from scratch in C language.

C programming is a universal language that is taught in technical and higher


information technology courses. In any case, as it is a simple method, it can
easily be learned from a reading of books and articles available on the Internet.

Programming has ceased to be considered a “seven-headed animal” and has


become a means of teaching, a means of challenging our own limits, and
especially a fun experience that increasingly infects adults and children
regardless of their age, from the simplest — projects even the most complex
programming schemes.
How much does an Arduino Cost?
The Arduino costs between $ 350 and R $ 5,000 on average, it does not have an
exactly defined value, because it is a type of microcontroller that is divided into
many models, from the smallest and easiest models to use to the complete
models with several extra functions.
The best known models are:
Arduino Uno R3
Arduino Mega2560
Arduino Nano
Arduino Micro
and Arduino DUE.

It has many variations because it is an open-source project, which may lower or


increase the prices mentioned above.

This is not to say that you will need an expensive microcontroller to have the
special functions because, with a simple one like UNO, you will be able to
install any extra modules that can even pass the functionality of the complete
model, everything will depend on the type of project that you want to develop.

What to do with Arduino


With Arduino, many electronic projects can be created, including robotic trolleys
and arms, battle robots, line-following robots, home automation projects, and
more.

For those just starting out and still wondering what the best Arduino to start
with, keep in mind that the Arduino UNO is currently the “standard” card on the
market and probably the best choice for those starting with this line of
controllers.

Have you ever come across a rising light with your simple presence, clapping, or
varying ambient light? Maybe you have seen carts that follow a line, dodging
obstacles, receiving commands through mobile phones, these are two of the
main electronic movements involving Arduino, Home Automation and Robotics.

Through Arduino UNO, it is possible to develop a wide range of interactive


objects and autonomous environments by simply assembling your project
physically, connecting Arduino with your computer, and through a specific
platform available for download at the link below to perform the recording
process.
Where to start?
After learning a little more about this amazing card in this “An overview of
Arduino?” section, Just pick a model and start studying the next content of this
book, surely you will be amazed at how many things can be automated in your
home and improved — their projects, whether at science fairs or robotics
competitions.

The Hardware of Arduino


Let's talk a little about what Arduino hardware. All information present here is
available on the official Arduino website and move further with this book to
explore it.

There is not just one Arduino model. There are several cards available, each with
different levels of complexity and different functionality. There are 6 classes of
Arduino prototyping platforms available on the market today. Are they:

Entry Level: Simpler versions focused on who is starting to


develop electronic projects.

Enhanced Features: Cards with additional functionality for more


complex designs.

Internet of Things: Specific platforms for IoT projects.

Education: Just a model of this class, focused on the teaching of


electronics and programming.

Wearable: Platforms with specific features for the development of


wearables, or “wearable technologies” such as smartwatches and
embedded electronics garments.

3D printing: 3D printer developed with Arduino.

Let's focus on Arduino UNO, an entry-level card, and one of the most popular
and most affordable models. It is an ideal card for those who are taking their first
steps in electronics and the Arduino universe.
As seen in figure 1, the board has a number of available connector pins and
connectors for interfacing with the outside world. The MCU is an ATmega328p
(datasheet). The main features of the board are:
14 digital I / Os, of which 6 can be used as PWM
6 Analog Inputs
16MHz Oscillator
USB connector
Power connector
ICSP header
Reset button

The card can be powered by both USB cable and AC / DC adapter. All features
of the microcontroller are available to interface with the outside world. In
general, analog inputs are used to read external sensors, and PWM outputs and
digital outputs are used to control motors and actuators and drive drivers for
external loads.
The Software of Arduino
The Arduino IDE is also open source. Its graphical environment was developed
in Java and based on Processing and other open-source languages. The
programming environment is available for Windows, MAC and Linux. The
download can be done directly on the official page.

The programming language used to write Arduino code is based on traditional C


/ C ++ (with modifications) and has a very high degree of abstraction and a
number of libraries that encapsulate most of the microcontroller complexity.

This high degree of abstraction and library set are largely responsible for making
programming more intuitive and fast, as the developer does not need to know the
registers, memory details, and dynamics processor.
Arduino UNO IDE.

We see that IDE is very simple and lean.


At the top, we have the following tabs: File, Edit, Sketch, Tools and Help. This
last one is interesting always to be frequented by the user because it has
important references and is the main source of information and troubleshooting.

Just below this main menu are some shortcut icons. They are (from left to right):

Shortcut toolbar.
Verify: Identify syntax errors in code
Upload: Loads software on board
New: Creates a New Blank Sketch Tab
Open: Opened a Sketchbook Sketch
Save: Save Sketch in Development
In the next couple of chapter, you will learn more about Arduino programming
and C / C ++ languages.
Getting Ready to Program Arduino
Now that we know what Arduino's hardware and software features are let's
prepare and configure our development setup.

From a hardware standpoint, simply power the card and connect the USB cable
to the computer. The IDE does all other settings. See the steps below:

Power and connect Arduino to PC via USB cable

In the IDE, select the board model

Open Tools tab, select Board option and then select Arduino
Uno

Select serial port to which the card has been assigned

Open the Tools tab, select the Serial Port option and then select
the COMX port, where X is the number the PC has associated
with the serial port assigned to Arduino.

After these settings, the IDE is ready to load programs developed in Arduino and
run any available example.
Programming the First Application
Let's now make the first example in Arduino. The simplest example, usually the
first made to test a board or when learning for the first time, is the famous "Led
Blink," that is, let's write a program to make a led flash.

The Arduino UNO platform has an onboard led previously connected to the
logic state of pin 13. So we can use this led to our example.

Another good news is that IDE has a good and complete library of examples that
can be used as a basis for a wide range of applications. To access the Led Blink
example, go to Files → Examples → Basics → Blink.
In the following figure, we see the code of this example:

Led Blink Sample Code.

In the example above, we can see the two parts that will always be present in all
your Arduino projects. The void Setup() function and the void loop () function.
The first is responsible for configuring and making all the necessary settings for
a given application. For example, in the case of Led Blink, we see the line:
pinMode (Led, OUTPUT).

This line of code is responsible for initializing the digital ports as outputs. Other
settings, such as PWM signal frequency, port initialization as input, serial
channel settings, among others, are all made in this function.
The second routine consists of the infinite loop that will be repeated throughout
the application. That is, after Arduino is energized, the first piece of software
that will run is the void setup () function, and soon after, the software enters the
void loop () routine, and repeats the code within that routine continuously. It is
in this infinite loop that the code for the application itself must be placed.

In the case of Led Blink, we have the following code in the infinite loop:

Led Blink application code present in infinite loop.


This code calls the digitalWrite (led, High) function, which assigns a high level
to the led pin, which in this case corresponds to pin 13 (note in figure 6 that led
is an integer variable to which the value 13 has been assigned) , i.e. the led
connected to pin 13 is activated.
Next is called the delay (1000) function, which pauses the loop for a thousand
milliseconds, that is, for one second.

After waiting for this time, the digitalWrite () function is called again, but this
time to assign a low logic level to pin 13, i.e. to turn off the led connected to pin
13. Finally, the delay function (1000) is again call to pause another second.

This way, the led flashes at continuous intervals of one second. Here's our
example Led Blink! Simple, isn't it ?!

To upload the code on the board, just click the Upload icon. The firmware will
be written to the board's Atmel microcontroller, and the first flashing application
will be ready. Each time the Arduino is energized, the pin 13 led will flash at
regular one-second intervals.

Fritzing Arduino Application Simulation


It is a common and highly recommended practice that every electronics project
be first simulated via software before it is mounted on hardware. In addition to
being a good practice that allows developers to debug and identify firmware
errors even before boarding the platform, simulators also allow applications to
be developed without the board necessarily being present.

A very popular simulator for Arduino circuits is Fritzing. It is open-source


software that has an excellent and intuitive graphical interface.

If you have come this far, then you already know what the Arduino platform is
and how it works. The Led Blink example is a very basic application, and we
recommend that you explore the other examples available in the IDE and follow
the blog posts here. There is a great documentary that we highly recommend
about Arduino history and how it all started ( see here! ).

The Arduino platform allows anyone to develop microcontroller electronic


applications, and was a milestone in the popularization of interactive systems in
the design and arts fields, as it made the lives of many non-electronics
professionals much easier.
For those who work in electronics, whether as a professional or as a hobby,
Arduino allows you to prototype and implement projects quickly and
inexpensively, so you don't have to go through giant datasheets or crush
handcrafted boards looking for problems. Hands-on!
New Arduino IDE - Professional - PRO IDE
For those who do not believe it is possible to do Professional Projects with
Arduino, this is an IDE (Development Platform) designed just for that. Very
interesting! But it is still in the development phase so that it may present errors.

The simplicity of the Arduino IDE has made it one of the most popular in the
world - it's easy enough for beginners and fast for advanced users. Millions of
people have used it as their daily tool for programming projects and applications.
However, we have listened to your comments, and the time has come for a new,
enhanced version with features that will appeal to the most advanced developers
among you - continuing with the simple, classic Arduino IDE that many of you
are familiar with.

Key features of this initial alpha release of the new Arduino Pro IDE are:
Modern and complete development environment
Dual Mode, Classic Mode (identical to Arduino's classic IDE) and
Pro Mode (File System view)
Ninth Board Manager
New Library Manager
Board List
Basic Autofill
Git integration
Serial monitor
Dark mode

But the new architecture opens the door to the features requested by the Arduino
community that will follow shortly:
Sketch Sync with Arduino Create Editor
Debugger
Fully open to third party plugins
Support for additional non-C ++ languages

The new Arduino Pro IDE is based on the latest technologies:

The Arduino CLI running in daemon mode provides all major


Arduino features.

The application frontend is based on the open-source Eclipse Theia


IDE.

Electron, the framework behind Eclipse Theia, enables the use of


web technologies in desktop environments.

Available on Windows, Mac OS X, and Linux64 versions.

For those who love and appreciate Arduino's classic IDE, don't worry, it will
remain available forever.
Chapter 3
C Language Basics

General Considerations
Many languages have been developed and for many years used for different
purposes and characteristics, such as Fortran, Cobol, Basic, Algol, Pascal, and so
on. But what is C? C is the name of a language currently used in different areas
and purposes. It is now part of an advanced language developed at Bell Labs in
the 1970s.

The formal definition of language can be found in the book "The C


Programming Language" by Brian W. Kernighan and Dennis M. Ritchie (the
parents of language). In the 1980s, work began on creating a standard called C
ANSI ( American National Standardization Institute ).

It is a medium level language, as it can work at a level close to the machine level
or as a high-level language like existing ones.

With C, we can write concise, organized, and easy-to-understand programs, but


unfortunately, lack of discipline can lead to poorly written programs that are
difficult to read and understand. It should not be forgotten that C is a language
for programmers as it imposes few restrictions on what can be done. C is
friendly and structured to encourage good programming habits; it is up to the
programmer to exercise these habits.

The need to write programs that make use of machine language resources in a
simpler and more portable way meant that the main use of C was the rewriting of
UNIX operating systems. Its indication is mainly in the development of
programs such as compilers, interpreters, text editors, databases. Computer
graphics, image manipulation, and processing, process control…

Key features of C language to consider:


Portability
Generation of fast and compact executable codes
Interaction with the operating system
Ease of use (through environments such as Borland C ++ 5.0)
Structured Language
Reliability
Simplicity

Basic Elements

Identifiers
They are used to name constants, variables, functions, and various user-defined
objects. The rules for forming these names are:

1. Every identifier must start with a letter (a..z or A..Z) or underscore

2. May not contain special symbols. After the first character can be
used: letters, underscores and / or digits.

3. Identifiers of a maximum of 32 characters are used as they are


significant.

4. It cannot be a reserved word or name of library functions.

Note: Upper and lower case letters are treated differently.

Basic Data Types

Type Number of bytes Scale


char 1 -128 to 127
Int 2 -32768 to 32767
float 4 3.4E-38 to 3.4E + 38 (+ -)
double 8th 1.7E-308 to 1.7E + 308 (+ -)
void 0 worthless
Modifiers
Type Number of bytes Scale
Unsigned char 1 0 to 255
unsigned int 2 0 to 65535
Short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
long double 10 3.4E-4932 to 1.1E + 4932

Comments:

1. The signed modifier may eventually be used, but its use is


equivalent to using a type without any modifier.

2. The word int can be omitted. Ex: unsigned long int Û unsigned
long

Declaration of Variables
The general form for declaring a variable is:

variable_type variable_list;

where variable_type is a valid type in C (Sections 1.2 and 1.3),


and variable_list can be one or more comma-separated identifier names.

Examples:

int f, i, k; / * all variables of type int * /


float a, A, b; / * all float variables * /

Constants
In C, constants are fixed values that cannot be changed by a program.

Constants in Decimal Basis


1. Integer numerical constants: can be assigned
to char and int variables, modified or not, depending on the value of
the constant and the range of values accepted by the variable.

Examples: 345 10 0 5000000

2. Noninteger numerical constants: can be assigned to float and double


variables, modified or not, depending on the value of the constant
and the range of values accepted by the variable.

Examples: -56,897 1.2E + 5

3. Character constants: can be assigned to char- type variables,


modified or not. The value of the constant is equal to the numeric
value of the ASCII table of the character represented by ''
(commonly referred to as “single”)

Constants in Hexadecimal and Octal Bases


Hexadecimal constants start with 0x, while octal constants start with 0.

Examples: 0xAB (hexadecimal) 016 (octal)

String Constants (Strings)


They are represented in quotation marks.

Example: “This is a string constant.”

C Language Control Characters


These characters must be represented as alphanumeric characters (in '') or as the
content of a string.

Code Meaning
\The audible signal
\B cursor backspace
\ f form feed
\ n new line
\ r car return
\ t horizontal tab
\ ' quotation marks
\ ' apostrophe
\ 0 null (zero)
\\ backslash
\ v vertical tab
\The beep
\ N octal constant (where N is octal)
\ xN hexadecimal constant (where N is hexadecimal)

Instructions
A C language statement is an expression followed by a semicolon. It can be an
assignment, a function call, a deviation test, or a loop test.

Example assignment statement: x = 12;

Where the equal sign (=) is the assignment operator. Note that the left operand of
the assignment operator is always a variable and that the right operand must be
of a data type compatible with the type of the variable.

Operators

Arithmetic Operators
Addition +
Subtraction -
Division /
Multiplication *
Rest %
Comments:

1. All operators are defined for integer and noninteger types except
the remainder (%) operator, which is not defined for variables of
noninteger types.

2. For any integer type, adding one to the largest track number of that
type produces the smallest track number. Overflow errors are not
always detected, so the programmer must be careful when sizing
program variables so that they do not occur.
Example:

unsigned char x;

x = 255;

x = x + 1; / * x should assume 256, however it overflows the range


and returns to the smallest value that is 0 * /

Relational Operators

Less than <


Bigger then >
Less or equal <=
Bigger or equal > =
Equality = =
Inequality ! =
Comments:

1. All relational operations result in an integer representing a logical


value (1 = true and 0 = false).

2. Do not confuse the assignment operator (=) with the equality


operator (= =).

Logical Operators

and (conjunction) &&


or (disjunction) | |
no (denial) !
Logical operators can receive any operand value, but nonzero values are always
interpreted as true, and zero values are interpreted as false. The result of a logical
operation is always a logical value.

Truth table:
p && p
P Q !P
q || what
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Combined Assignment Operators

+ = - = * = / =

Examples:

a + = b; / * a = a + b; * /

a - = b; / * a = a - b; * /

a * = b; / * a = a * b; * /

a / = b; / * a = a / b; * /

Comments:

1. All assignment operators assign the result of an expression to a


variable. If the left side type is not the same as the right side type,
the right side type will be converted to the left side type. This can
cause loss of accuracy in some data types and should be taken
seriously by the programmer.
Postfix and Prefixed Operators
Operator Meaning
++ variable increment the variable before
using its value
Variable ++ increment the variable after using
its value
- variable decrement the variable before
using its value
Variable - decrement the variable after using
its value
Examples:

int a, b, c;

a = 6;

b = ++ a; / * a gets 7 then b also gets 7 * /

c = a ++; / * c gets 7 and then gets 8 * /

Bit Level Operators

Shift left <<


Shift right >>
and (and) &
or (or) |
or exclusive (xor) ^
not not) ~
For further discussion on the use of bits and binary numbers, see the text
on Numerical Bases.

Address Operators
& - return variable address
* - return the contents of the address stored in a pointer variable
To learn more about address operators, see Pointers.

Other Operators
sizeof ( operand ) - provides the size in bytes of your operand
Ex:
int x;
float y;
char c;
x = sizeof (int); / * gives the size of type int (2 bytes) * /
x = sizeof (y); / * gives the size of variable y (4 bytes) * /
x = sizeof (c); / * gives the size of variable c (1 byte) * /
Expressions
Operators, constants, variables, and functions are expressions. The main
algebraic rules are considered in the expressions. Some aspects of expressions
are C language-specific and are explained below.

Automatic Type Conversion


When constants, variables, and functions of different types are mixed into one
expression, they are all converted to the largest operand type. This is done
operation by operation according to the following rules:

1. All operands of type char and short int are converted to int. All float
operands are converted to double.

2. For all pairs of operands involved in an operation, if one of them is


long double the other operand is converted to a long double. If one
is double, the other is converted to double. If one is long, the other
is converted to long. If one is unsigned, the other is converted to
unsigned.

Example:
float x, res;
char c;
...
res = x / c; / * the value of x / c is converted to a float, although c is
originally a char * /

Explicit Type Casts


You can force an expression to be of a specific type without, however, changing
the types of variables involved in this expression. This type of operation is called
explicit type cast, or type cast.

The general form of a type cast is:


(type) expression;
where type is one of the default C language data types.

Type cast operations are very useful in expressions where some operation results
in loss of precision due to the type of variables or constants involved. For
example:

float res;
int op1, op2;
op1 = 3;
op2 = 2;
res = op1 / op2; / * res gets 1 since op1 and op2 are both
int numbers and the result of their
division is also int * /
res = (float) op1 / op2; / * res gets 1.5 as type cast
forced the op1 operand to be a float
In this operation. The result of the division,
therefore it is also float * /

Spacing and Parentheses


We can put spaces in an expression to make it more readable. Using redundant
or additional parentheses will not cause errors or slow the expression's execution
speed.

Example:
a = b / 9.67-56.89 * x-34.7;
a = (b / 9.67) - (56.89 * x) - 34.7; / * equivalent * /
Structure of a C program
An interesting feature of program C is its modular and functional aspect, where
the main program itself is a function. This form of language presentation
facilitates the development of programs, as it allows the use of structured and
modular forms found in other languages.

The structure of a C program has the following elements, and those enclosed in
brackets are optional:

[ preprocessing settings ]
[ type definitions ]
[ global variable declarations ]
[ function prototypes ]
[ functions ]

main ()
{
/ * variable definitions * /
/ * main function body, with declarations of its variables,
its commands and functions * /
}

Preprocessing definitions are commands interpreted by the compiler, at compile


time that refer to operations performed by the compiler for code
generation. They usually start with a hash sign (#) and are not C language
commands, so they will not be treated here in greater detail.

Example:

#include <stdio.h> / * preprocessor command used to tell the compiler to


'paste' the stdio.h file definitions into this file before compiling it * /

Type definitions are definitions of structures or special data types introduced by


the user to facilitate data manipulation by the program. Nor will they be dealt
with here in greater detail.

Global variable declarations are made when it is necessary to use global


variables in the program. The concept of the global variable and the advantages
and disadvantages of its use concern the modularization of a C program (see
material on modularization and functions).

Prototypes of functions and functions also concern modularization issues.

Main () is the main function of a C program, containing the code that will
initially be executed when the program itself is executed. Every C program must
contain the main () function, otherwise, an error will be generated during the
program generation process (more specifically, in the binding step).

Basic I / O Functions
This section describes some of the basic I / O functions that will initially be used
to provide the programmer with a keyboard data input channel and a monitor
data output channel.

printf () Function (stdio.h Library)


The printf () function is basically used to send information to the monitor, i.e., to
print information. Your prototype is as follows:
printf (data string and format, var1, var2, ..., varN);

where data string and format are literal data to be displayed on the monitor (for
example, any text) plus an optional set of format specifiers (indicated by the%
symbol and a character set). These specifiers will determine how the contents of
the var1 through varN arguments are displayed.

var1 through varN indicates, in turn, the arguments (variables or constants)


whose values will be displayed at the location and format determined by the
format specifiers within the data string and format. The number N must be equal
to the number of format specifiers provided.

Most used format specifiers:

%W simple characters ( char type )


% d integer (type int )
%and scientific notation
% f floating-point ( float type )
% g % e or% f (shorter)
%O octal
%s string
% u unsigned integer
% x hexadecimal
% lf double type
unsigned integer
% u
(type unsigned int )
% ld like long int
Examples:

1)

int n = 15;
printf (“The value of n is h% d”, n);

/ * displays ´The value of n eh 15´. Note that all contents of the data string
and format are displayed literally, except for the% d specifier, which is
replaced by the integer value of variable n * /

2)

char charac = ´A´;


float num = 3.16;
printf (“The letter is% c and the number is% f”, character, num);

/ * displays 'The letter eh A and the number eh 3.16'. In this case, the
The value replaces % c specifier (first of string)
of the character variable and the%, f specifier is replaced by the value
of variable num. It should be noted that the types of specifiers and
variables are compatible * /
scanf () Function (stdio.h Library)
The scanf function is used to receive data from standard data input. We will
assume, for simplicity, that this default input is always the
keyboard. The scanf prototype is as follows:

scanf (format string, & var1, & var2,…, & varN);

where the format string contains the format specifiers in sequence and relative to
each of the data to be received. For a list of commonly used format specifiers,
see printf () Function (stdio.h Library) section.

var1 through varN identify the variables in which the values received
by scanf will be stored in the same order as determined by the format
specifiers. The number N must be equal to the number of format specifiers
provided.

IMPORTANT: The address operator (&) MUST be used in front of variable


identifiers. Otherwise, an error occurs. For more details, see the pointer theory.

Examples:

1)

int t;
printf (“Enter an integer:“);
scanf (“% d,” & t); / * waits for a type number to be entered
int. The number entered is stored in the
variable t when the user types ENTER * /

2)

char char1;
int i;
printf (“Enter a comma-separated character and int:“);
scanf (“% c,% d”, & charac1, & i);

/ * In this case, the format specifiers% c and% d are
comma-separated, meaning that the user must enter the values also
comma-separated and in the correct order * /

getch () Function (conio.h library)


The getch function is basically used to wait for a user to press a key. The key
pressed can be captured by the return value of the function (for more details on
return value see function theory).

Because it stops execution until a key is pressed, the getch function can be used
at the end of a console program to allow the user to view the output of the
program before its window closes.

Example:

printf (“I'm showing a sentence \ n”);


printf (“Type any key to exit the program”);
getch (); / * waits here until a key is pressed * /

/ * end of program * /

Note: The getche function works similarly, but displays the typed character on
the screen (the name means “get char with echo”).

clrscr () Function (conio.h library)


The clrscr function is used to clear the screen (the name means “clear screen”).

Control Structures
Simple Command
A command line in C always ends with a semicolon (;)

Examples:

x = 443.7;
a = b + c;
printf (“Example”);

Command Block
Braces ({}) are used to delimit command blocks in a C program. They are most
commonly used in grouping statements for execution by conditional and
repeating structure clauses.

Conditional Structures

if-else Structure
Format:

if (condition)
{
command block 1
}
else
{
command block 2
}

Condition is any expression that can be evaluated to true (“true”) or false


(“false”). In the case of expressions that have a numeric value instead of a
logical value, if the value is nonzero, the expression is evaluated with a logical
value "true," otherwise it is evaluated with the logical value "false."

If the condition has a logical value of “true,” command block 1 is executed, if


the logical value of the condition is false, command block, 2 is executed. For
either block, if it is formed by a single command, the keys are optional.

The if-else structure is similar to a compound conditional structure in which


either command block is executed; The else clause, however, is optional, and if
it is omitted the structure will function as a simple conditional structure, where a
command block (in this case, block 1) is only executed if the condition is true.

Examples:

1)

int num;
printf (“Enter a number:“);
scanf (“% d”, & num);

if (num <0) / * tests if num is less than zero * /
{
/ * command block executed if condition is true. In this case, as printf is a
single command the keys could be omitted * /
printf (“\ nThe number is less than zero”);
}
else
{
/ * command block executed if condition is false.
In this case, as printf is a single command the keys
could be omitted * /

printf (“\ nThe number is greater than zero”);
}

2)

if ((a == 2) && (b == 5)) / * condition with logical operation * /


printf (“\ nCondition satisfied”); / * command block * /

getch (); / * this statement is not part of the structure
conditional, therefore always executed * /

3)

if (m == 3)
{
if ((a> = 1) && (a <= 31)) / * this if is part of the previous if
command block * /
{
printf (“Date OK”);
}
else / * this else is from the nearest if (which does
part of the command block) * /
{
printf (“Invalid Date”);
}
}

Switch Structure

Format:

switch (expression)
{
case value1:
seq. of commands 1
break;
case value2:
seq. of commands 2
break;
. . .
case valueN:
seq. N commands
break;
default:
seq. standard
}

The switch command evaluates the expression and compares successively


against a list of constants value1 to valueN (minus string constants). When it
finds a match between the expression value and the constant value, it jumps to
the corresponding case clause and executes the associated command sequence
until it finds a break statement, then exits the structure.

The default clause is executed if no match is found. This clause is optional and,
if not present, no action will be taken if all matches fail. It is typically used to
direct any free end that may be pending in the switch statement.
COMMENTS:

1. If the break command is forgotten at the end of a sequence of


commands, execution continues for the next case statement until
a break or the end of the switch is encountered, which is usually
unwanted.

2. never two case constants on the same switch can have equal values.

3. A switch statement is more efficient than an if-else thread, and can


be written much more “elegantly.”

4. value1 to valueN MUST be constant values.

Examples:
1)
int dia;
printf (“Enter a day of the week from 1 to 7”);
scanf (“% d”, & dia);
switch (day) / * tests the value of the variable day * /
{
case 1:
printf (“Sunday”);
break;
case 2:
printf (“Monday”);
break;
case 3:
printf (“Tuesday”);
break;
case 4:
printf (“Wednesday”);
break;
case 5:
printf (“Thursday”);
break;
case 6:
printf (“Friday”);
break;
case 7:
printf (“Saturday”);
break;
default:
printf (“This day does not exist”); / * only enters here if the user does not
enter a day between 1 and 7 * /
break;
}

Repetition Structures

While Structure

Format:

while (condition)
{
command sequence
}

The while command evaluates the logical condition value; if the logical value is
true ( true ), the command sequence is executed, otherwise, the program
execution continues after the structure while. If the command sequence consists
of a single command, the use of keys is optional.

After the command sequence has been executed, the logical condition value is
reevaluated, and if it remains true, the command sequence is executed
again. This behavior is repeated until the truth value of the condition is false
( false ) when the execution of the structure while it is stopped and continued on
the next instruction.

Each of the command sequence runs is called a loop iteration. In the case of
the while structure, the number of iterations can range from 0 to N, where N is
the number of the iteration, after which the condition test results in a false
logical value.
NOTE: If the condition is true on the first test and the command sequence is
executed, it must make the condition false at some point; otherwise, the
condition will always be reevaluated as true, and the command sequence will be
executed in an infinite number of iterations.

Example:
int x = 0;

/ * prints x values from 0 to 9
the value 10 is not printed because when testing the condition for
x equals 10, the logical value is false and the while execution
is interrupted * /

while (x <10)
{
printf (“\ nx =% d”, x);
x ++; / * makes the condition false
at any moment */
}

do-while Structure
Format:

of {

command sequence

} while (condition);

The command sequence is always initially executed in a do-while


structure. After its execution, the logical value of the condition is evaluated, and
if true, the command sequence is executed again. The cycle is repeated until the
truth value of the condition is false ( false ), where execution continues in the
following statement to the structure of the while. If the command sequence
consists of a single command, the use of keys is optional.
Unlike in the while structure, in the do-while structure, the number of iterations
varies between 1 and N, where N is the number of the iteration, after which the
condition test results in a false logical value.

NOTE: As with the while structure, if the condition is true on the first test, the
command sequence must make the condition false at some point.

Example:

int num;
of {

printf (“Enter a number from 1 to 9:“)
scanf (“% d”, & num);

} while (! ((num> = 1) && (num <= 9))); / * in this case, obtaining
of the value of one way
scanf may make the condition false * /

for Structure

Format:
for (initialization; condition; increment)
{
command sequence
}

The initialization is performed only once, at the beginning of the execution of


the structure is, and is usually an assignment used to initialize some loop control
variables.

After initialization, the logical value of the condition is tested. If true, the
command sequence is executed, otherwise, execution continues after the for
structure. At the end of the command sequence execution, the command
corresponding to the increment is executed, and the condition is retested.

The cycle is repeated until the test condition results in a logical false value (
false ) when then execution continues after the structure is. If the command
sequence consists of a single command, the use of keys is optional.

The for the structure is equivalent to a while structure of the following format:
boot
while (condition)
{
command sequence
increment
}
COMMENTS:

1. Any of the header clauses (initialization, condition, or increment)


can be omitted; In case of omitting initialization or increment, it is
considered that these are null commands (that is, they do nothing)
while omitting the condition is considered that its logical value is
always true. The semicolons that separate each of the clauses cannot
be omitted.

2. Initialization and increment clauses can consist of several


commands each; In this case, the commands must be separated from
each other by commas.

Examples:

1)

/ * in this case x is used as loop control variable


(controls execution between 1 and 100) and also has its value
printed by the printf * / function

for (x = 1; x <= 100; x ++)
{
printf (“% d”, x);
}
2)

/ *, in this case, the command sequence is null, and the loop is


used only to “spend time” counting from 0 to 999 * /

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

3)

/ * there is no increment, and the loop is executed until the value


entered by the user is 10 * /

for (x = 0; x! = 10;)
scanf (“% d”, & x);

4)
/ * two variables are initialized, tested and incremented * /

for (x = 0, y = 0; x + y <100; x ++, y ++)
printf (“% d”, x + y);

Interrupt Commands
Break Command

The break command can be used to interrupt the execution of a loop at any
time. Only the innermost loop is broken, and execution continues on the
command following that loop.

Example:

#include <stdlib.h> / * required to use rand () * /


#include <stdio.h>

void main (void)
{
int draw = rand (); / * generates a random number
between 0 and 32767 * /
int num, x;
for (x = 0; x <10; x ++)
{
printf (“Try to set the number (between 0 and 32767).”);
printf (“You have% d attempts.”, 10 - x);
scanf (“% d”, & num);
if (num == draw) / * hit number * /
{
break; / * breaks the loop (are not
more attempts required) * /
}
}

/ * if x equals 10, user timed out
unsuccessfully * /

if (x <10)
{
printf (“Very good!”);
}
else
{
printf (“Regrettable!”);
}
}

Continue Command

The continue command works similar to break, except that only the current
iteration is interrupted; that is, loop execution continues from the beginning of
the next iteration

Example:

/ * prints even numbers



for (x = 0; x <100; x ++)
{
/ * if number is not even, go to next iteration
without printing * /

if (x% 2! = 0)
continues;

printf (“% d,“, x);
}

Modularization in C

Functions

In C there is no distinction between functions and subroutines. That is, all


subroutines, from an algorithmic standpoint, can be treated as functions that
return no value.

Function declaration format:

Return type function_identifier ( type1 param1, type2 param2, ..., typeN


paramN)
{
/ * body of the function * /
return return value ;
} / * end of function * /

Return Type specifies the type of value that will be returned to the caller of the
function. When the return type is void, this means that it is a function that
behaves like a subroutine; that is, the function does not need to return any value,
just to be called.

Examples of return types in function headers:

int func1 (...) / * returns an integer value * /


void func2 (...) / * returns no value. Behaves like subroutine * /

The return command is used to perform the function return; This can be used at
any point in the function that you want to finish executing and return the value
(if the function returns any value) to the caller.

Return Value is the value to be effectively returned and can be either a variable
or a constant; In cases where the function returns no value, the return command
must be used alone, or you can simply omit it, which will automatically return
the function to its end.

Usage examples of return:

return 0; / * returns constant value 0 * /


return var; / * returns the value of the variable 'var' * /
return; / * does not return value. It is used for functions with void type
return * /

Parameters param1 through paramN identify the parameters that you want to
pass to the function. Each of these parameters becomes a local variable of
the type1 to typeN function and is initialized to the value that was passed to you
at the time of the function call. Functions that take no value as a parameter must
be declared with the word void in parentheses.

Examples of parameter declarations in the function header:

/ * two parameters, one int and one char. The ... refers to any return type *
/
... Func1 (int var, char var2)
{
}
... Func2 (void) / * receives no parameter * /
{
}


Example of C function and program that calls it:

int func1 (char charac, integer int, floating float) / * function declaration * /

{
/ * one can declare other variables in here, as in a normal program snippet
these variables are local to the function * /
int other;
/ * use of received variables as parameter * /
printf (“% c”, charac); printf (“% f”, floating);
scanf (“% d”, & other);

printf (“% d”, integer + other);

return another one; / * returns the value of the variable 'other' * /

} / * end of function * /


void main (void) / * main program * /
{
char c1;
float f;
int result;
int integer;
/ * this 'integer' variable exists within the scope of the 'main' function, so
it has nothing to do with the 'integer' variable that is created in the 'func1'
function when passing parameters * /

/ * reads an integer, a character and a float * /
scanf (“% d,% c,% f”, & integer, & c1, & f);

/ * call function 'func1' with parameters in correct order * /
result = func1 (c1, integer, f);
printf (“% d”, result); / * prints result of function * /

}

Comments:

1. main () is also a function, but special as it represents the starting


point for any C program;

2. The result of the function 'func1' in the example above need not
necessarily be assigned to a variable (in this case,
'result'); otherwise, the return value of the function will simply be
lost. However, as the function was made to return an integer value
this should be avoided because it constitutes a bad structuring and
use of the function;

3. All variables declared within the body of a function are local to it;
that is, they only exist while the function is being executed.

All functions must be “known” wherever they are used, i.e., your statement must
come before use. If you do not want to implement the function before where it
will be used, you can write a prototype as follows:

Return type function_identifier ( type1 param1, type2 param2, ..., typeN


paramN);

The prototype must be placed before the function call, signaling to the compiler
that that function exists and will be implemented later. In our example, if we
wanted to write function 'func1' after function 'main,' we should include a
prototype of 'func1' before it.

CAUTION!! The prototype is not exactly the same as the function header; it has
one more semicolon at the end!

Global Variables
In C is considered as a global variable, all those variables declared outside the
scope of any function (including the function 'main'). Any variable is known
only after its declaration, so it is usually declared all global variables at the
beginning of the program, before the implementation of the functions that use it.

Example of declaration and use of global variables:

int c;
char t;
/ * function that returns an integer value and receives no parameter * /
int func1 (void)
{
/ * there is a t variable that is global, but it works as a local variable * /
int t;
/ * c is global, so it can be used within function 'func1' * /
if (c! = 0)
{
c ++;
t = c * 2;
/ *, in this case, the value of t returned is that of the local variable since local
definitions override global definitions in the scopes where they exist * /
return t;
}
else return 0;

}
void main (void)
{
int return;
printf (“Enter a character:”);
scanf (“% c”, & t);
printf (“Enter an integer:”);
scanf (“% d”, & c); / * tec variables can be used here because they are
global * /
return = func1 (); / * call function func1 and return value in variable
'return' * /
printf (“\ nResult:% d”, return);
}
Parameter Passing by Value

In pass by value, a copy of the value of the argument is stored in the called
function parameter. Any change to this parameter is not reflected in the original
value of the argument.

An alternative to value parameter passing, which is parameter passing by


reference using pointers, would allow the function to change the value of the
parameter so that this change is reflected in the original value of the argument.
This type of parameter passing will be further studied in the chapter on
'Pointers.'

Functions with Parameter Variable List

In C, it is possible to declare functions whose number of parameters is not


defined. It is then up to the function, by using specific C library functions, to
obtain each of the received parameters and convert it to the desired type.

The cstdarg library provides some data types and functions used to obtain the
parameters of a list:

va_list - type of variable parameter list, used to declare a structure (see chapter
“Data structures”) containing the received variable parameters.

void va_start (va_list list, last) - macro used to initialize the va_list parameter
list . Last is the identifier of the last parameter on the right that does not belong
to the variable list of parameters.

va_arg type (va_list list, type) - allows, from the list the type va_list, get the kind
of value type of the next argument list.
void va_end (va_list list) - finalizes the list parameters.
To declare a variable list function:
Return type function_identifier ( type1 param1, type2 param2, ... );
Where the ellipse ( ...) Denotes the beginning of the variable list of parameters.
An example: a function that takes n values and returns its average:

/ * n is the number of values, which are next in the parameter list * /


float media (int n, ... )
{
float sum = 0;
int i;
va_list values; / * parameter list * /
va_start (values, n); / * 'n' is the last fixed parameter before the variable
parameter list * /
for (i = 0; i <n; i ++)
{
/ * here the value of the next float parameter is added to 'sum' * /
sum + = va_arg (values, float);
}
va_end (values); / * finishes obtaining the parameters * /
return sum / n;
}

Vectors and Matrices

Vector Definition

Vector in C is a variable composed of a data set with the same name (identifier)
and individualized by an index.

Vector Declaration in C

The vector is declared as follows:

type name [size];

Where type is the type of each of the vector elements and size is the number of
vector elements.

To access a vector element the syntax is:

name [index];
IMPORTANT! The index of the first element of a vector is ALWAYS ZERO!
Thus, the index can range from 0 to size value - 1.

For example, for the declaration of a vector called test whose data type
is char, and that has 4 positions, it states:

char test;

The index of the last indexable element of the vector is 3 because, in C, the first
position used is position 0. In this case, the positions available in the vector are
as follows:

test [0]
test [1]
test [2]
test [3]
Passing Vector as Parameter to Function

There are three possible ways:

1. return_type name (type v [size], ...);

2. return_type name (type v [], ...);

3. return_type name (type * v, ...);

In all cases the function receives a reference (address). Note that in the last way
a pointer is used, which will be explained later.

Because a reference is passed, changes made to the vector elements within the
function will be reflected in the original vector values (since its actual memory
position will be used).

For example:

void exchange (int v [])

{
int aux;
v [0] = v [1];
v [1] = aux;
}

void main (void)
{
int nums [2];
nums [0] = 3;
nums [1] = 5;
exchange (nums); / * The argument is the name of the vector * /
/ * prints '5, 3' as the nums vector values have been changed within the
'change' function * /
printf (“% d,% d”, nums [0], nums [1]);
}

Matrix Statement

The declaration of matrices is as follows:

type name [dim1] [dim2];

Where dim1 and dim2 are the two dimensions of the matrix (in the case of a
two-dimensional matrix). To access an array element the syntax is:

name [ind1] [ind2];

Where ind1 and ind2 follow the same rules as the one-dimensional vector
indices (that is, they can assume values between 0 and dimension - 1),
where ind1 is the row index and ind2 the column index.

The graphical representation of an M 3x2 matrix is as follows:

M [0] [0] M [0] [1]


M [1] [0] M [1] [1]
M [2] [0] M [2] [1]
In memory, it can be viewed as follows (note: left values represent arbitrary
memory addresses, considering an array of one-byte char elements ):

M [0]
0100
[0]
M [0]
0101
[1]
M [1]
0102
[0]
M [1]
0103
[1]
M [2]
0104
[0]
M [2]
0105
[1]
Passing Array as Parameter to Function

The possibilities are as follows:

return type name (type m [] [dim2], ...)

return type name (type * m, ...)

In the first case, dim2 must be provided so that the compiler can calculate the
offset in bytes from the address of the first element for a given position.

In the second case, m can only be used through pointer arithmetic (explained
below).

Example:

void row_back (int m [] [2])


{
int aux1, aux2;
aux1 = m [0] [0];
aux2 = m [0] [1];
m [0] [0] = m [1] [0];
m [0] [1] = m [1] [1];
m [1] [0] = aux1;
m [1] [1] = aux2;
}
void main (void)
{
int m [2] [2];
.
.
.
invert_line (m);
.
.
.
}

Initialization of Vectors and Arrays

For vectors: values in braces, separated by commas. For example :

int cousins [7] = {2, 3, 5, 7, 11, 13, 17};

If the number of initialization values is less than the size of the vector, the
remaining positions will be filled with zeros. For example:

int test [5] = {1, 2, 3}; / * test [3] and test [4] get 0 * /

For arrays, each line is padded with braces, with values separated by
commas. All lines are enclosed in braces.

Example:

int m [5] [3] = {{1, 2, 3}}, {3, 2, 1}, {3, 3, 2}, {1, 2, 1} {3, 2, 0}} ;

If any element is not explicit, it will be filled with zero.

Example:
int m2 [3] [4] = {{3,2,5}, {4,6,6}, {1,2,3,4}};

3 2 5th 0
4 6th 0 0
1 2 3 4
Pointers

Pointer in C is a variable that, instead of storing data of a certain type, stores the
address of a data of a certain type:

Pointers are often used to:

Memory mapped I / O access

Using dynamic memory allocation.

Alternative to pass by reference parameters (in C ++)

C Pointer Statement

The pointers are declared as follows:

type * name;

Where name is the pointer identifier and type is the data type to which it can
point.

Example:

int * d;
short int * ptr;
float * ptr2;
Pointer Operators
Operator &: Referencing operator. Returns the address of a variable. It can be
used to initialize a pointer.

Operator *: Dereferencing operator. Returns the contents of the address pointed


by a pointer.

Example:

int x, a;
int * ptr;
x = 30;
ptr = & x; / * ptr <- address of x * /
.
a = * ptr; / * a receives the contents of the given address * /

A didactic way to understand pointers is to "read" the meaning of * and & as


"content of the address pointed to" and "address of", respectively. For example
in the following code:

int * ptr;
int x;
x = 10;
* ptr = 3; / * ADDRESS CONTENT POINTED BY ptr gets 3 * /
ptr = & x; / * ptr gets the ADDRESS of x * /

Problems Using Pointers


Pointers should always point to addresses corresponding to variables that have
been declared or regions of memory in which no data or code exists from other
programs. For example, the following code stores the contents of variable x at
any address, which may be an invalid address.

int * ptr;
int x = 3;
* ptr = x; /* ERROR! Where does ptr point ??? * /

Pointers must point to data of the same type as your declaration, otherwise,
misinterpretation may occur in the dereferencing operation. For example, the
following code does not store the value 56 in variable f, since
the floatpointer will attempt to read the size of a given float from the memory
address of variable x and not the size of an int, which is the declared type. of
variable x.

int x = 56;
float * ptr;
float f;
ptr = & x; / * Pointer to float points to int * /
.
.
.
f = * ptr; /* ERROR! F value is not 56 * /

Pointer Arithmetic
Integer numeric values can be added or subtracted from a pointer. The result is
an address that follows the rules of pointer arithmetic, that is:

For a pointer declared as follows:


type * ptr;

and initialized with an end1 address :


ptr = end1;

The ptr + N operation , where N is an integer, results in an address that is equal


to end1 plus N times the size of the pointed data type (that is, the size
in type bytes ). For example, assuming variable x was allocated at address 120:

int x, y;
int * ptr;
ptr = & x; / * ptr receives address 120 * /
y = * (ptr + 4); / * y receives the contents of address 120 + 4 * (int size) ==
address 128 * /

Another example:

float * ptr;
ptr = (float *) 100; / * pointer is 'forced' to end. 100 * /
.
* (ptr + 3) = 15; / * Number 15 is stored at address 100 + 3x4 = 112 * /
Pointer-Vector Relationship

When a vector is declared, the vector identifier marks the start address of the
memory area allocated by it. Thus, the vector name can be used as an address
reference with the same operators as pointers. Therefore:

int vector [10], b; / * vector allocated at end. 100 (eg) * /


.
b = vector [3]; / * position 3 == end. 106 of memory * /
Equals:
int vector [10], b; / * vector allocated at end. 100 (eg) * /

/ * In memory this will be stored at position 106 -> 100 + 3 x Size of data
type pointed (int = 2 bytes) * /
b = * (vector + 3);

Using a Pointer to Pass Parameters

In many cases, it is interesting for a function to provide more than one output
value as its result. But the C language syntax allows only one direct return value
(via the return command ).

Using pointers creates an alternative for a function to provide more than one
output value, based on the fact that the concept of address in a program is scope
independent. That is, if a calling function provides the calling function with the
addresses of its variables, the called function can receive them in pointers and
fill in values at these addresses, which in turn will be available for direct access
by the calling function.

Example:

/ * function receives two addresses of 'int' as parameters * /


void exchange (int * a, int * b)
{
int aux;
aux = * a; / * content of address received as parameter * /
* a = * b
* b = aux;
}
void main (void)
{
int n1 = 8, n2 = 5;
/ * addresses of n1 and n2 are passed to the swap () function * /
exchange (& n1, & n2);
printf (“% d,% d”, n1, n2);
}

Strings
String Definition
Strings are miscellaneous strings. They are known as "literals" in structured
algorithm theory and are represented in quotation marks. Some examples of
strings:

“So-and-so,”
“? Question? “,
“1,234”,
"0".

In C, strings are represented by character vectors, ending with the end-of-string


character whose value in the ASCII table is zero (0 or \ 0).

String Statement

A vector in C wishing to store a string n characters must be allocated with n + 1


char positions to contain the string terminator. Initialization of a string can be
done using a quoted string.

Examples of string declarations:

char phrase [] = “First string”; / * Initialization without dimension * /

char phrase [16] = “First string”;

char phrase [6] = {'T', 'e', 's', 't', 'e', 0); / * initialized as a common character
array, 'forcing' the terminator character * /

In the case of the first and second example, the vector representation of
the phrase string is:

'P' 'r' 'i' 'm' 'and' 'i' 'r' 'The' '' 'f' 'r' 'The' 's' 'and' 0
Where each square represents one byte of memory (one char size ).

String Operations

String is not a primitive type of C language, so the following operations are


NOT valid:

char str1 [10];


char str2 [] = “Word 2”;
str1 = str2 / * ERROR! Do not copy str2 to str1 * /
if (str1 == str2) / * ERROR! Does not compare str1 with str2 * /
{
.
}

To operate on strings, functions from the string.h library is used. This library has
a few dozen functions with various variations, and for simplicity, only some of
the main ones will be explained in this material. For details on other functions,
see library documentation (usually available in the development environment
help files).

strlen

Prototype:

int strlen (char * string)

Description: Returns the number of characters in a string (except the end of


string character).

Example:
char name [] = “So-and-so”;
printf (“Name has% d letters”, strlen (name));

strcpy

Prototype:

char * strcpy (char * string1, char * string2)

Description: Copies the contents of string2 to string1 and returns the string
address.

Example:

char str1 [10];


char str2 [] = “Word”;
strcpy (str1, str2); / * Now str1 also contains “Word” * /

strcmp

Prototype:

int strcmp (char * string1, char * string2)

Description: Compares the contents of string1 and string2 character by character


and returns

0 if string1 = string2

<0 if string1 <string2

>0 if string1> string2

Example:

char name1 [] = “so and so”


char nome2 [] = “Beltrano”;
if (strcmp (name1, name2) == 0)
{
printf (“Names are the same”);
}
else
{
printf (“Names are different);
}

gets

Prototype:

void gets (char * string1)

Description: Receives a string via keyboard and stores it in string1. Characters


are stored until enter is pressed.

Example:

char name [10];


gets (name);

Comments:

1. the gets () function allows the user to provide more characters than can be
stored in the vector, which can cause an error. To avoid this problem, you can
use the fgets function:

char name [10];


fgets (name, 10, stdin); / * 'stdin' is a file opened by default, related to
data entered via keyboard * /

In the example shown, fgets would take 9 characters (or until the user hit enter)
and store the data entered in the string name by adding the string terminator
character. It is important to note that if the user typed enter before 9 characters,
the newline character ('\ n') would also be stored in the vector.

2. gets () ends when the user enters a space, preventing typing sentences with
more than one word. To work around this issue, you can use scanf data pickup
options:
scanf (“% s,” str); / * Get a string until the first space is inserted * /

scanf (“% [\ n] s,” str) / * Receives a string until sent the ASCII character \ n,
which corresponds to enter * /

Controlled Data Entry


You can make a controlled data entry (ie characters are checked as soon as they
are received) by receiving them one by one. In the following example we will
implement a password entry that shows the * characters on the screen instead of
the corresponding letters using the getch function (which does not echo the
character entered for the monitor). Note that only letters and not numbers and
symbols will be accepted.

int i = 0; char str [9];


printf (“Enter an eight letter password”);
while (i <8)
{
str [i] = getch ();
if (((str [i]> = 'a') && (str [i] <= 'z')) || ((str [i]> = 'A') && (str [i] <= ' Z '))))
{
printf (“*”);
i ++;
}
}

Dynamic Memory Allocation


Dynamic memory allocation consists of reserving space for on-demand data
storage, freeing that space when it is no longer needed. For dynamic
allocation, alloc.h library functions are used, the main ones of which will be
presented here.

The malloc function is used to try to allocate a contiguous space of n bytes of


memory. If it succeeds it returns the start address of the memory area, otherwise
it returns zero. The prototype of the function is:

void * malloc (int n);


Example:

int * v;
int n;
printf (“How many elements in the vector?”);
scanf (“% d”, & n);
v = (int *) malloc (n * sizeof (int)); / * Allocate n times the size of an 'int' * /
if (v == 0)
{
printf (“Error”);
}
else
{
/ * here could come the code for vector manipulation
.
.
.
* /
free (v);
}

The free () function is called at the end of using dynamically allocated memory
space to free this space, allowing it to be used by other dynamic allocation
operations. The free prototype is as follows:
void free (void * ptr)

where ptr contains the starting address of the memory area to deallocate.
Chapter 4
Programming with Arduino
To develop your application and put your ideas into practice with Arduino, there
is no escape from programming. The writing of the software, but well called in
this case “firmware,” that is, a program that will be embedded in a
microcontroller is the most important step of the project execution.

Once you've done the architecture and designed the wiring layouts for all
hardware that will interface with Arduino, the next step is to get your hands dirty
and write the code that will run on your board. Let's remind you of the basics of
structured languages that are important and give you the conditions to develop
your first applications and walk with your own legs. Come on!

What do you Need to Know to Start Programming an Arduino?


Preparing your Setup
The first step in getting started programming Arduino is to download and install
the IDE used to write and write the codes on the board. This IDE is open source
and is available for Windows, MAC, and Linux. The download can be done
directly on the official page.

Basically, we should perform the following three steps:

1. Power and connect Arduino to PC via USB cable

2. In the IDE, select the board model

i. Open the Tools tab, select the Board option and then select
Arduino Uno (or any other model you are using)

3. Select serial port to which the card has been assigned

i. Open the Tools tab, select the Serial Port option and then select
the COMX port, where X is the number the PC has associated
with the serial port assigned to Arduino.
After these three steps, the Arduino IDE is ready to use and to write the code on
your board.

What Language does Arduino Use?

Arduino's programming language is based on the famous C and C ++ languages ,


as well as the Wiring language.

The C language is said to be a low-level language, that is, a language that is


close to the language of microcontrollers and processors, in which we have to
program bit registers, manipulate memory and execute processor instructions. C
++ is already a high-level language; that is, its level of abstraction is higher, and
it is closer to human language than to computers. In high-level languages, we do
not manipulate memory and hardware resources directly, but rather through
libraries and previously available resources that make the language more
transparent to the programmer.

The Arduino language uses a number of libraries and features so that the user
does not have to manipulate microcontroller bits and registers. From the user's
point of view, only function calls and logical procedure writing are used.

If you have already programmed any of these languages, Arduino will not be a
problem for you. If you have never programmed in C / C ++, or even any
language, there are no problems either! Arduino is very intuitive, and the whole
complex part is encapsulated in libraries and functions.

How to Compile and Record a Program


Compiling and recording a program in Arduino is very smooth. First, let's
understand what it is to compile a computer program.

Compiling, in the context of programming, means checking all the syntax of the
code and, if everything is written within the rules of the language, creating the
so-called object code, which is another program, semantically identical to what
you wrote, but which is written in microcontroller language. The file generated
by the compilation process is exactly the file uploaded to Arduino at the time of
writing it.
To compile a program in the Arduino IDE, simply use the shortcut ctrl + R or
access the compile command in the Sketch -> Verify / Compile tab.

Now, after compiling a program, we need to record it on our board. To do this,


make sure that the card is properly plugged into the USB port of the PC and that
it has been recognized by the IDE.

If so, just use the shortcut Ctrl + U, and the code will be uploaded to the board.
Or, access the upload command from the File -> Upload tab.

What do you Need to Know to Understand a Program in Arduino?


A computer program has several different components. With Arduino is no
different. Like other programming languages, it has variables, functions and
routines, logical control structures, and so on. We will understand the main
components of an Arduino program in this session.

Components of a Code

Variables

A program variable is a predefined size memory space associated with the type
of the created variable. For example, if you need to do a simple arithmetic
account in your program, you could create a variable of type Integer named X.
So you could write the following line of code:

X = 2+ 3;

The memory space associated with variable X will be filled with the value 5.

Variables can have different types. In Arduino, variables can be of the following
types:
boolean: true or false
char: one character
Byte: 8-bit size
int: 16-bit signed integer
unsigned int: 16-bit unsigned integer
long: signed 16-bit integer
unsigned long: unsigned 16-bit integer
float: simple precision real number (floating point)
double: double precision real number (floating point)
string: string
void: empty type (no type)

Thus, depending on the mathematical needs and logic characteristics of your


program, you will need to declare variables of one type or another.
Value Assignment
Value assignment is the act of assigning to a variable that a value has been
created to be stored by it. This is done in Arduino through the "=" sign.

See the examples below:

Arduino Variable Declaration.

In the example above, a whole variable name was created X, and a type float
variable name Y. Using the assignment signal, we store the value 5 in the X and
1.3 for Y.

Functions and Routines


Functions and routines are separate pieces of code from the main program
structure that perform a given task and may or may not return a result. In the
classic definition, functions are code snippets that return a value, and routines
are functions that return nothing. However, these two names are used
interchangeably in everyday life.

For example, if you are writing a program and need to do a calculation of adding
some variables several times throughout the code. Instead of writing this
calculation multiple times throughout the code, you can create a function named
similar (x, y, z) and call that function each time you want to do the math.

The functions have the following syntax:

Declaring Functions with Arduino.

Note that a function is composed of:

Function Type: This is the type of value the function returns. In our
example, the result returned by the function is an integer, so the type
of the function will be Int. It is declared before the function name
(in red in the example). If the function returns nothing, the type
must be Void.

Function Name: This is the name you will use throughout the code
to call the function. It is blue in our example above.

Function Parameters: Parameters are the values the function


receives in order to perform calculations or logical procedures.
These values must have a type. In our example, we have three
parameters, x, y, and z, of integer type. Parameters are declared in
parentheses right after the function name.

Function Body: In orange, in our example is the function body


itself. After the function declaration, the logical procedure you want
to write must be enclosed in braces. Between these two keys, you
will write the calculation or any task you want to perform with the
function.

Flow Control and Decision Making Structures


Throughout your code, you will always need to make decisions, direct the flow
of the algorithm and its tasks and calculations, loop to populate vectors, or
implement a logical task and various other possibilities.

All of this is done through the flow control structures. We will highlight the top
five of them by dividing them into two groups: Decision Making and Flow
Control.

Decision Making

If..else

The basic structure for decision making is if..else. As its name suggests, he
makes a decision based on a logical assessment. If the result of this evaluation is
true, the structure executes code subsequent to if, if the result is false, code
follows to else is executed .
The syntax is as follows:
If (logical expression)

Else
… ..

Example:

Using if… else with Arduino.

In the example above, variable X will be given 5, because the result of the
logical expression in parentheses in if is true. If it were false, the value of X
would be 2.

There are some variations, such as if… elseif… .else, and also some abbreviated
ways of writing the structure. However, if you understand the basic if..else, all
other variations will be natural to you.

switch ()
The switch is a decision-making structure that evaluates the value of a control
variable and directs the code to a specific case. Let's see what the syntax is like
to understand it better.
Using Arduino switch ().

In the structure shown above, the variable x controls decision making. If the
value of x equals 1, the code goes to line Case 1. If x equals 2, Case 1 is ignored,
and the code executed is as follows in Case 2. The number of cases is undefined,
but it is recommended to be no more than a dozen and no less than three.

In the event that there is no Case corresponding to the value of the control
variable, the code executed is Default, usually written at the end of the Switch.

The breaks in the middle of the switch say to the compiler to and out of the
switch, continuing the code that comes just below the closing of the keys that
define the switch. They are placed after each Case to prevent unnecessary
evaluations from being made.

Flux Control
Flow control structures are the famous loops used to iterate and perform tasks.
The two main ones are for and while.

For
The for syntax is as follows:
Using for with Arduino.
This structure means that the code entered between the keys following the for
will be executed x times. That is, if x equals 5, the loop will run 5 iterations. At
each iteration, the value of the control variable i is iterated as well. Thus, in the
first iteration, the value of i is zero, the second is one, the third is two, and so on
until i is equal to or greater than x.

While

While is also a widely used looping structure. The code snippet inserted
between the keys following the while is always executed as long as the logical
expression is true. The moment the logical expression of while is false, the loop
will not be executed anymore.

Example:
While with Arduino.
In the example above, the loop will be iterated fifteen times. Note that when
starting While the control variable is zero. And inside while there is a line: i + +.
The ++ operator causes the variable to be summed to 1 unit. That is, at each
iteration of while, the variable i is summed by 1 unit. Thus, in the first iteration, i
starts with zero but is summed by 1 unit and becomes one. In the second
iteration, i starts equal to one, is iterated and becomes two. And so on until i
equals fifteen. At this point, the while logical expression becomes false, and the
while body is no longer executed.

Standard Arduino Code Structure and Libraries


In every Arduino code, you will always find two functions: void setup () and
void loop (). In addition to these, you will commonly see lines with the #include
directive, which is used to include libraries in code.

Libraries are collections of functions and parameter and variable definitions that
instead of being included in the main program, are saved in a separate file and
included in the main program through a line of code. Thus, all functions and
definitions within these libraries are available in your code. Libraries are very
useful as they allow you to split a complex program into more than one file.
Library files generally have the extension .h.

The void setup () function is where Arduino microcontroller initializations and


configurations are made. The void Loop () function is where we will write our
code itself. This is the infinite loop that will run while Arduino is on. All actions
in our code should be in this loop.

See the figure below for an example in which two libraries are included, one for
working with strings and one for controlling LCDs:

Includes in Arduino.

This default structure, in conjunction with the other concepts you just learned,
will be the core code tools of all your Arduino programs.

Continue to learn from reading the next section of this chapter. There we will
talk about the hardware interfaces of the Arduino board and how to control and
use them in your applications.

Hardware Interface
In the first part of this chapter on how to program Arduino, we covered only
software development issues. Functions, libraries, decision structures, and loops,
are tools used in your code to implement the logic you need.
But we also have the hardware!

Arduino has a number of libraries and functions ready to access microcontroller


settings and manipulate hardware interfaces. It is the existence of these libraries
and functions that encapsulate all the complexity of the microcontroller that is
largely responsible for the ease of learning and programming Arduino.

Some things end up repeating in every program. Configuring digital and analog I
/ Os, establishing a serial communication channel, and generating/reading PWM
signals are basic concepts you will always need for most of your applications.
Thinking about it, let's understand how this is done in this session.

Digital I / Os
The Arduino has 14 digital inputs/outputs. These I / Os are used to read and
generate signals of a digital nature, that is, signals that assume only two states:
high (5 V / 3.3V) or low (GND).

Before using a digital pin, you must set it as input or output. By default, pins are
configured as input, but it is good programming practice to make this explicit in
your code.

The functions you will use to configure, read, and set a digital pin are:

void pinMode ()

Used to configure pins as input or output. Its usage syntax is as follows:

pinMode (pin, mode);

Where pin is the digital I / O number you want to configure and mode can be
INPUT, INPUT_PULLUP and OUTPUT. For example, to set pin thirteen as a
digital output, you would write:

EX: pinMode (13, OUTPUT)

int digitalRead ()
The function used to read the state of a digital pin. In this case, you must have
set the pin as an input. The syntax of this function is:
digitalRead (pin);
Where pin is the number of the digital pin, you want to read. For example, if you
want to know if pin 13 is high or low, you should write the following line of
code:

X = digitalRead (13);

In this case, the variable x must be declared beforehand. It is responsible for


receiving the value corresponding to the pin state (1 if it is high level and 0 if it
is in GND).

void digitalWrite ()
Finally, the function to write in the pin, or as it is said, “set” the pin to a certain
logical level. The usage syntax is as follows:

digitalWrite (pin, value);

The pin is the pin number you want to "set." Value can be HIGH or LOW. So, if
you need to set pin 13 to a high logic level (5V), you should write the following:

digitalWrite (13, HIGH);

Remember that to use this function, the pin must be set to output. A classic
example of using digital I / Os is led blink; a simple firmware focused on
flashing a led. See the program below:

Example: Led Blink


Example Arduino Led Blink.
In this code, in the initialization function, we set pin 13 as a digital output.

In the infinite loop, the digitalWrite (13, High) function is called, responsible for
assigning a high level to pin 13, that is, the led connected to pin 13 is activated.
Next is called the delay (1000) function, which pauses the loop for a thousand
milliseconds, that is, for one second.

After waiting for this time, the digitalWrite () function is called again, but this
time to assign a low logic level to pin 13, i.e. to turn off the LED connected to
pin 13. Finally, the delay function (1000) is again call to pause another second.

Analog I / Os
The analog channels are 6. These inputs are used to read analog signals, i.e.
signals whose voltage level varies continuously between 0 and VDC (usually 5
or 3.3V).
These inputs are connected to the ATmega328 A / D converter. The A / D
converter is an internal circuit to the MCU responsible for converting the analog
quantities applied to the inputs into a digital value with which the processor can
work. The Arduino UNO A / D converter has a 10-bit resolution. This means
that a signal ranging from 0 to VDC in analog terms when converted to digital
will be a value ranging from 0 to 1024. Each unit in this range from 0 to 1024
corresponds to VCC / 1024.
If the reference voltage is 5V, each unit in this range from 0 to 1024 will
correspond to 4.88 mV.
To work with analog inputs, you will use the following functions:
analogReference (type)
This function is used to set the A / D converter reference voltage. Its syntax is:
analogReference (type);
Which type defines the possible A / D channel settings. Are they:
DEFAULT: The default conversion voltage is the board supply
voltage. Usually, these values are 5V or 3.3V
INTERNAL: Internal reference of 1.1V in Atmega168 and
Atmega328, and 2.56V in ATmega8;
INTERNAL1V1: 1.1V reference, only on Arduino Mega;
INTERNAL2V56: Internal 5.6 V reference, only on Arduino
Mega;
EXTERNAL: Voltage reference applied to the AREF pin (between
0 and 5V).
To configure the A / D converter to operate with external AREF voltage, for
example, you must write the following:
analogReference (EXTERNAL);
The other function used is:
int analogRead (pin)
This function is used to read the value of one of the analog inputs. Its syntax is
as follows:
SensorValue = analogRead ( pin );
SensorValue is any variable to store the value read. The pin parameter is the
input number you want to read. For example, if you want to store the value of
analog channel 1, you would write:
SensorValue = analogRead ( 1 );
Analog Sensor Example
In the example below, we see how an analog sensor is read. This sensor could be
a thermistor to measure temperature, a potentiometer, a light sensor, and any
other whose output signal is analog.

Analog Sensor Example with Arduino

In the void Setup () function, we set pin 13 as the digital output and the A / D
converter reference voltage for DEFAULT, i.e. the board supply voltage.

In the infinite loop, we use the analogRead () function; to read the sensor value,
which in this case is located at pin A0 (value 0 could also have been assigned).

After reading the sensor value, pin 13 is activated, and shortly after that a delay
whose wait value is the read value of the sensor is called. That is, the hold time
depends on the value read from the sensor. After the first delay, pin 1 is
deactivated, and a new delay is called.

This program only turns on and off the LED connected to pin 13, varying the
waiting time according to the sensor signal.

Serial Communication
Serial communication, known by the acronym UART, is a very interesting
feature to make a communication channel between the board and the computer
or between the microcontroller and other modules such as GSM, GPS devices,
among others.

Here are the main functions for using Arduino UNO serial channel. On the
board, you can see that there is a digital pin named RX, and another pin named
TX. These are the two pins used in serial communication.

The functions you will use to establish serial communication are:

Serial.begin (): It is used to configure the communication rate and


other parameters. It is the first function that should be called

Serial.available (): This function returns the number of bytes


available in the read buffer. It can be useful to find out if there is
any data in the buffer to read or not.

Serial.read (): Reads the most recent byte of the read buffer.

Serial.print (): Writes a given the word in ASCII code to the serial
port.

Serial.println (): Same as above, but it adds at the end of the word
a line break character (/ n).

Serial.write (): Writes a byte to the serial port.

The Arduino IDE has a serial terminal that can be used to view receiving and
sending data to the board. To access this serial terminal, click the Serial Monitor
icon or go to Tools -> Serial Monitor menu.

PWM
The PWM technique, which stands for Pulse Width Modulation, is a technique
used to vary the average value of a periodic waveform. The basic idea of PWM
is to keep the frequency of a fixed square wave and vary the time the signal is at
a high logical level.

That is, the time the signal is activated varies. This time is called the Duty Cycle,
and it is by varying this time that the average value can be varied proportionally.

Arduino Uno has specific pins for PWM outputs. These pins are indicated by the
'~' character in front of their number. The function used to generate a PWM
signal is AnalogWrite, see its syntax below:

analogWrite (Pin_PWM, value);

Pin_PWM corresponding to the pin to which the PWM will be applied. Value is
the duty cycle to be applied to the PWM signal. This value must be between 0
and 255, with 0 being a 0% duty cycle and 255 being a 100% Duty Cycle.

Programming
Let's now make an example application for you to train the knowledge gained.
This example will be a little different. We will not show any code, because
everything you will need, the functions and programming structures, have
already been shown in the previous examples.

Here in our example, we will describe the application and just present the logical
structure of the program. You are the one who will have to implement in your
Arduino by replacing the logical descriptions with the necessary functions and
codes, as you learned in this post. So, are you excited ?! To enter the Arduino
world, you have to be!

Let's start.

Challenge
Our application is as follows:

“Control the brightness of a led, using as a control signal the ambient


temperature. Also, the ambient temperature should be displayed on the
computer terminal. ”

Description of Application Needs

From the description of our challenge, we know the following:

We have to control the brightness of a led. This means we have to


apply a variable voltage signal to the led terminals. In other words,
we have to use a PWM output to vary the activation voltage of the
led.

The brightness of the led should be proportional to the ambient


temperature. That is, we will have to read a sensor to know the
ambient temperature. This means that we will use one of the analog
channels to read the signal from a temperature sensor.

It is necessary to display on the PC terminal the temperature value


read with Arduino. This means that we will have to use the Arduino
serial channel to send the read temperature value to the PC and
display it on a serial terminal, for example, the Arduino IDE
terminal itself.

From the logical point of view, the problem does not require major
elaborations. We basically have to monitor a temperature sensor
continuously, and based on the variations that the sensor perceives,
we will adjust the Duty Cycle of a PWM applied to an LED and also
send the temperature data to the PC via a serial port.

Algorithm
Let's draw an algorithm of what this application would look like. We already
know the base structure of every Arduino program, which is the void Setup ()
and void Loop() functions. In the image below, you can see the walkthrough of
how your void Setup () function should look.

Examples:

// We have to declare the variables we will use


Step 0: Declarable Variable to Store Sensor Lad ° Value
void setup ()
{
// Here we have to configure and initialize Arduino

Step 1: Configure pin 13 (led) for digital output

Step 2: Set the A / D converter to the standard reference voltage

Step 3: Configure Serial Channel Baud Rate

Now the algorithm of what the Void Loop () function should look like.

Example §

void loop ()
{
// Here is our application itself

Step 1: Read Temperature Sensor Value

Step 2: Knowing the sensor's temperature range, convert the read value using a
factor to fit a range from 0 to 100

Step 3: Use the converted value to vary the PWM Duty Cycle applied to pin 13
led

Step 4: Convert the read value from the temperature sensor to an actual
temperature value.

Step 5: Send this value to PC using the serial channel

Step 6: Use a delay to regulate the reading frequency of the sensor and also to
ensure that serial communication has finished sending data. Writing data on PC
and computationally slow operation

So, now it's easy, right ?! Go back to the previous topics of the text, identify
which functions to use, and write your code.

Ardublock - Graphic Programming for Arduino

How to Program Arduino with Block Graphics Language

Ardublock is a programming language that uses ready function blocks. Just as


Arduino helps enthusiasts get in the middle of electronics and automation,
Ardublock helps those with no programming skills to create Arduino programs
simply and intuitively.

Since Ardublock's available blocks match the functions of a programming


language, Ardublock has a wide range of usability and application.

Installing Ardublock
Once Arduino is configured, go to the Ardublock website to download and
install Ardublock on the Arduino IDE:

Download the file from the website in the DOWNLOADS section.

Locate where the Arduino Sketchbook is located.

In Windows, by default it is found in: “Documents \


Arduino” inside your user's folder;

On Mac, by default it is found in “Documents / Arduino”


inside your user's folder;

On Linux, by default, you can find “sketchbook” in your


user's folder.

Once you find this folder create a subfolder named: tools and inside
it another subfolder called ArduBlockTool and yet another subfolder
called tool.
Copy the downloaded file to this last folder.

Now when you open Arduino IDE, in the tools section, Ardublock
will appear in the list. (See figure below).

Programming with Ardublock


Here we will demonstrate how to perform a simple LED flashing program in the
Ardublock program environment. On the left of Ardublock are all available
functions, from logic operators and state conditions to Arduino input and output
controls, etc.

Phases

1. Loop Function
Any Arduino program must contain the loop function. This function is
performed indefinitely when Arduino is turned on. So that's where we want to
put our blocks.

Hit the Control section and drag the loop block to the desktop;

2. Setting the LED


To simplify the project, we will use the internal LED, already embedded in
Arduino, located on pin 13.

Push in the Pins section and drag the digital pin set block to the
desktop;

This block has 2 arguments: Pin number and desired logical state.

Push in the Pins section and drag the digital pin set block to the
desktop;

Select pin 13 and high logic level (HIGH);

3. Lead Time
Let's use the delay milliseconds block to make a delay of 1 second. Its parameter
is the time delay in milliseconds.
Click on the Utilities section and drag the delay milliseconds block ;

Set the value to 1000. (Corresponding to 1 second);

4. Connection
Ardublock, like the Arduino language, is sequential so that it will perform one
function at a time. To give the instructions of instructions in Ardublock, we
connect one function below the other by simply dragging and attaching one pad
below the other.

Do this for the last 2 blocks created. Placing the delay below the
digital pin set.

Now, these 2 little blocks form one block. Since we want to turn the LED on for
a second and then turn it off for a second, we need a second block of this to do
the second operation.

Right-click on this block and hit the clone button to make a copy.

Snap the copy of the block created below the original block, and set
the second digital pin set to LOW

5. Connection with the loop


This new block now represents what we want to do in the program: Flash the
LED at 1-second interval.

Finally, connect this block inside the loop by dragging it.

Click the upload button to save the program to your Arduino.

6. Comments
Make sure in the tools section of the Arduino window that the card
and communication port has been selected correctly.

Ardublock takes care of configuring pin inputs and outputs to make


it easier for the user.
Here we have reached the end of this chapter: Programming with Arduino. At
this stage, now we hope that you are confident enough to test your first
programming with Arduino.
Chapter 5
Arduino Electrical Scheme
In this chapter, we will explain the entire Arduino UNO R3 version schematic,
showing the functions of each component in the circuit. All board components,
without exceptions, are explained here. At the end of this chapter, you will
understand the basics of each part of the circuit and have a good foundation for
better evaluating commercially available Arduino cards, understanding the
differences between different models, including compatible clones and cards.

Our goal during the preparation of this material was to pass as much information
as possible while maintaining a simple language. The idea is that anyone with
any knowledge of electronics and design can understand the material without
any major difficulties.

During the explanation, we also made several comparisons of UNO with other
versions of Arduino. This will allow you to learn more about the differences
between them, and to understand any schematic of the Arduino family better.
We hope you will enjoy it and like it.
Arduino UNO Project
Currently, Arduino UNO is the most popular and best-selling version of the
entire Arduino line, as well as serving as a base for other models such as the
Arduino MEGA 2560, for example. For this reason, we chose him to do this
section.
Designs across the official Arduino line are made using Eagle software. There is
a free version of Eagle that you can download and use to open or modify the
original Arduino designs. The original Arduino UNO project can be downloaded
directly from the Arduino website.
Installing Eagle and downloading Arduino project files are optional and are not
required to accompany this lesson.
Schematic Analysis
The complete schematic diagram of the Arduino UNO R3 can be seen in the
image below.

Original Arduino UNO R3 Schematic


This schematic may seem a little intimidating, and even a little confusing at first
glance.

For ease of understanding, we have arranged it in the original layout. This was
done by just aligning the name and value of the components, and also slightly
improving the separation between them. However, no components have been
modified, removed, or added, maintaining 100% compatibility.

We also split the components into three main blocks: USB processor, main
processor and power. All of them will be explained in the following sections.

The figure below shows the schematic after the organization.


Arduino UNO R3 schematic organized in parts.
Another difficulty that normally occurs when analyzing Arduino operation is the
difficulty of locating a specific component on the board since it does not have
the identification of all of them. Only the LEDs, connectors, and reset buttons
are labeled. Resistors, capacitors, chips, and other components are not identified.

In the figure below, we identify all board components with the same names used
in the schematic. You can use it as a guide for locating components.

Named Components on Arduino UNO Board


Note the two components marked with a question mark (?). They are on the
board but do not appear in the project. This indicates that the project published
by the Arduino team is from an earlier version, and not exactly the same as the
one being produced. However, we do not notice any other significant
differences, and this does not hinder our analysis.

Now enough talk. Let's get down to business, which is the analysis and
explanation of the schematic. In the following topics, we will explain how each
of the three main blocks works:

USB processor

Main processor

Food

USB Processor

The USB processor, named U3 in the schematic, is responsible for


communicating Arduino with your PC via the USB port. This is required as the
Arduino main processor (ATmega328) does not support a direct connection to a
USB port. This way, the USB processor converts the USB data from the PC to a
serial signal (UART), which can be read by the main processor. We can then say
that the USB processor works as a USB-Serial converter.

The processor used for this function is ATmega16U2. Earlier versions of


Arduino, such as Arduino Duemilanove, Diecimila, Nano, MEGA (earlier than
R3), and many other similar cards, use another component for this function, the
FT232 manufactured by FTDI. However, many users have complained that
switching from FT232 to ATmega16U2 has caused Windows and MAC
compatibility issues. This way, even today, many "Arduino compatible" cards
continue to use FTDI chips.

Let's take a closer look at how the ATmega16U2 USB processor is implemented.
The figure below shows the circuit in more detail:
USB processor schematic

USB Connector
On the left, we can see the USB connector named as X2. This is a Type B
female USB connector, and this is where you connect the USB cable. Other
versions of Arduino use different USB connectors. The Arduino Nano, for
example, uses the Mini USB connector, and newer versions like Arduino
Leonardo, DUE, and Zero use the Micro USB connector, which is the same as
used in most current smartphones.

The USB connector has two functions - bringing information from the PC's USB
port to the card, and also feeding Arduino when no external source is connected.

USB Filter and Protection

Leaving the connector, the signals and power from USB pass through the block
called "USB filter and protection." We will analyze all the components present
in it.

F1
First, all the current coming from the PC's USB port (which will power the
Arduino and other circuits) goes through the F1 component. This component is a
fuse, and has the function of protecting the PC's USB port in case of a short
circuit or accidental overload on the Arduino board. By default, each USB port
should be capable of delivering up to 500 milliamps of current, and the fuse is
there to protect it if this limit is exceeded.

In fact, this fuse is nothing more than a resistor whose resistance value increases
with increasing temperature (also known as PTC or positive temperature
coefficient). However, unlike a traditional fuse that blows when overloaded, this
component has the ability to reset itself when operating conditions return to
normal.

For current values of 500 milliamps or less, the fuse resistance value remains
low. In this way, the current flows freely through it (effectively it is as if it is not
there). However, when there is a short circuit or overload on the Arduino, the
current drained from the USB port increases. This causes more current to pass
through the fuse, causing it to heat up and increasing its resistance. Increased
resistance cuts the current flow, effectively functioning as a blown a fuse.
However, if the short circuit or overload is removed, the fuse cools, and its
resistance value lowers back to its original state.

However, it is important to keep in mind that the 500 mA value is just a


reference. It is only the minimum required by the USB standard, and many PCs
can provide more current than that (in addition to having their own built-in
protection mechanisms). So it doesn't necessarily mean that your PC's USB port
will be damaged if you drain 501 milliamps of it. The actual current value that
effectively "trips" the fuse is not exactly 500 milliamps, but is a function of the
time it takes to trip, along with the ambient temperature value.

All versions of Arduino with USB port have this fuse. It is the MF-MSMF050-2
model manufactured by Bourns

Z1 and Z2
USB communication is via the connector pins labeled D- and D +. These signals,
after exiting the connector, pass through components Z1 and Z2. They are
known as varistors, and have the function of protecting the ATmega16U2 pins
against electrostatic discharge, which could cause the processor to burn out or
malfunction.
Electrostatic discharges or ESD(electrostatic discharge) are events that occur
when approaching an object charged with electrical charges to another that is
discharged. The most common example of electrostatic discharge is when you
walk on a rug or carpet wearing a rubber-soled shoe, and then take a shock when
you try to open the metal door handle. In this case, your body is charged with
electrical charges because of the friction of the shoe with the carpet; then these
charges are quickly transferred to the door handle, causing you to receive a slight
shock. If your body is charged, and instead of the doorknob, you touch an
electronic circuit board, loads are transferred to it, which may cause circuit
damage (even with the board off).

Electrostatic discharges occur all the time, and in most cases, the current is too
low for you to feel a shock, so they end up unnoticed, but can still damage the
most sensitive components. Components and circuits with which the end-user
has direct contact (as is usually the case with USB ports) deserve special
attention about ESD protection, as they normally receive the discharges.

Like the fuse, the varistor is also a resistor, but in this case, the resistance value
decreases as the voltage on it increases. At low voltage values, such as occur
during normal USB port operation, the resistance of the varistor is quite high (in
the order of 100 mega ohms), so the signals pass through them without
deviations. However, when an electrostatic discharge event occurs, the voltage
increases rapidly (up to several kilovolts), causing the varistor resistance to drop,
and diverting excess current from the ATmega16U2 pins to the Arduino GND,
protecting the processor.

The component used for this function is CG0603MLC-05E, also manufactured


by Bourns.

Arduino versions that use FTDI chips in place of ATmega16U2 usually do not
have ESD protection components. This is because these chips already have built-
in protection structures, which is sufficient in most cases.

L1
The component called L1 is known as ferrite. Basically, ferrites are used for
noise suppression. In this project, its function is to filter out possible noises that
may come through the USB cable mesh to Arduino, as well as to isolate the PC
from noise generated by Arduino. Not all versions of Arduino have this
component, and its presence is not required for operation.

RN3A and RN3D


The last components of this block are the 22 Ohm resistors called RN3A and
RN3D. Their nomenclature comes from the fact that in the Arduino design, no
individual resistors are used, but components that have 4 resistors together.
These components are called a "resistor network" or "resistor network" (RN).
Thus, we have, for example, that the component named RN3A is resistor A of
resistor network 3, RN3B, is resistor B of this same network, and so on to the
fourth resistor (called D). Note that in this case only 2 resistors were used,
resistor B and resistor C were left over, and are located just above the filter and
shield block.

RN3A and RN3D Resistors


The function of these resistors is to attenuate noise and voltage spikes that may
come through the USB cable, helping to protect the processor. However, they
are not required to function, and versions using FTDI chips do not normally use
them.

Oscillator
The oscillator is the heart of any processor and is responsible for generating the
clock pulse. Virtually all existing processors use an oscillator, and their
implementation is often quite similar. Although it uses few components, the
operation of this circuit is relatively complex, so we will not go into detail and
focus only on the fundamental features.

In this project, the ATmega16U2 oscillator was implemented using a crystal as


its main component (Y1). This crystal has a resonant frequency of 16MHz. The
function of the crystal is to generate a sinusoid, which will serve as the basis for
the clock. Internally, the processor transforms this sinusoid into a square wave.

In addition to the crystal, there are two 22 PF capacitors (C11 and C9), and a 1
Mega Ohm resistor (R1).

The role of resistor R1 is to facilitate the start of clock generation. Some


processors and integrated circuits require this resistor to get the circuit to work
after the power are turned on, but this is not required, and its use depends on the
chip manufacturer's guidance.

Capacitors C1 and C2 are required in this type of circuit, and in addition to their
other functions, have the role of adjusting the crystal frequency. Usually, each
crystal has the specification of which capacitor value is optimal for its operation,
and it is the designer's role to choose the value accordingly. Wrong capacitor
values may alter the resonant frequency of the crystal, or even impede its
operation.

USB Processor
This block comprises the USB processor itself, i.e. the ATmega16U2 chip. In
this project, he is responsible for receiving data from USB and turning it into
serial signals.
USB Processor Block

C7
We can see the 100 nanoparad C7 capacitors connected directly between the 5
Volt supply voltage and the GND. In this circuit, the capacitor performs the
function of the " decoupling capacitor." Capacitors with this function are very
important in the operation of digital integrated circuits. Virtually all integrated
circuit manufacturers recommend the use of capacitors attached to the power
pins, with 100 nanofarad a classical value. In addition to the value, the most
important requirement when using a decoupling capacitor is its location and
should be positioned as close as possible to the power pins of the integrated
circuit in question (if it is removed, its effect will be null).

The main functions of a decoupling capacitor are:


Filter out the noise coming from the power supply, not letting it get
into the integrated circuit. Also, they filter out the noise generated
internally in the integrated circuit, not letting it spread to other board
components.
A digital circuit, such as a processor, consumes peak current, which
usually coincides with clock pulse transitions. The capacitor has the
role of storing enough power to supply the current surges required
by the processor.
RN1C
The RN1C resistor acts as a pull-up resistor, and its function is to keep the
processor pin 24 at a high level (high level, in this case, means that there is a 5
Volt voltage at the pin). This is the processor reset pin, and it is active at the low
logic level, i.e. the processor is reset when the pin voltage is zero. In this way,
the resistor holds the voltage at 5 Volts and prevents the processor from resetting
improperly. The ATmega16U2 already has an internal pull-up resistor for this
pin, and the use of internal resistor is not required but is indicated in
environments with high noise levels.

D3

Diode D3 has the role of reinforcing the electrostatic discharge protection (ESD)
on pin 24.

But why is the diode placed only on this processor pin, not the others?

Well, the story is a little long, but we can say that processors usually already
have internal ESD protection structures, which are comprised of two diodes
connected to each pin. However, the reset pin is a special case as it is used
during software recording, and some (but not all) programming methods apply
12 Volts to this pin during the process. This fact prevents the ESD protection
structure from being fully implemented in the reset pin since the diode would
prevent the application of 12 Volts the same. In this way, the chip manufacturer
removes one of two internal protection diodes. As the Arduino production does
not use the programming methods that require the 12 Volts to be applied to the
reset pin, the omitted internal protection diode has been reinserted externally.

The use of this diode is optional and is not present in many versions of Arduino,
such as Pro, ProMini, Nano, Duemilanove, MEGA and others.
C8
The ATmega16U2 processor has an internal voltage regulator, which is required
for the operation of some of its circuits. For this regulator to work properly, the
manufacturer recommends that a capacitor with a value of 1 microfarad be
connected to pin 27 of the processor (named as UCAP).

USB LEDs
There are two LEDs, RX and TX, which are controlled by processor software
and used to indicate USB communication activity. That is, when there is
information sent from Arduino to the PC, the TX LED flashes, and when there is
information sent from the PC to Arduino, the RX LED flashes. The
implementation of this circuit is very simple and traditional; there is only one
resistor in series with each LED (RN2B and RN2C) with the value of 1 kilo
Ohms, which has the role of limiting their current.

LEDs to indicate USB Bus Activity


Note that since the LEDs are wired directly at the 5 Volt voltage, their activation
occurs in an "inverted" mode. That is, the LED goes out with a high logic level
on the pin and lights up with a low logic level.

Programming Connector

ATmega16U2 Programming Connector


Usually, this connector is used only during Arduino manufacture; at the time, the
first software is written to the processsor. This connector is for connecting the
Arduino board to the programmer that will record the software (an example of a
programmer is AVRISP mkII).

Other Components in the USB Processor


There are still some components attached directly to the ATmega16U2
processor. Let's explain to them now.

RN4A and RN4B


Resistors that interconnect serial between processors.

These two resistors are connected in series with the serial RX and TX signals
that go to the ATmega328 main processor, i.e. they are the link between the two
processors. The presence of these resistors in series allows you to use Arduino
shields that make use of the ATmega328 processor serial. In a way, it's as if the
serial coming from the ATmega16U2 processor is disconnected the moment you
plug into Arduino, a shield that uses the serial. This brings greater flexibility in
the use of Arduino, as it allows the use of serial with other shields, but it is as if
the USB port was disabled while there is a serial shield plugged in. Thus, to
program Arduino, or to communicate with the PC, it is necessary to unplug the
shield that uses the serial.

C5 and RN2D

Capacitive coupling on the Reset Line


When you write your software to Arduino, the ATmega16U2 processor sends
the information to the main processor (ATmega328) via serial. However, while
recording, you must reset the ATmega328 processor to put it into programming
mode. ATmega16U2 sends this reset signal to ATmega328 via pin 13. Capacitor
C5 is inserted in series with this signal, making the capacitive coupling between
processors. This capacitive coupling causes the reset signal to be sent only for a
short time, which is necessary for the ATmega328 to be reset, but to prevent it
from being reset all the time.

The RN2D resistor is labeled "USB boot En" and is a pull-down resistor.
However, we could not get more information about its function.

JP2

JP2 Connector
It appears to be an expansion connector, but it does not come soldered to the
board, and we have no further information about its function.

Ground
Soldering Jumper
It is a soldering jumper, which is located on the bottom plate. It serves to
connect the ground from the USB cable loop (after passing through the L1
inductor) to the main ground. In electronic projects, designers typically make
this connection between the "different grounds" using a jumper, as this ensures
that they are connected only at one point, which prevents current from
circulating in unwanted areas of the board. This jumper is already factory closed.

Main Processor
Now that we understand the operation of the USB processor, it will be much
easier to understand how the main processor works, as the circuit
implementation is very similar.

As we said earlier, in Arduino UNO, the component that plays the main
processor role is ATmega328, also manufactured by Atmel Semiconductor and
named as ZU4 in the schematic.

Other Arduino models use different processors. For example, there are versions
of Arduino Nano and Duemilanove that use ATmega168, which is basically a
component identical to ATmega328 but with less memory. The Arduino MEGA
2560 uses the ATmega2560, which has more pins and more memory than

ATmega328. Arduino Leonardo uses the ATmega32U4 processor, which has


features similar to ATmega328, but it has a built-in USB interface, resulting in a
single processor board (but this version has not become very popular). Finally,
there are also Arduino versions that use ARM processors, such as Arduino DUE
(AT91SAM3X8E), and other platforms such as Intel Galileo, which uses an Intel
processor (Intel® Quark SoC X1000).

ATmega328 is the "brain" of Arduino UNO, and in short, we can say that it has
three functions:
Receives sends, and interprets serial signals coming from the
ATmega16U2 USB processor.
Runs the software that is programmed into it.
Interacts directly with shields and external elements, performing
device activation and sensor reading.
The figure below shows the main processor block:

Main Processor Schematic


Let's now take a closer look at how the main processor circuit is implemented.
Oscillator

ATmega328 Ceramic Resonator


The ATmega328 oscillator works very similarly to the previously presented
ATmega16U2 oscillator, and both have a 16 MHz frequency. The main
difference is that the ATmega328 oscillator was made with a ceramic resonator
instead of the crystal used in the ATmega16U2.

The ceramic resonator is named Y2 in the schematic, and the model used is the
CSTCE16M0V53-R0 manufactured by Murata. Ceramic resonators are
components with crystal-like function, i.e. they are also responsible for
generating the sine wave that will serve as the basis for the processor clock
signal.

Usually, the ceramic resonator is more compact than the crystal, and they come
with the adjustment capacitors installed internally, making the circuit simpler.
However, in terms of accuracy, the ceramic resonator usually performs worse
than the crystal; we can say in general that the resonator has an accuracy of 0.5%
against 0.003% of the crystal. That is why resonators are most commonly used
in compact and space-saving applications.
Arduino versions like Duemilanove, Diecimila, and MEGA use the crystal as a
resonant element. We are not sure what drove this switch to the ceramic
resonator in Arduino UNO. It may have been a legacy of the Arduino Nano, as
he always used resonators, but it's hard to say for sure.
Anyway, the important thing is to know that the circuit, in general, is the same,
only the capacitors are omitted (since they are already inside the resonator), and
the 1 Mega Ohm resistor that assists in the start of operation (R2) continues.

Main Processor
ATmega328 Processor
This is also a block similar to the USB processor. We can see in the schematic
the 100 nano Farad components C4 and C6, which perform the function of
decoupling capacitors for pins 21 and 20, respectively. The designer could still
have placed another capacitor to uncouple pin 7, as recommended, but it was not
inserted in this scheme.

The RN1D and D2 components fulfill the pull-up and ESD protection function
for the reset pin, similar to the RN1C and D3 components on the USB processor.

We can also notice the serial signals coming from the USB processor, which are
connected to pins 2 and 3 of the ATmega328, as well as the reset signal
connected to pin 1.

Programming Connector

ATmega328 Programming Connector.

This connector, like the USB processor, is used for programming the first
software made at the Arduino factory (this software is called bootloader).

Reset button

ATmega328 reset button.

The button is named as RESET in the schematic. When pressed, the button
closes the pins 1 and 2 contacts with pins 3 and 4, connecting the processor reset
pin directly to the GND. This causes a low logic level on this pin, which resets
the processor.

Shield Connectors

ATmega328 Connectors for Shield Fittings


These are the connectors used to plug the shields into the Arduino. They are
connected directly to the processor I / O pins, as well as to the 5V, VIN, 3.3V
and GND supply voltages.

Note that in the schematic, all signals with the same name are interconnected,
regardless of whether there is a physical connection between them. For example,
the two branches named AD5 / SCL are electrically connected, even though
there appears to be a "loose" end on the connector (see complete block schematic
image), so do the 3.3V, RESET, GND and all others.
Try to match the connectors shown in the schematic with the connectors on the
board. Note that they are named as POWER, IOH, AD, and IOL, and the green
caption indicates the numbering or function of the pin in Arduino. Also, there is
an inscription indicating the size and model of the connector, for example, the
caption "8x1F-H8.5" indicates that it is an 8-pin connector, a female-type
speaker, and an 8.5mm.
food
Let's move on to the last block of the schematic, and see how the Arduino UNO
power supply works.

The figure below shows the components present in this block:

Arduino UNO Power Schematic

Input Jack

This connector, named X1, is where you connect the external power supply plug.
It is convenient to use an external source to power the Arduino when it cannot
always be plugged into the PC's USB port, when there is an element in the
application that needs to be powered with a voltage greater than 5 Volts, or when
the circuit requires a current than 500mA supported by the PC's USB port.
Jack for an External Source

The recommended voltage range for external source Arduino power is 7 to 12


Volts, even though the board supports voltages of up to 20 Volts. The use of
voltages greater than 12 Volts may cause overheating of the regulators and is not
recommended (we will see more details about this below).

This connector is a female type and set to 2.1 mm, which means the pin in its
center is 2.1 mm in diameter. This means that the source used must have a male
connector, also with 2.1 mm and positive center (i.e., the inside of the plug has
positive voltage compared to the outside, which is the GND).

Image of 2.1mm Plug required for Connection to Arduino


Unfortunately, there is no international standard for this type of plug (as there is
for USB connectors, for example), so it is not difficult for you to come across a
power supply that does not have a proper connector to connect to Arduino.

Protection Diode
The current flowing through the input jack soon encounters the first component,
which is the protection diode D1. Its function is to protect the Arduino if an
inverted polarity source is accidentally plugged into the jack. An inverted
polarity font, in this case, would be a negative center model.

When accidentally connecting a reverse-polarity source to an unprotected


electronics board, it causes reverse current to flow, causing multiple components
to burn out, destroying most circuits. In the case of Arduino, diode D1 prevents
current from flowing backward, protecting the board. Briefly, we can say that
the diode functions as a closed switch for correct polarity sources, and as an
open switch for reverse polarity sources.

It is important to note that when a reverse polarity source is connected to the


Arduino, the Arduino is protected but does not work, and it is necessary to adjust
the polarity of the source for normal operation.

After passing through the protection diode, the voltage from the source is called
a VIN, and is also available on one of the Arduino connectors.

The diode used is the M7 model, which is the SMD version of the popular
1N4007, and the maximum current supported is 1A. However, the voltage drop
on this diode is large, reaching 1.1 Volts, which can bring undesirable effects
such as increased thermal dissipation, causing loss of efficiency. In this case, a
Schottky diode would be more appropriate because the voltage drop on it is
smaller.

Most other versions of Arduino do not specify which diode model was used.
Also, some versions like Nano do not have this polarity reversal protection.
There are still other versions like Leonardo and Arduino Micro that use other
components, or the same diode connected differently. Download the designs of
these boards and try to compare the differences in circuits.

5V regulator
The next component of the circuit that we will look at is the 5 Volt regulator
named U1. Its function is to lower the source voltage (which can have a value
between 7 and 20 Volts) and stabilize it at 5 Volts, which is the recommended
voltage for the operation of Arduino components, such as the two processors. In
addition, the regulator also acts as a filter, attenuating any noise that may be
present in the voltage generated by the power supply.

This regulator is called a linear regulator, and the means it uses to lower the
supply voltage is simply to dissipate excess power., throwing it away as heat.
For this reason, it has low efficiency and usually gets very hot in some cases. If
you power your Arduino with a 12 Volt source, for example, you will only be
using 40% of the power supplied by the source, the other 60% being thrown
away as heat. This happens with any linear regulator, regardless of manufacturer
and model. So don't be alarmed if this component starts to heat up when you use
Arduino with an external source as it is there for that. If the board is well
designed, the temperature will be within limits tolerated by the component (but
will probably be above the limit tolerated by your finger, so be careful).

The more the voltage from the external source increases, the less efficient the
operation of the linear regulator becomes. Using a 20V power source, for
example, only 25% of the energy is harnessed, with 75% being thrown away as
heat. So, whenever possible, use small power supplies such as 9 or 7.5 Volts, for
example.

In Arduino UNO, the component used for the 5 Volt regulator is the NCP1117
manufactured by ON Semiconductor, and it uses two capacitors to assist you in
this task, PC1 and PC2, both 47uF. These capacitors are important for the proper
functioning of the regulator. PC1 helps to stabilize the input voltage from the
power supply, and also provides the power to supply any power surges that
occur while using the card. The capacitor PC2 has the same stabilizing role but
in the output voltage. Also, this capacitor still plays an important role in
regulator stability and should be chosen carefully according to the
manufacturer's instructions for capacitance and series resistance (this is a
parasitic resistance that every capacitor has, it is called ESR). or "

Despite the low efficiency, virtually all versions of Arduino use a linear
regulator because they are easy to use, inexpensive and reliable. Some models
use the same NCP1117; other versions use different chips. Arduino
Duemilanove uses, for example, MC33269D-5.0, while Arduino Nano uses
UA78M05. However, the function and operation are always similar. There are
still other versions, such as Arduino Due, which does not use a linear regulator
to generate the 5 Volt voltage (download the schematic from the Arduino
website and try to find out the differences. Tip: the IC used is IC2, model
LM2734Y).

3.3 Volt Regulator


The Arduino UNO also has a second regulator, which lowers the 5 Volt voltage
from the U1 regulator to a 3.3 Volt voltage. This component is named U2 and is
the LP2985 model originally manufactured by National Semiconductor (today
this company is part of Texas Instruments).

In the Arduino UNO design, the 3.3 Volt voltage is only used on component U5
(which is part of the circuit switching we will see later), on the other component
is powered by it. And why is this regulator present? Typically, the 3.3V voltage
is used by users to power other external circuits or shields that use this voltage.
Especially the most modern electronic circuits are migrating from the classic
voltage of 5 volts to 3.3 volts, is very common today in many devices. This is
why it is useful to have this feature available in Arduino.

The implementation of regulator U2 is similar to that of U1. The input capacitor,


in this case, is the 100 nano Farad C2, and the output capacitor is the 1 micro
Farad C3 (see on the Arduino board that the capacitor C2 is located very far
from the U2 regulator, which is not recommended in this case).

Some Arduino versions that use the FT232 chip for the USB-serial converter
function, such as Duemilanove, Nano, and MEGA, do not have a second
regulator to generate the 3.3V voltage. In this case, it comes from an internal
regulator present on the FT232 chip itself. Although the current capacity is
reduced (50 milliamperes), it is sufficient for the vast majority of cases.

Switching Circuit
As we have seen before, Arduino can be powered either from an external power
supply or directly from the PC's USB port. In cases where Arduino is connected
to the USB port, and there is still an external source connected to it, there would
be a conflict between them as both would try to power Arduino at the same time.
This could cause damage to the power supply, the PC's USB port, and also the
Arduino.

The switching circuit has the function of resolving this conflict. It disconnects
power from the USB port whenever a power supply is connected to the Arduino.
We can then say that the external source will always have a preference to feed
the set. This process is transparent to the user, so you can connect and disconnect
the power supply even when the card is running (assuming USB has the power
to power the entire set).

The components responsible for this function are resistors RN1A, RN1B,
transistor T1 and chip U5.

Let's start by explaining how the T1 transistor works (the model is the FDN340P
manufactured by Fairchild Semiconductor). Since a complete understanding of
this component involves more complex concepts such as silicon doping and PN
junctions, let's try to abstract a little, and show it more practically.

Transistor T1 is part of a family of transistors known as MOSFET (in this case,


it is a P-channel MOSFET). A MOSFET is a device that has three terminals, one
of which is the command terminal (called a gate), and the other two are current-
carrying terminals (called drain and source, respectively). Its operation can be
described as that of an on and off switch. This way it lets it pass, or cuts the
current through the drain and source terminals depending on the command that is
sent to it. Briefly, we can say that:

The MOSFET remains off (cutting current between the drain and source
terminals) as long as the voltage at its control terminal is at a high logic level.

The MOSFET stays on (letting current flow between the drain and source
terminals) as long as the voltage at its control terminal is at a low logic level.

Sending the command to turn transistor T1 on and off is component U5. This
component is an operational amp (op-amp). The op-amp is one of the most
versatile components in existence, and it is widely used in analog electronic
projects, making it possible to make oscillators, filters, buffers, adders, and a
host of other applications. However, on the Arduino UNO switching circuit, the
op-amp is used as a comparator, and this is how we will analyze it.

The component used is the LMV358, manufactured by several companies like


Texas, On Semiconductor, ST, etc ...

A comparator has 2 input terminals, which are called - and +, plus an output
terminal. Its function is to compare the voltage present at the terminals - and +,
indicating through the output terminal logic level, which of these voltages is the
highest. The operation can be described as:

The voltage at the output terminal remains at a high logical level, while the
voltage at the terminal + is greater than - terminal voltage.

The voltage at the output terminal remains low logic, while the voltage at the +
terminal is less than - terminal voltage.

Let's go back to the schematic now. In it, we can see that the voltage present in
the - terminal is the 3.3V voltage itself generated on the U2 regulator. Already
the voltage present in the + terminal is the voltage VIN from the external source
after passing through the resistive divider formed by resistors RN1A and RN1B.
Since both resistors have equal values (10 kilo Ohms in this case), they form a
divisor by two, so that the voltage present at the + terminal of the comparator is
half the voltage VIN (in fact one would also have to discount the voltage drop
over diode D1, but let's ignore that because its influence is low).

When there is only a USB voltage present, VIN is zero since no external source
is connected. In this situation, the voltage at the terminal + is less than - terminal
voltage, making the comparator output remain at a low logical level. This low
logic level is sent directly to the MOSFET command terminal, causing it to turn
on and conduct current from the USB port. This allows it to power the entire
circuit (in the schematic, the current coming from USB comes from the signal
called USB VCC that originates right after passing through fuse F1, remember
that signals with the same name are always connected to each other, even if there
is no physical connection in the schematic).

However, when a 12 Volt power supply, for example, is connected to the


Arduino, there will be a 6 Volt voltage present in the + terminal of the
comparator (remember the resistive divisor by two). In this situation, the voltage
at the + terminal is greater than - terminal voltage (which is always 3.3V), which
makes the comparator output stay at a high logical level. This high logic level is
sent directly to the MOSFET command terminal, causing it to shut down and
prevent USB current from passing through it, effectively disconnecting power
from the USB port. Therefore the current from the external source becomes
preferred, and it is the one that feeds the Arduino.

Since the source voltage is always divided by two at the comparator input, the
minimum value required for it to be able to turn off the MOSFET is 6.6 Volts.
This value is below the recommended minimum limit for external source
Arduino power (which is 7 Volts), so the external source will always have a
preference.

Still, another component is present in the switching circuit, which is the Farad
100 nano C1 capacitor. In the schematic, it is connected to two "loose" pins just
above the U5A comparator, but these pins are part of the same U5 component.

The C1 is connected to the power pins of the op-op is our well-known


decoupling capacitor (see USB Processor section "for more details).

LED D13
The next circuit we will look at is the Arduino D13 pin LED, which is named L
in the schematic. This is the LED that flashes when we run the Blink example.
Actually, this circuit is not part of the power circuit, but we inserted it in this
section because it shares the same U5 component of the switching circuit.

This LED has a 1 kilo Ohm RN2A resistor connected in series with it to limit its
current, and they are connected directly to the output of another amp op.
However, although there are two amp-ops in the schematic (U5A and U5B),
both are inserted into the same package, i.e. they are part of the same
component.

LED Powered by Arduino Pin D13


We have then the + terminal the op-amp is connected to the SCK signal, which
comes from the Arduino pin D13, and it is this signal that will make the LED
actuate. The – terminal op-amp is connected directly to the output. This amp-op
mount is called a voltage follower or buffer. In practice, it does not perform any
logic functions as the LED lights up every time there is a high level on pin 13
and goes out every time there is a low logic level. Effectively it is as if the LED
were connected directly to this pin.

But then why use the amp-op to trigger the LED?

The op-amp was used because pin D13 does not have the exclusive function of
turning the LED on and off. It is also, for example, the SPI communication clock
pin (SCK). If the LED were turned on directly, it would drain from pin D13 an
approximate current of 3 milliamps while it was on, adding an extra charge. This
could influence and impair the use of the D13 pin in other applications.
The op-amp, in turn, has a high impedance on its input pins. This means that the
current consumed by them is very small (around 250 nanoamps). This way, it
virtually adds no extra charge to the Arduino D13 pin, eliminating the influence
of the LED. All in all, you drain from the pin a current of only 250 nanoamps to
drive a load of 3 milliamps (12000 times less).

Op-amp is not the only circuit that can be used for this purpose; it is also
possible to use buffers or transistors. Another option is to use high brightness
LEDs, which are more efficient. This increases the resistor value, reducing the
load on the pin, which makes the influence of the LED negligible.

The Arduino Nano does not use this circuit - LED goes directly on the processor
pin.

LED ON

Power Indicator LED

This is the last block we need to analyze, and it is also the simplest. This is the
LED that always stays on while Arduino is on, it is named in the schematic as
ON.

The circuit has two resistors, RN4C and RN4D, both 1 kilo Ohms and connected
in parallel. Effectively they work as a single 500 Ohm resistor and have the role
of limiting the current in the LED.

Fiducials
The most attentive may say that there are still missing components to be
explained. They are the three circles that appear loose just beside the POWER
connector on the original schematic. The figure below shows where they are.

Location of the three circles.


Well, these are not components themselves. They represent some markings on
the board and are called fiducial points. These points serve as reference points
for machines that automatically assemble components at the Arduino factory,
thus achieving better alignment.

In the project published by the Arduino team, there are 3 fiducial points, and
they are located below the source input jack, reset button, and ATmega328. This
way, you can no longer see them after the components are assembled.

We find another version of Arduino UNO, with the ATmega328 processor in


SMD encapsulation, where you can see two fiducial points. They are highlighted
in the image below.
Fiducial Point Examples
We have reached at the end of this chapter and wish your enjoyment throughout
the next chapters of the book.
Chapter 6
The LCD Display Function
In this chapter, you will learn:
Introduction to LCD Displays
How LCD Display Works
LCD pinout
I2C Interface for LCD Displays
The LCD display with Arduino (4-bit bus)
Creating Special Characters for the LCD Display
LCD Display with Arduino (I2C Interface)
Introduction to LCD Displays
LCDs are very useful for those who want to use a microcontroller to develop an
application. They allow a simple and easy-to-use visual machine-to-machine
(HMI) visual interface. On the LCD, you can send text, numbers, symbols, and
even images that can indicate what the microcontroller is doing, the data that
may be being collected or transmitted, etc. For those who don't know, LCD
stands for English - Liquid Crystal Display- or liquid crystal display. A big
advantage of LCDs is that they don't need much power to operate. Remember,
digital LCD clocks decades ago? The batteries could last months and even a
year. But the LCDs we're talking about have LEDs behind them so they can be
used in low or no light environments. These LEDs spend a little more. But if you
were to use only LCDs, the power consumption would be very low!

The monitors of the early laptops of the 1980s used the same LCD technology!
And without LED lighting.

In the early days of Digital TVs, this LCD technology was also widely used.
There are currently other technologies that reproduce images much more
faithfully.
The LCD market is always innovating, and today we have color displays: blue,
red, green, etc., that is, for all tastes. This Guide will always reference blue
LCDs. But be aware that everyone has the same principle of operation. What
changes only is the color of the LED that illuminates it.

For the use of microcontrollers such as Arduino, the most common LCDs are 16
× 2 (16 characters x 2 lines) or 20 × 4 (20 characters x 4 lines).
16 × 2 blue LCD
16 × 2 green LCD
20 × 4 blue LCD with I2C
20 × 4 green LCD

How LCD Display Works


When they were created decades ago, they were not luminous. They simply let
in the light or obstructed it, leaving shadows. The dial is formed of two
transparent acrylic plates. Among these plates is liquid crystal. This liquid
crystal alters its crystalline behavior, depending on the tension applied between
it. The displays, as you can see, are made up of various dots. Each dot may be
light or dark, depending on the polarization of the electricity. Under the
transparent plates, there is an invisible array of connections that control all these
dots. Who does this is the controller chips behind the display.

The most widely used LCD controller chip in the world today is one that was
developed by Hitachi - the HD44780, a long time ago. He is so good; he has
become a standard. If you want to deepen your study of LCDs by learning how
to use all the many features available, I recommend reading the datasheet.

Datasheet HD44780
Communication between the LCD Controller and the Microcontroller (for
example, Arduino) can be parallel (4 or 8 bits) or serial (I2C). For a limited
number of digital ports, we recommend using the I2C interface.

As a curiosity, be aware that this chip has an internal ROM where some
characters and symbols are already engraved. And for you to generate your own
symbols, there is an internal RAM. Very versatile!

Here's a part of the internally recorded Character Table - each character is made
up of a 5 x 8 dot matrix:

LCD pinout

16 × 2 blue LCD display


This is a very detailed Datasheet of a 16 × 2 LCD Display. Note that it uses
HD44780 compatible controller chips:

16 × 2 LCD Datasheet
At the top of the display are 16 holes where pins or cables for communication
and power can be soldered. Caution: Incorrect connection or use of voltages
above 5V may damage the display.
NOTE: The 16 × 2 LCD pinout is identical to the 20 × 4 LCD!

Pinout and Function of each Pin

pin 1 - VSS - Power pin (zero volts - GND)

pin 2 - VDD - + 5V power pin


pin 3 - VO - LCD contrast adjustment pin - depends on applied
voltage (adjustable)

pin 4 - RS - Command Selection (level 0) or Data (level 1)

pin 5 - R / W - Read (level 1) / Write (level - 0)

pin 6 - E - Enable (Enables display with level 1 or Disables with


level 0)

pin 7 - D0 - data bit 0 (used on 8-bit interface)

pin 8 - D1 - data bit 1 (used on 8-bit interface)

pin 9 - D2 - data bit 2 (used on 8-bit interface)

pin 10 - D3 - data bit 3 (used on 8-bit interface)

pin 11 - D4 - data bit 4 (used on 4 and 8-bit interface)

pin 12 - D5 - data bit 5 (used on 4 and 8-bit interface)

pin 13 - D6 - data bit 6 (used on 4 and 8-bit interface)


pin 14 - D7 - data bit 7 (used on 4 and 8-bit interface)

pin 15 - A - LED Illumination Anode (+ 5V DC)

pin 16 - K - LED Illumination Cathode (GND)

LCD illumination is done by LED. Pin 15 (LED Anode) can be connected


directly to +5 V, and pin 16 (LED Cathode) must be connected to ground
(GND). This way, the LED will consume approximately 22 mA. The total
current draw (LCD + LED) of the 16 × 2 Blue LCD is approximately 23 mA.

If you want to consume less current, use a series resistor, for example, 220 ohms
(7.6 mA consumption).

For LCD contrast adjustment, the voltage on pin 3 (VO) must be adjusted. Use a
20K ohm potentiometer. At the ends of the POT connect + 5V and GND. Center
pin connect to LCD pin 3. On my blue 16 × 2 LCD, the VO voltage was
approximately 1.0 Volts.

I2C Interface for LCD Displays

When this type of LCD Display was developed, the microcontroller data buses
used 8 bits. In the Arduino era, the available digital ports are reduced. To
address this limitation, a specially dedicated I2C interface for LCDs has been
developed. The chip used in this module is the PCF8574. It is a parallel port
expander, has an I2C interface, and can control up to 8 bits either as input or
output (depending on configuration). I2C interface speed is limited to 100 kHz.
The supply voltage can be either 3.3V or 5V, which enables it for all common
microcontrollers.

This photo is the back of the LCD Display with the I2C Interface already
connected.
16 × 2 LCD with I2C Interface.

To connect with Arduino or another Micro-controller, only four pins are


required:
GND - Plug into Arduino Ground
VDC - connect to 5V power
SDA - Serial Data - I2C Interface
SCL - Serial Clock - I2C Interface

The Blue potentiometer on this interface is used for contrast adjustment. After
the display is energized and programmed, adjust it to make the image visible.
The LED jumper is used to activate the Backlight LED. If you do not want to
use the LED to save power, remove this jumper. The red LED on the board is an
indication that it is energized.

PCF8574 Addressing

On an I2C interface, communication is serial. To select a device, the address is


sent to the bus because on the same bus, you can have multiple devices.

The PCF8574 chip has some addresses already defined, depending on the model
(identify your module chip):

PCF8574 = 0x20H

PCF8574A = 0x38H
In addition to the basic address, through 3 address pins (A0, A1, and A2), the
addressing can be changed, as in the case of using more than one chip on the
same bus. See on the module jumpers A0, A1 and A2.

One more very important detail! For the I2C interface to function properly,
PULL UP resistors must be used on both lines (SCL and SDA). These resistors
connect these lines to the VCC. In this I2C module, these PULL-UP resistors
(4.7 K ohms) already exist. So do not add any more resistors on the interface.

The LCD Display with Arduino (4-bit bus)


As I said, the LCD Display can be connected to the Arduino via a Parallel or
Serial bus (using the I2C module).

In the case of a parallel bus for Arduino, only 4 data bits are used. But for
control lines, more ports are needed (RS, R / W, and ENABLE). Adding a total
of 7 doors! This type of communication should be avoided if there is no number
of ports available for the application.

This is the Fritzing circuit diagram for testing the 16 × 2 LCD Display with
Arduino Nano:
And this is the electronic diagram of the same circuit - Arduino Nano with 16 ×
2 LCD:

Note that pin 5 (R / W) is grounded (level zero). Therefore the display can only
receive data (write)

To position characters on display, there is this row and column addressing. See
that the count starts from 0 and not from 1 (Row 0, column 0)! The differences
from a 16 × 2 display to a 20 × 4 display are the number of characters and the
addressing. All commands are identical for both types of displays.

In this assembly, we will use the Liquid Crystal Library, so it must be installed
using the procedure below.

Installing a New Library in Arduino IDE

To install the new Library, click Sketch> Add Library> Manage Libraries.

After opening the Library Manager window, refine the search by entering the
library name. In the selected library, click More Info and then Install. After a
few seconds, it will be automatically installed. Remember that your computer
needs to be connected to the internet. After installing the library, you must close
and reopen the Arduino IDE program.

Using examples from the Liquid Crystal Library, I did this Sketch to test
various Display functions:

print message
flash message
cursor test
message scroll test
message direction test
To configure Display Type:
lcd.begin (16.2); // setting the LCD - 16 columns and 2 rows
lcd.begin (20,4); // setting the LCD - 20 columns and 4 rows

LCD Test Program

/ * LCD Test Program


ABC Blog - http://blog.abc.com/xyz/
Arduino Nano - 16/2 Blue LCD - IDE 1.8.5
Alex Nulsen April 11, 2018
LiquidCrystal Library https://github.com/arduino-libraries/LiquidCrystal
* /
#include <LiquidCrystal.h> // Using the LiquidCrystal Library
const int rs = 8, en = 9, d4 = 4, d5 = 5, d6 = 6, d7 = 7; // display pin definition
LiquidCrystal lcd (rs, en, d4, d5, d6, d7); // setting the pins
int thisChar = 0;
void setup ()
{
lcd.begin (16.2); // setting the LCD - 16 columns and 2 rows
}
void Hello () // printing message
{
lcd.setCursor (0.0); // selecting column 0 and row 0
lcd.print ("ELETROGATE Blog"); // print of message
lcd.setCursor (2,1); // selecting column 2 and row 1
lcd.print ("LCD Guide"); // Print of message
delay (1000); // 1 second delay
}
void Flash ()
{
lcd.noDisplay (); // turn off display
delay (1000); // half a second delay
lcd.display (); // turn on display
delay (1000); // half a second delay
lcd.clear (); // clear the screen
delay (1000); // 1 second delay
}
void Blink () // cursor test
{
lcd.noBlink (); // delete cursor
delay (1000); // 1 second delay
lcd.blink (); // light cursor
delay (1000); // 1 second delay
lcd.clear (); // clear the screen
delay (1000); // 1 second delay
}
void AutoScroll () // message scroll test
{
lcd.setCursor (16,1); // selecting column 16 and row 1
lcd.autoscroll (); // set automatic message scrolling
for (thisChar = 0; thisChar <10; thisChar ++) // print from 0 to 9
{
lcd.print (thisChar); // print the number
delay (350); // 350 ms delay
}
lcd.noAutoscroll (); // turn off auto-scroll
lcd.clear (); // clear the screen
delay (1000); // 1 second delay
}
void dirText () // message direction test
{
lcd.clear (); // clear the screen
lcd.cursor (); // turn on the cursor
lcd.setCursor (10,0); // selecting column 10 and row 1
for (thisChar = 1; thisChar <10; thisChar ++) // print from 1 to 9
{
lcd.rightToLeft (); // print from right to left
lcd.print (thisChar); // print the number
delay (350); // 350 ms delay
}
for (thisChar = 1; thisChar <10; thisChar ++) // print from 1 to 9
{
lcd.leftToRight (); // print from left to right
lcd.print (thisChar); // print the number
delay (350); // 350 ms delay
}
lcd.noCursor (); // turn off the cursor
}
void loop ()
{
Hello (); // printing message
Flash (); // flashing message
Blink (); // cursor test
AutoScroll (); // message scroll test
dirText (); // message direction test
delay (1000); // 1 second delay
}

Creating Special Characters for the LCD Display

Another great feature of the Liquid Crystal Library: create special characters!
This library has a method that allows, by controlling the 5 × 8 matrix points of
each LCD character, the creation of any symbol or special character. Use the
Link Character Generator below to create Sketch code. To draw, click on the 5 ×
8 matrix points. Copy the generated code and insert it into Sketch.

Special character and symbol generator

LCD16x2_Arduino_Caracter:

/ * LCD Character Generator Program


ABC Blog - http://blog.abc.com/xyz/
Arduino Nano - 16/2 Blue LCD - IDE 1.8.5
Alex Nulsen April 12, 2018
LiquidCrystal Library https://github.com/arduino-libraries/LiquidCrystal
* /
#include <LiquidCrystal.h> // Using the LiquidCrystal Library
const int rs = 8, en = 9, d4 = 4, d5 = 5, d6 = 6, d7 = 7; // display pin definition
LiquidCrystal lcd (rs, en, d4, d5, d6, d7); // setting the pins
byte customChar [8] = // Special Character Matrix
{
0b00000,
0b11011,
0b11011,
0b00100,
0b00100,
0b10001,
0b01110,
0b00000
};
void setup () // up to 8 special characters can be created
{
lcd.clear (); // clear the screen
lcd.createChar (1, customChar); // creating special character 1
lcd.begin (16.2); // setting the LCD - 16 columns and 2 rows
lcd.write ((byte) 1); // printing the special character 1
}
void loop ()
{
}

I found on Youtube, this application also very interesting to use large numbers
on the 16 × 2 LCD Display.

Big Crystal Library

The Liquid Crystal library is very versatile! Allows the use of various interface
types:

4-bit parallel interface

I2C Serial Interface

SPI interface

As a reference for reference, this is the link to use the SPI interface (little used):
LCD16x2 with SPI Interface – ARDUINO

LCD Display with Arduino (I2C Interface)

As I mentioned earlier, there is an I2C Interface module specially designed for


the use of LCD Displays. The big advantage is the reduced number of ports used
on Arduino - only two - SCL and SDA.

Arduino - Wire / I2C Library

I2C Port Connections (for Arduino):

SCL port = pin A5

SDA port = A4 pin

Do not forget to connect the GND of the I2C interface in GND Arduino. Same
for 5V. The current draw measured by me was 27.5 mA. Make the adjustment
of the contrast using the pot I2C interface.

This is the Fritzing circuit diagram for testing the 16 × 2 LCD Display (I2C
Interface) with Arduino Nano:

This is the electronic diagram of the same circuit - 16 × 2 LCD Display (I2C
Interface) with Arduino Nano:
I2C Scanner
The first test to be done is to identify the interface I2C address. Run Sketch I2C
Scanner. In my assembly, the address found was:

I2C scanner. Searching…

I2C Address found: 63 (0x3F) - This address should be entered in Test Sketch

Found 1 device (s).

I2C Scanner

// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011
#include <Wire.h>
void setup ()
{
Serial.Begin (9600);
// while (! Serial)
{
}
Serial.println ();
Serial.println ("I2C scanner. Searching ...");
byte count = 0;
Wire.begin ();
for (byte i = 8; i <120; i ++)
{
Wire.beginTransmission (i);
if (Wire.endTransmission () == 0)
{
Serial.print ("I2C Address Found:");
Serial.print (i, DEC);
Serial.print ("(0x");
Serial.print (i, HEX);
Serial.println (")");
count ++;
delay (1);
}
}
Serial.print ("Found");
Serial.print (count, DEC);
Serial.println ("device (s).");
}

void loop () {}

This is the Liquid Crystal I2C Library used in this test assembly (install it using
the procedure above):

Liquid Crystal I2C Library

Using the Liquid Crystal I2C Library, I created the program to test the same
functions as the previous example (4-bit interface):

print message
flash message
cursor test
message scroll test
message direction test

LCD Test Program

/ * LCD Test Program - Interafce I2C


ABC Blog - http://blog.abc.com/xyz/
Arduino Nano - 16/2 Blue LCD - IDE 1.8.5
Alex Nulsen April 13, 2018
LiquidCrystal Library
https://github.com/marcoschwartz/LiquidCrystal_I2C
* /
#include <Wire.h> // using the Wire library
#include <LiquidCrystal_I2C.h> // using the LiquidCrystal I2C library
LiquidCrystal_I2C lcd (0x3F, 16, 2); // Set up I2C address and 16 character, 2
line display
int thisChar = 0;
void setup ()
{
lcd.init (); // initialize LCD
lcd.backlight (); // enable backlight led
}
void Hello () // printing message
{
lcd.setCursor (0.0); // selecting column 0 and row 0
lcd.print ("ELETROGATE Blog"); // print of message
lcd.setCursor (2,1); // selecting column 2 and row 1
lcd.print ("LCD Guide"); // Print of message
delay (1000); // 1 second delay
}
void Flash ()
{
lcd.noDisplay (); // turn off display
delay (1000); // half a second delay
lcd.display (); // turn on display
delay (1000); // half a second delay
lcd.clear (); // clear the screen
delay (1000); // 1 second delay
}
void Blink () // cursor test
{
lcd.noBlink (); // delete cursor
delay (1000); // 1 second delay
lcd.blink (); // light cursor
delay (1000); // 1 second delay
lcd.clear (); // clear the screen
delay (1000); // 1 second delay
}
void AutoScroll () // message scroll test
{
lcd.setCursor (16,1); // selecting column 16 and row 1
lcd.autoscroll (); // set automatic message scrolling
for (thisChar = 0; thisChar <10; thisChar ++) // print from 0 to 9
{
lcd.print (thisChar); // print the number
delay (350); // 350 ms delay
}
lcd.noAutoscroll (); // turn off auto-scroll
lcd.clear (); // clear the screen
delay (1000); // 1 second delay
}
void dirText () // message direction test
{
lcd.clear (); // clear the screen
lcd.cursor (); // turn on the cursor
lcd.setCursor (10,0); // selecting column 10 and row 1
for (thisChar = 1; thisChar <10; thisChar ++) // print from 1 to 9
{
lcd.rightToLeft (); // print from right to left
lcd.print (thisChar); // print the number
delay (350); // 350 ms delay
}
for (thisChar = 1; thisChar <10; thisChar ++) // print from 1 to 9
{
lcd.leftToRight (); // print from left to right
lcd.print (thisChar); // print the number
delay (350); // 350 ms delay
}
lcd.noCursor (); // turn off the cursor
}
void loop ()
{
Hello (); // printing message
Flash (); // flashing message
Blink (); // cursor test
AutoScroll (); // message scroll test
dirText (); // message direction test
delay (1000); // 1 second delay
Conclusion
Have you thought about having a tech-house? One that can offer all the
possibilities of Arduino home automation that the market offers? Well, unless
you are Iron Man and enlisted by the help of JARVIS (Iron Man computer), this
will not be entirely possible at the moment, but with the help of our smart little
superhero ARDUINO, you will be able to reproduce many things in your home
that you only see in movies.

To conclude this book, we will present 5 Arduino project ideas that you can
employ on your home premises, allowing the home automation world to invade
every room, controlling and monitoring your safety and day-to-day tasks. Do
everything, right!).

This great little microcontroller, which is responsible for the different


possibilities of the projects presented below.

If you have your Arduino, then it's time to get it off the shelf and dust it off to
get it to work (we're all guilty of it sometimes, don't you think?). Let's add some
modules, sensors, a little of our time, and achieve extraordinary feats.

Ready !? Fasten your seat belts and come on!

1- Arduino Design Lighting Control by Cellphone


One of the most coveted projects for technology lovers is Arduino home
automation, where you can, through apps, run the house as a whole, letting you
open and close motorized curtains and windows, turn televisions on and off at
preset times, run fans and everything else you think of, right on your phone,
tablet or computer.

Great things in automation can be done by adding an Ethernet Shield to the


Arduino, allowing you to turn the small microcontroller into an Internet-capable
device that can change the state of lights, TVs, coffee machines - just about
anything you can think of - on and off using a browser-based interface or a
timer.
Have you thought, for example, about waking up in the morning and the coffee
being ready, your TV on and tuned to your favorite channel, because in the
Arduino world, everything possible is just a matter of having the necessary
accessories and making the right programming.

There is not much secret in the items needed for this; you will basically need 1
Arduino, 1 Ethernet Shield or 1 Wifi Module, 1 Relay Module, LEDs and
jumpers. You can also give these commands directly from your smartphone via
Bluetooth.

2 - Arduino Design RFID Access Control


How about replacing the old key with an RFID tag to access your home? With
an Arduino and an RFID Kit, you and your family members can open doors
quickly, simply and very safely, simply by swiping the card in front of the RFID
reader to release the electronic door lock or lock.

RFID technology uses radio waves for communication and data transfer, where a
unique numbered tag (code) is embedded in a card or key chain, for example,
and when passing the encoded object in front of the reader, it will receive
information from the cardholder, where permitted, will release the door lock
giving access to the room.

The registration of the cards or tags that will be previously allowed to pass is
configured and saved directly in Arduino, which is responsible for comparing
the information, as well as managing the reading and command procedure for
opening the door by activating a relay, which consequently will release the
electric lock.

Of course, it is not enough to connect the Arduino and RFID reader for you to be
able to carry out this project, it is necessary that the door has previously some
kind of electric lock, which will be interconnected to the programming set,
executing the received commands.

For execution, you will need 1 Arduino, 1 RC522 RFID Kit (which includes
RFID Reader and two tags, one in keychain format and one in card format), 1
relay module, 1 16 × 2 display, 1 lock or electric lock and jumpers.
This type of home automation is not limited to door use but can be applied to
gates, drawers, cabinets, and anything else you can imagine, just use creativity
and put it into practice. For more details on this project, go to the “Arduino
RFID Access Control Project.”
3 - Intelligent Security Alarm Design with Arduino
For those looking for extra protection and not wanting to afford the high
purchase and monthly payment costs of modern and sophisticated alarm
systems, the little Arduino can be a great option, delivering great results and a
relatively low cost.

Technology has benefited many homeowners concerned about the security of


their property, with a growing number of PC-based security systems, the values
have become increasingly significant and even hurt in the pocket of those not so
prepared to cover that extra expense.

The Arduino can help automate the home security, providing a compact solution
(bringing together all in one device) to control PIR motion sensors, magnetic
sensors, sirens, cameras, electric locks, signaling lights and more, and this with
activation and deactivation controlled by safe codes handled directly on numeric
keypads.

The type of residence, the number of rooms and the security profile you are
looking for will define which sensors and modules to use, where you can employ
PIR motion sensors to detect movements based on the variation of infrared light
emitted by human body radiation, firing a siren if so, for example.

If you are using a large number of sensors, you may need to use an Arduino
Mega, which has many more ports to connect than Arduino Uno, which may
provide greater possibilities, emphasizing that in both cases, the operation will
be the same mode.
4 - Arduino Irrigation Project - Autonomous Greenhouse
Now the excuse is gone: "Puts, I forgot." Anyone who has a garden or
greenhouse knows that they should water regularly. You may love flowers or
have salads and vegetables in the greenhouse that you are eager to eat, but
watering can be a challenge, especially if you are traveling or going out at night
(this is because you should avoid watering during the day because water in
conjunction with the scorching sun can burn the leaves).

So what now? Shouldn't I plant anything else? Calmly, the solution is Arduino
home automation, where once again, it saves the day, allowing your garden to
keep itself watered with the help of specially developed sensors.

Using specialized soil temperature and humidity sensors, Arduino can detect
when plants need to be watered and trigger a solenoid valve or water pump, for
example by meeting the need for plants housed in that particular location,
because it will be able to Set when the land is dry and when it is wet (Real-
time!), presented better results than those in which a person manages.

And what will I need? Some similar items already used so far and some specials,
requiring 1 Arduino, 1 water pump or solenoid valve, 1 relay module, 1 Soil
Moisture Sensor and Jumpers, and of course, that specific location type
programming you want to automate, allowing you to stay alone. So now, this
daily watering commitment is no longer yours. For more details, go to the
“Arduino Automatic Irrigation Project.”

5 - Automatic Dog Feeder Design with Arduino


Pets are our partners in the house, whether cats or dogs, they need a lot of care
especially, especially balanced and nutritious nutrition at the right time. But how
do you control this if you work and stay away all day?

Excessive food is not good for the animal, the measure must be right and ruled
with defined intervals between meals, i.e. leaving the bowl overflowing with
food in the morning and forgetting for the rest of the day is not a good solution.

Nothing better than home automation with Arduino to break this deadlock and
proportionate a healthy habit that will influence your pet's health. You are
providing food at the right amount and at the right times.

I liked it, but how does it work? With a standalone feeder connected to the
Internet, you can send commands to Arduino to feed your dog or cat at the right
time or at scheduled times if using an RTC (Real Time Clock Module)
connected to the microcontroller system.

Efficient and simple, the feeder is fixed in a place already stocked with ration,
where a type of shovel stuck in an engine is responsible for dosing the amount of
food, which motor is driven by Arduino as previously scheduled, to serve more
or less, with a buzzer system to let the pet know it's time to eat.

For this automation, you will need 1 Arduino, 1 Relay Module, 1 Ethernet Shield
(if you want to connect to the internet) or 1 RTC (if you want to work at pre-
programmed times), 1 Motor, 1 Motor Driver, 1 Buzzer and Jumpers. Since here
everything is possible, you can replace any component with another, being mere
suggestions that may or may not be followed will depend on the will and
possibilities of who will do the installation and programming.

Finally, these 5 project ideas are just a few possibilities for starting home
automation with Arduino in your home and can be broadly extended due to a
large number of sensors and electronics modules currently in existence. Check
out every Arduino product line available on the website.

So which one are you going to do? Time to take Arduino off and put it to work.
More than ever, the electronic revolution is approaching; perhaps one day, we
may have a fully automated home, as intelligent as Iron Man's. While this day is
not enough, let's kick-start, because this decade will be the machines!
ARDUINO

Advanced Methods and Strategies of Using


Arduino
Ethan Thorpe
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 SDO, DO, SO
In
MISO Master In Slave SDI, DI, SI
Out
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 Bandwidth


Resistance (seconds) Rate (Hz) (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