100% found this document useful (5 votes)
147 views414 pages

Basic Course On Arduino, 2024

Uploaded by

Paco Lojo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (5 votes)
147 views414 pages

Basic Course On Arduino, 2024

Uploaded by

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

Index

INTRODUCTION - The STEM disciplines and the Be Maker Basic Course


Plan.
Warnings
Copyright Notes
Preparing our Electronics and Robotics Lab.
Installation of software on the PC
Configuring the Arduino IDE
Well begun is half done
What is Arduino
What is the Arduino IDE
What is a Library and how to add it to the IDE
LESSON 1 - Current, Voltage and Electrical Resistance.
Ohm's law.
What is an LED.
Project 1 - Turning on an LED
The Button: how it works and how to use it
Project 2 - The use of a push button to turn on an LED.
Curiosity: A bit of scientific history
What is a Breadboard.
Project 3 - Hello World
Arduino's digital PINs
Project 4 - Police cars with flashing lights
LESSON 2 - Insights into Electrical Resistance
How to read the value of a resistor
Resistors with 4 colored circles
Resistors with 5 colored circles
Trivia: What is a Physical Magnitude and Uncertainty in
Measurements
Project 5 - The Traffic Light with Arduino
Introduction to Coding
The sketch
Project 6 - The Stelliere
Analysis of the sketch: The Stelliere
Arduino Analog PINs
Project 7 - Ohmeter. Using Arduino to measure a
resistance
Sketch Analysis: Ohmeter with Arduino
LESSON 3 - Robotics with Arduino
The photoresistor or also called Light Sensor
Project 8 - Crepuscular Switch with Photoresistor
Sketch Analysis: Twilight Switch with Photoresistor
Curiosity: What is Light
Project 9 - Luxmeter with Arduino
Sketch Analysis: Luxmeter with Arduino
The PWM signal - Pulse Width Modulation
Relationship between Analog PINs and PWM Digital PINs
Project 10 - Night and Day with PWM Signal
Analysis of the Sketch: Night and Day with PWM signal
Project 11 - The Return of the Cylons
Analysis of the Sketch: Return of the Cylons
LESSON 4 - THE RGB LEDS
Project 12 - RGB LEDs with Arduino
CURIOSITY: Stars shine and change color.
Project 13 - Starlight
Analysis of the sketch: Starlight
Project 14 - Starlight 2
The Tilt Sensor or also called the Ball Tilt Sensor.
Project 15 - Making an Electronic Hourglass.
Analysis of the Sketch: The Electronic Hourglass
LESSON 5 - THE SOUND
CURIOSITY: What is sound?
Project 16 - The Teresa wasp and the active buzzer.
The Passive Buzzer
Project 17 - The passive buzzer and the Piano-Man.
Analysis of the Project 17 sketch - The passive buzzer and
the Piano-Man.
CURIOSITY: The Microphone and the Loudspeaker or
Acoustic Speaker.
Project 18 - What happens in that house? Let's use the
microphone.
LESSON 6 - THE ULTRASOUNDS
Curiosity: what is Speed?
HC-SR04 Ultrasonic Module. Obstacle Distance Detection
Project 19 - Detect the distance to an obstacle.
Analysis of Sketch: Project 19 - Obstacle Detection with
Ultrasonic Module.
CURIOSITY: What are Degrees of Freedom (DOF) and
Electric Drives.
The Servo Motor - Giving movement to things.
Project 20 - Controlling a Servo Motor SG-90
Analysis of the Sketch: Project 20 - Controlling a Servo
Motor.
Project 21 - Radar System Ultrasound
Project 22 - Ultrasonic Radar System with Processing
LESSON 7 - Active and Passive Components and Elements in Series and
in Parallel.
The Active and Passive Components.
Series and Parallel Connection of Components.
The Series and Parallel Connection of Resistors.
The Voltage Divider and the Potentiometer
The Voltage divider
The Potentiometer (for electronic applications it is called a
Trimmer).
Project 23 - The Use and Connection of the Potentiometer
Fun facts: what is Temperature and what is Humidity
LM35 Temperature Sensor
Project 24-Detect the temperature of a body.
Project 25 - Light thermometer.
Analysis of the Sketch: Project 25 - Luminous
Thermometer.
The DHT11 Environmental Temperature and Humidity
Sensing Sensor.
What is a Library and how to add it to the IDE
Project 26 - Ambient Temperature and Humidity.
Sketch Analysis: Project 26-Environmental Temperature
and Humidity.
LESSON 8 - Magnetism and the Magnetic Field.
Curiosity: The Hall Principle
Project 27 - Magnetic Field Presence Detection - KY003
Analysis of Sketch: Project 27 - Use of LED on board
Arduino.
Project 28 - Analog Detection of a Magnetic Field - KY035
Curiosity: The Metal Detector
Project 29 - Magnetic Detector with the Linear Magnetic
Hall Sensor KY024.
Analysis of the Sketch: Project 29 - Magnetic Detector.
LESSON 9 - The Display for Arduino
7-segment LED display.
Project 30 - Let's Make a Countdown.
Analysis of the sketch: Project 30: Let's make a
Countdown.
4-digit 7-segment LED display.
Project 31 - Seconds counter.
Project 32 - Counter of seconds and tenths of a second.
Analysis of the sketch: Project 32 - Chronometer with use
of the Library.
Project 33 - Potentiometer Value Display with 4 Digit
Display
Project 34 - Insight for the millis() function.
LED Matrix Display
Project 35 - HELLO WORLD IN MATRIX !
Analysis of the Sketch: Hello World in the Matrix
The LCD Display
Curiosity: how the LCD display works
Project 36 - HELLO WORLD WITH LCD DISPLAY.
Sketch Analysis: Hello World with LCD Display
LESSON 10 - Insight into Light: the Infrared
Infrared Sensor Module KY-032
Comparison of HCSR04 Ultrasonic Module and KY032
Infrared Module.
Project 37 - The use of KY032 Module with the EN PIN
disabled
Analysis of the Sketch: Project 37 - Form KY032.
Project 38 - The use of KY032 Module with the EN PIN
enabled
KY-033 Infrared Sensor Module - Line Tracking
Project 39 - The Use of KY033 Line Tracking Module.
Sketch Analysis: Project 39 - KY033 Line Tracking Module.
The Infrared Remote Control - IR Remote Controller
Project 40 - Decoding the IR signal of a remote control
Sketch Analysis: Project 40 - Decoding the IR signal of a
remote control.
Project 41 - Piloting Events with IR Remote Control
Analysis of Sketch: Project 41 - Piloting events with IR
Remote Control.
INTRODUCTION - The STEM disciplines and the
Be Maker Basic Course Plan.
The Be Maker Course that I wanted to create fits perfectly
into that new area of teaching that has been spreading
lately, especially internationally, and in Italy we are just at
the beginning. More and more resources are being invested
in this, which has now even become a path of study that
starts from elementary school up to the point where
students reach graduation. This new area, which
encompasses multiple disciplines, is called STEM and is also
the origin of the Logo I wanted to give to the New Course.

STEM is an acronym and stands for Science, Technology,


Engineering and Mathematics. This acronym, of course,
should be read in the broadest sense of its meaning, in fact,
although the basic subjects are scientific, in this
multidisciplinary area Art also quietly finds its place so
much so that, again internationally, the new acronym
STEAM has spread. Consequently, with the introduction of
Art, all those associated humanities disciplines are also
involved (History, Literature, Philosophy, etc...).
The Be Maker Course represents, trying my best, the
perfect synthesis of the new model of study, where all STEM
disciplines are involved and called upon in a homogeneous
and coordinated way. Obviously this is a first piece...
The Course has been divided into Modules, the first Module
which is the one we are about to begin, is the Basic Course.
With this Course the foundations are created to deal with
the subsequent Courses that will have more specialized
features.
The Basic Course Study Plan is rich and varied and is based
on four main science topics: ELECTRICITY, LIGHT, SOUND
and MAGNETISM.
All projects, which are also created for fun purposes (in fact,
if there is no fun there is no interest either), are nothing
more than educational applications of the theoretical parts
covered.
The minimum suggested age is 12, but it depends a lot on
the student's desire to learn new things. As for the
maximum age, there is no limit...in fact, the Course creates
the foundation of knowledge of the use of the development
platform.... what will then limit the implementation of the
projects, will only be the imagination and the desire to
engage in learning new things...so there is no upper age
limit for the students of the Course.
Warnings
Regarding safety aspects, since the projects are based on
very low voltage power supply delivered from the pc's usb
port or from supporting batteries or power supplies with
maximum 9V output, there are no particular electrical risks.
However, it should be pointed out that any short-circuits
caused during the exercise could produce damage to the
pc, furniture and in extreme cases even burns, for this
reason whenever a circuit is assembled, or modifications
are made on it, it will be necessary to do so in the absence
of power supply and at the end of the exercise it will be
necessary to disconnect the circuit by removing both the
usb cable connecting to the pc and any batteries from the
appropriate compartments or external power connectors. In
addition, again for safety reasons, it is strongly
recommended to carry out the projects on insulating and
heat-resistant mats that can be purchased in any
electronics store or even on specialized websites.
At the end of the drills, hands should be washed, as
electronic components may have processing residues that
could cause harm if ingested or if in contact with eyes,
mouth, skin, etc. Although the individual projects have been
tested and safe, those who decide to follow what is stated
in this document assume full responsibility for what might
happen in the execution of the drills provided in it. For
younger and/or first-time students in the field of Electronics,
it is recommended that the exercises be performed with the
help and in the presence of an adult.

Copyright Notes
All trademarks shown belong to their rightful owners; third
party trademarks, product names, trade names, corporate
names and company names mentioned may be trademarks
of their respective owners or registered trademarks of other
companies and have been used for explanatory purposes
only and for the benefit of the owner, without any purpose
of infringement of the Copyright rights in force. What is
reported in this document is the property of Roberto
Francavilla, Italian and European copyright laws are
applicable to it - any texts taken from other sources are also
protected by Copyright and owned by their respective
Owners. All information and content (text, graphics and
images, etc.) reported are, to the best of my knowledge, in
the public domain. If, unintentionally, copyrighted or
infringing material has been posted please notify me by
email at info@bemaker.org and I will promptly remove it.
THE BOOK WAS TRANSLATED FROM ITALIAN INTO YOUR LANGUAGE BY
ARTIFICIAL ITELLIGENCE. THE TRANSLATION IN SOME PLACES MAY NOT
BE ACCURATE ESPECIALLY IN THE SOFTWARE CODE PARTS. FOR THIS
REASON AFTER EACH TUTORIAL THERE IS A LINK FROM WHICH TO
DOWNLOAD THE CORRECT SOFTWARE CODE. IN ADDITION THE BOOK IS
SOLD AT AN EXTREMELY LOW PRICE AND IN THE OFFERS IT IS EVEN
FREE. I HOPE YOU APPRECIATE THIS GESTURE OF MINE IN CHOOSING
MY BOOK ANYWAY, BECAUSE I AM SURE YOU WILL FIND IT, IN SPITE OF
EVERYTHING, VERY INTERESTING.
FOR ANY INFORMATION: info@bemaker.org

Roberto Francavilla
Preparing our Electronics and Robotics Lab.
As the first activity of the Course, we need to prepare our
Laboratory, and to do this we need to take all the materials
from our Starter Kit out of the packaging.
We check that all the materials that will be used in the
various projects are present:
We also need a PC (desktop or notebook is indifferent, but I
suggest with Windows 10 installation):
You also need to have a set of screwdrivers with magnetic
Phillips and flat heads (preferably different sizes):

and for the more daring a Digital Tester:

Installation of software on the PC


The entire Basic Course is based on the use of the Arduino
UNO R3 development board, Arduino is actually a true open
source platform, but it is also possible to use the many
compatible versions of development boards made by the
various manufacturers using the same platform.
We now turn to the software installations on our PC.
There are two pieces of software to be installed:
- The chipset driver of the USB communication port of the
development board.
- The "sketch" development environment called IDE
As for the driver, if it is not installed you will notice it right
away because when you first load the sketch (the program
you need to run Arduino), it will give you an error. Normally
the most popular development boards, even the compatible
ones, make the drivers available on the Internet, so just do
a search and download the driver and then run the
executable.
Since I cannot predict which boards you will buy, I will tell
you that for the original board the driver is already included
in the development environment, so no special
configuration is needed, while for the compatible boards,
the most common one (also because it is very cheap) is the
one that has the chipset in SMD format, and normally in this
case the driver to be installed is called CH341SER.zipper
It can be downloaded from the Internet, unpacked, and then
by running the executable, the driver will be installed.
We mentioned that our development board is based on the
open source Arduino platform, so we can use all the tools
that the platform provides.
Let's go to the Arduino website by typing the following
address into our browser or clicking on the following link:
https://www.arduino.cc
The initial window appears, we click on "SOFTWARE" :
then a page will be displayed where you can download the
latest version of the IDE.
Depending on which operating system you are using, on
your right side you need to choose the relevant DOWNLOAD
link [I suggest installing version 1.8.19, you can find it by
scrolling down the page at the bottom]:

As you can see from the picture on the web page above,
there are the different versions of the IDE for: Windows,
Mac, Linux,.
What is shown below is the procedure for Windows; for
other systems, the procedure is almost identical.

Two ways of installing the IDE are possible, the automatic


way by clicking on "Windows Win 7 and never" and the
manual way, where you first need to download the ZIP
package and then, once unpacked, you double-click on the
executable.
By clicking either option, the donation window appears in
both cases:
and in this regard, I strongly suggest, given the immense
amount of work that the Arduino guys do, to carry it out,
even a small amount.
In case you decide not to make the donation, you can
proceed with "JUST DOWNLOAD."
Once you have launched the installer (by double-clicking on
the .EXE executable file), following the prompts on the
screen via dialog boxes, you will proceed to complete
installation of both the IDE development environment and
the driver for the Arduino development board. The windows
that will appear to you will be:
If the following dialog box appears, you should choose
"Install."

When the installation process is complete, an icon will


appear on our Desktop:

We now connect the Development Board to the PC using


the USB cable that came with the board.
If all went well, the PC, after a few seconds (necessary for
driver installation), should be able to recognize the newly
connected peripheral.
It is possible to verify the correctness of the installation
process by going to the START windows window located at
the bottom left of the desktop:

Click on Device Management:


Look under Ports (COM and LPT) or other devices.
A yellow exclamation mark indicates that the driver
installation failed. In such a case, manual driver installation
is required.
Configuring the Arduino IDE
After installing the driver correctly, it is time to configure
the IDE, this is because the IDE can be used for different
devices, we, on the other hand, want to use it for our
Arduino or compatible Development Board.
For either the original or compatible Arduino Development
Board, you need to go to Tools ---> Board ----> and select
Arduino Uno (as shown below).
We then go on to select the correct COM port.
Once the Development Board is connected, go to Windows
START and right-click on it, then left-click on Device
Manager

Clicking on Ports (COM & LPT) shows which COM port the
device is connected to.
At this point we return to the Arduino IDE, go to Tools -- →
COM Ports and select the port to which our device is
connected.
So we have finished the most boring part, don't worry from
now on there will be lots of new things to learn and have
fun.
Well begun is half done
Our ambitious goal is to become Makers !
That is, implementers of our electronic and robotic projects,
and I am sure we will succeed.
The following lessons, based on practical projects, are set
up in such a way that theoretical topics are explained
several times, even on different practical projects. In this
way, even if a topic might at first be unclear or particularly
difficult to understand, don't worry.... GO AHEAD!!!
In fact you will surely find the same topic in another
application, perhaps easier to learn.... And so you will find
yourself saying.... ahh!...so that's how it works...that thing I
didn't understand at project # .......
Also I want to remind you that through the email you will
have the opportunity to get in touch with me, indeed I
would be happy to, so don't delay when you need
clarification, or even give me suggestions (which will always
be welcome) and also to elaborate on some topic that
needs clearer explanations....
Finally, since I do not want to bore you with all these
premises, the last message is about the methodology of
explaining the lectures; it is my intention to avoid using
technical terms except those that are strictly necessary and
to try to explain their meaning. Even for the theoretical
parts, I will try to avoid going into details of physics and
chemistry and will keep a suitable and congruous level of
explanation with school bases for children 12 years old and
up.
At this point we begin to learn about the tools we will use in
our Maker training.
What is Arduino
Arduino is a kind of small PC, it has a processor (a
microcontroller to be exact), memory (like the RAM and
Hard Disk of a PC), a motherboard, and connectors for
signal inputs and outputs that go to external peripherals
which can be sensors, actuator modules such as electric
motors, etc. There are different types of boards, depending
on certain features, for example, there are boards that
already have WiFi module built in, those that have GPS,
etc.. among the most popular is the Arduino UNO R.3, a
basic development board that can be integrated with any
type of module. Because the Arduino project is open source,
many other manufacturers have made their own UNO R.3
board:

Some manufacturers, seeing the potential of this board,


have also developed it further by adding features and
making it even easier to use.
So many projects can be made with this Maker
Development Board, the only limit is our imagination.
Using the supplied USB cable, it is possible to connect the
Development Board to the USB port of the PC from which
the board itself draws the power necessary for its operation
and interfaces with the PC to be programmed.
What is the Arduino IDE
First, let's start with the name: IDE which is an acronym and
stands for Integrated Development Environment i .e., a set
of applications that aggregates common development tools
into a single graphical user interface. The IDE is an
environment consisting essentially of:
- Editor: a text editor that facilitates the writing of
software code that is called a sketch. The programming
language used is based on C++.
- Monitor and Serial Plotter: where numeric variables
can be represented, or textual, but also graphically and is
also useful for debugger (searching for errors in sketches)
- Libraries: are a collection of functions and instructions
that simplify the use of certain devices (sensors, modules,
etc.)
Clicking on the Arduino icon opens the window below:
What
are the indicated icons?
A- It is used to verify written sketches by precompiling
it and detects any errors.
B- Load the sketch onto our Arduino board or Board.
C- It is a shortcut to create a new editor window for a
new sketch.
D- It is used to directly open an example sketch.
E- It is used to save the sketch.
F- Used to send data from the board to the serial monitor.

IMPORTANT: ALL PROJECTS SHOWN CAN BE


REPRODUCED WITH ANY ARDUINO UNO R.3
COMPATIBLE BOARD, INCLUDING THE ORIGINAL OF
COURSE !!!
What is a Library and how to add it to
the IDE
The Internet, as you well know.... even better than I!, is a
vast world where one can find anything. Even for the
Arduino world.... surely there has been someone, in the vast
global world, who has already solved technical problems
and made his knowledge available for humble mortals so
that they could improve (or even enhance what had been
created!) by making complicated things become simple to
understand and apply. Knowledge creators in the field of
electronics and robotics, are called... MAKERS!
(pronounced: meikers) and I hope that one day you will also
become one with my little help!
Well! The concept of a "Library" is basically this.... It is a
repository in which you find instructions that simplify and
make it easier to use things that would otherwise require
complex operations that are difficult to apply.
Let's take a practical example: the DHT11 sensor.
The DHT11 sensor is a device that, thanks to the amount of
water in the air or the ambient temperature, measures
changes in the electrical resistance of certain elements.
Basically, the DHT11 sensor is as if it were itself a mini
Arduino to which elements are connected whose resistance
varies according to the more or less presence of water in
the environment and its temperature.
This means that the sensor, already by itself, has a mini
computer (you can see it in the picture above) that would
already require software for its operation that would have to
be written before the actual software that we would have to
develop for its use.
Then the creator of this sensor has given us a gift!, he has
already developed all the software necessary for the
internal workings of the sensor and has created a LIBRARY
, that is, a set of simple instructions made available to us so
that the DHT11 sensor is already properly programmed to
return to us the values we need.
There are several ways to insert a library into the Arduino
IDE, the one we will use is the quickest and easiest, but be
aware that it will not always be possible to use this
method... but don't worry we will see them all when needed!
Back to us: inserting a new library into the Arduino IDE and
then allowing the IDE itself to load into Arduino the right
instructions needed for Arduino and the add-ons that
connect to it to work.
First we open the software, double-click on the Arduino icon
on the Desktop, and the IDE opens:
Since when you open the IDE it usually loads the last sketch
you wrote, let's start with a clean sketch to avoid confusion.
To do this, you click on "File" and then on "New."

as depicted above. At this point we can close the initial


window where the previous sketch was.
Now we click on "sketch" then on "#include library" and
then on "Manage libraries..."
After a few seconds, the following window appears and we
go to type in the text box "DHT11"
A list of libraries comes up, we select the one produced by
Adafruit...

...and click on "Install."


After a few seconds, the window that says "INSTALLED"
appears. The library is now usable and when compiling the
sketch for Arduino, the IDE will not give an error.
This procedure applies to any new sensor that requires a
library to be installed; all you need to do is change the
name of the sensor.

LESSON 1 - Current, Voltage and Electrical


Resistance.
Let's start with some theory, but don't worry I won't bore
you.
To give an intuitive explanation of what electric current and
electric voltage is and how it works, it is useful to think of
water. In fact, the current flowing in electric wires is quite
similar to a flow of water. The major difference between
current and water is that, while for water it is molecules (of
water) that flow in the pipes, in electric wires, it is electrons
(elements that make up the "atom"). Such flow of electrons
is called "electric current."
We can think of electrons as balls, and just as water can
drive water mills, electrons can also drive similar objects,
sort of electron mills. These mills, driven by electrons, can
produce light, noise, sound or motion!
So: current consists of electrons flowing in a wire and can
drive electrical components, which we can imagine as small
mills. Electric current is measured in "A" that is, in amperes
(it is read "amper" because it comes from French).
Let us now make the water analogy more specific, and think
of a waterfall arising from a reservoir (i.e., made by means
of a man-made dam). In a waterfall, water falls from the
highest point and falls to the lowest point (due to gravity),
where it collects, and there we suppose there is a system of
pumps that bring back up into the reservoir the water that
has just collected after falling from the waterfall. In this way
the water is ready to make a new cycle of falling from the
waterfall and rising through pumps. The highest point of the
waterfall is the one with a "higher potential" (conventionally
denoted by "+"), the lowest point is the one with a "lower
potential" (conventionally denoted by "-"). So water goes
from the + to the -, the same thing electric current
conventionally does, that is, it goes from the + (higher
potential point) to the " - " (lower potential point). This, in
electrotechnical terms, is called potential difference (ddp),
or also electrical voltage and is measured in "V" i.e. Volts.
Water in its descent downstream surely encounters rocks,
narrows, becomes a river and finds bends... such elements
that oppose the intensity of water flow, in electrical
engineering, are called "resistances" and they oppose the
flow of electric current. Resistance is measured in Ohms, or
also referred to as "☐."

Ohm's law.
At this point, we can already identify one of the earliest
laws of electrical engineering, namely: for the same voltage
(thus the jump in the waterfall's elevation), the higher the
resistance (i.e., the more rocks and impediments to water
flow), the lower the electric current (i.e., there is less water
flow). This law of electrical engineering is called Ohm's law
and is represented as follows:
The inverse formulas are:

and
What is an LED.

Although the shape is very


reminiscent of an incandescent bulb, its operation is
completely different. In the incandescent bulb, the current
flows through a very thin filament of material with high
electrical resistance, and thus by becoming incandescent,
because precisely the electrical resistance tries to prevent
the passage of current, incandescence generates light, but
also a lot of heat, which is wasted energy because it is not
used for the purpose of better brightness.
In an LED, current flows through a semiconductor (i.e., a
conductor that can conduct current only in a predefined
direction), and the material that makes up the
semiconductor, when current flows through it, emits light
(i.e., photons).
This method of producing light energy is much more
economical, in fact, there is no waste of energy that turns
into heat, and the LED is also more reliable as a light source
because it is not subject to the temperature changes that
cause incandescent filaments to break down, as is the case
with regular light bulbs.
Remember that the LED is a semiconductor, so the polarity
with which we power it is important; the anode (i.e., the
longest terminal) must be connected to the positive,
otherwise it will not light, and if a reverse voltage (with
swapped poles) is applied to it, which is higher than the
permissible threshold voltage, we will surely burn out the
LED.
In reality, even powering the LED correctly risks burning it
out, in fact you have to be careful not to exceed what is
called "junction voltage," which is why in series with the
LED in the previous project we put a 220 Ohm resistor (later
I will explain how to determine the correct resistor value
depending on the LEDs and the number of LEDs to be
powered.
The LED, as you can see from the figures above consists of
two platelets between which is the semiconductor that
when excited (i.e., run through by an electric current) emits
photons (i.e., light!). The platelets end in "terminals" one
longer (the anode) and the other shorter (the cathode). So
the positive voltage, the one indicated by the "+," should
be connected to the anode, the negative voltage, indicated
by the "-," should be connected to the cathode. The two
plates, with the semiconductor, are then covered with a
light-transparent plastic capsule that protects the
components and directs the same light outward.
Project 1 - Turning on an LED
The first project I would like to introduce is the power
supply of an LED .

For this project we need Arduino, the breadboard, an LED


(any color), a 220-ohm resistor (Ohm, also referred to as "
☐ ", is the unit of measurement of electrical resistance),
and Dupont jumper cables (male-male, i.e., those that have
the silver tip on both sides):

Arduino Uno Bread board 220 Ohm LED


R3 or resistance
compatible

Dupont male USB


- male cables connection
cable

Pay attention!
The 220 Ohm resistor is identified by the colored rings,
specifically if the resistor has 5 colored rings, it must have
the rings colored as follows: red-red-black-brown. If the
resistor has 4 colored rings, then the colors of the rings
must be: red-red-brown and then a silver or gold colored
ring. In the next lesson we will learn how to read the values
of resistors through the use of the color chart.

Resistance to 5 colored rings


Resistance with 4 colored rings
For the LED, you need to pay attention to the terminal pins,
one is longer and one is shorter:

The longer terminal (anode), in the connection diagrams is


shown "bent"
The connections to be made are:
If everything has been connected well, when you plug one
side of the USB cable into the USB port on the Arduino and
the other side of the cable into the USB port on the PC, the
LED should light up, because it is powered.
At the bottom is the electrical symbol of the LED and the
classical connection circuitry via resistor:
In the electrical circuit the resistor can be placed before or
after the LED, it does not matter because the two
components have the same "I" current flowing through
them (they belong to the same electrical branch), the
voltage drop across the resistor is identical. Such a way of
connecting the resistor to the LED is called, in
electrotechnical terms, "in series" , the meaning will be
better seen later.
So with this project, you are beginning to have your first
contacts with the world of electrical engineering and
electronics, but let's take a closer look at what we did.
Basically to a passive element, as the LED is, [passive
element means it needs electricity to function], we have
applied an electric voltage. The electric voltage is also
called EMF (electromotive force), in fact it indicates how
hard we push the electrons out of their orbits and create
that flow called electric current. The electric current, thus
generated, as it passes through the semiconductor material
that makes up the LED, transfers this energy to the same
material, which transforms it into "photons," that is, light.
So Arduino functioned as a power supply, i.e., energy
supplier, the electrical wires caused this energy to be
transferred to what is called the user, i.e., the LED
Some of this energy is dissipated in the resistor in series
with the LED in the form of heat, this is to reduce the
amount of energy that would otherwise be too high and risk
burning out the LED.
[For the video related to the project click here].
The Button: how it works and how to
use it
Before moving on to the next project, it is good to see how
a very important component works and how it is used: the
button.

The principle of operation of a button is very simple, and


the animated gif below visually summarizes that operation.
The button consists of a movable part and a fixed part, the
movable part consists of a metal blade attached to a plastic
holder that is the button of the button that will be pressed,
below that blade is a spring that keeps the movable part
pushed upward.
The fixed part, on the other hand, consists of two separate
blades that continue forming the button feet. The whole is
enclosed in a plastic case.
When the button is pressed, the spring compresses and the
moving blade brings the two fixed blades into contact. If an
electrical voltage (denoted by "+") is applied to one of the
two blades, that voltage is also transferred to the other
blade, so we have what is called in electrical engineering
jargon "closing an electrical circuit."
The buttons we use are characterized by having 4 pins (or
also called terminals) of which are two by two metallically
connected to each other.
So connecting either pin A or C is the same thing, as is also
pin B with respect to D. The pins that are separated
metallically, as the figure above also shows, are those that
are closest to each other, that is, pin A is separated from B,
just as C is separated from D.
Another type of push button, but whose functionality is
identical to that seen above, is the two-terminal push
button:

However, now let's execute a project that better than


anything else illustrates how the button works.
Project 2 - The use of a push button to turn on an
LED.
In this project I would like to show you how to power an LED
through the use of a Button that will allow us to turn the
LED on and off at will.

The materials needed for this project are identical to the


previous one, but in addition we need a micro button.

Arduino Uno Bread board 220 Ohm LED


R3 or resistance
compatible
Dupont male USB Button
- male cables connection
cable

We proceed with the connections as per the diagram below


keeping the USB cable disconnected from the Arduino. In
particular, attention should be paid to the longer terminal of
the LED which should be connected in series with the 220
Ohm resistor. The resistor in turn is in series with the button
terminal. The red dupont cable, which carries the 5V, should
be connected to the other terminal of the button and the
yellow dupont cable should be connected to the Arduino's
GND and the LED's cathode.
If everything has been connected well, when you plug the
cable to the USB port of your PC, the LED should be off and
pressing the button will turn it on, because only by pressing
the button is the LED powered, that is, the button closes the
circuit and gives electrical continuity.
[For the video related to the project click here].
Now we try to understand what we have done.
Let us remember the flow of water from a waterfall, or a
river.
With the insertion of the button, all we have done is to
interpose a dam, that is, an obstacle that cannot be crossed
by the water, and only when the pipes are opened does the
water flow out for the waterfall. So the button interrupts the
flow of current with a circuit interruption, only when it is
pressed the circuit is restored and current can flow through
it.
Another example to make people understand the function of
the button, is to imagine that you have a faucet, only when
you open the faucet you create the pressure difference such
that the water comes out (and thus circulate the power).

IMPORTANT: I would like to point out to you that I have


used the term conventional direction of current, this is
because in the days of the studies of this phenomenon it
was thought that it was the positive charges that moved
from the + to the - (because they were attracted by the
opposite sign), actually later it was discovered that it is the
electrons that generate the current flow and since they
have a negative charge, they are attracted to the positive
pole, so the current actually goes from the negative pole to
the positive pole, but conventionally we have continued to
maintain the convention that the current goes from the + to
the -.

Curiosity: A bit of scientific history


In 1799, Italian scientist Alessandro Volta (hence the
name Volt to the unit of voltage measurement), who had
been studying the then mysterious phenomena of
electromagnetism for years, succeeded in building an early,
rudimentary but effective electric battery.
In the early 1800s Charles Augustin de Coulomb
discovered that electrons, sub-atomic particles with a
negative electric charge, are naturally attracted to areas
where electric charges are of lesser intensity, and thus can
be seen as 'gaps,' with positive valence.
In the mid-1800s, around 1860, the unit for measuring
electric current was named after the French physicist
André-Marie Ampère, a leading scholar of
electromagnetism.
The Ohm (symbol: Ω) is the unit of measurement of
electrical resistance, its name derived from that of the
German physicist Georg Simon Ohm discoverer of Ohm's
law of the same name. In fact, in 1827, his main discovery
was that the electric current flowing through a conductor is
directly proportional to the voltage applied to its ends. Of
course, I have mentioned only a few physicists, actually
between the early and late 1800s, there were 100 years of
outstanding scientific discoveries in the fields of electrical
engineering, electronics and electromagnetism.
In 1889 the International System was born in Paris, after
the agreement of several states, i.e., fundamental physical
quantities such as: length, mass and time were given the
units of measurement "meter [m]," "kilogram [kg]" and
"second [s]," then over time were added: kelvin degrees
[K] for temperature, ampere [A] for current, candle [cd]
for brightness and mole [mol] for the amount of
substance. These are the units of measurement that all
scientists use to exchange information and scientific
research around the world.
What is a Breadboard.
The Breadboard is to the maker like
the blank canvas to a painter
[Roberto Francavilla].

Breadboard
is a board made of insulating material with many small
holes. There are commercially available of different sizes,
the most common one being the 400-hole one. The various
small holes are electrically connected to each other in a
special way that I will show you later. Basically, in these
small holes the terminals of the various electronic
components are inserted and without soldering, thus saving
considerable time and especially reuse of components, it
allows the connection between the various electronic
components.
In fact, the Breadboard is used to experiment with the
functionality of the circuits that makers develop with the
possibility of reusing components and the speed of
modifying and trying out different circuit solutions. As can
be seen from the photo, metal strips arranged horizontally
and vertically allow connections between holes in the same
horizontal and vertical row.
Breadboard columns are identified by numbers, rows by
uppercase letters.
The only rows whose holes are all electrically connected to
each other are those identified with "+" and " -." The holes
in the other rows (A, B, C, D, E, F, G, H, J), as can be seen
from the picture above and from the lines in the figure, are
not connected to each other horizontally, but they are
connected vertically, that is, in columns. This means that
inserting a pin in column 6 to any line in the group between
A and E, is the same thing. The Breadboard, as you can
always see from the figure, is divided into two parts that are
isolated from each other.
Project 3 - Hello World

With this project we begin to use Arduino in its true


functionality, in fact in projects 1 and 2 our Maker board
was used as a simple battery (power supply), now we will
use it for what it is, which is a development board with a
powerful and flexible microcontroller.
For the project we will only need an Arduino development
board and a USB cable. This project is not only a test of
communication between our Arduino board and PC, but also
a basic project in the Arduino world that introduces
programming.
Arduino Uno R3 or USB connection
compatible cable
And as a matter of practice, when starting to learn a new
programming language, one of the first things to learn is to
make our system we are programming write the phrase
"Hello Word."
Then we connect our development board to the PC via the
USB cable and launch the Arduino IDE application by
double-clicking on its icon.

An empty window opens, or a new empty window must be


opened:
We type the sketch below into the window:
/*
Be Maker - STEM - Project 3 - Hello World
*/
int val; //we define the variable named "val"
void setup()
{
Serial.begin(9600); // Let's initialize the port with a baud rate of 9600
}
void loop()
{
val = Serial.read(); // Reads what is entered into the bar as input to the Serial
Monitor and
// assigns it to the variable val.
if(val=='R') // Checks if what was entered is equal to the letter "R"
{ // if it is = "R",
Serial.println ("Hello World!"); // show the string message "Hello World!"
}}

Once you have written the sketch, first proceed to click on


the "V" (check mark), if there are no errors*, then upload it
to Arduino by clicking on "->" and finally, once uploaded
click on the lens (top right).
The Serial Monitor window appears to you:
Whenever we type in R (uppercase) and then on Send (or
Send), the Serial Monitor displays the words: Hello World !
* In case clicking on the check mark brings up an error, then
there are three possible causes:
1) Incorrect typing of the sketch, so double-check the
individual lines paying attention to the ";" at the end of
the instructions or the double lines for comments...we
will discuss this at length later anyway.
2) Incorrect configuration of the serial port on the PC,
about which I invite you to see the procedure provided
in the initial activities at the Course
3) Incorrect installation of the development board driver,
in fact some compatible Arduino install microcontrollers
that require special drivers to be installed on your PC in
order to be seen by the serial port. Also for this problem
see the procedure provided in the initial activities at the
Course.
[For the video related to the project click here].
[For the sketch related to the project click here].
Arduino's digital PINs
Before proceeding with the next project, it is helpful to
know what digital PINs are and how they work on our
development board. The Arduino board has 14 digital PINs.

Digital PINs are particular PINs that can function as an input


for Arduino or also as an output (the same PIN cannot
function as an input and an output at the same time) and is
characterized by the fact that it can take only two values:
state High - High i.e. 5 V and state Low - Low i.e. 0 V. Some
digital PINs (6 to be exact) are indicated with a wavelet " ⁓
", these digital PINs are characterized by the fact that they
can produce a PWM-type signal, but we will discuss this
later.
In the next project we begin to look at the use of Digital
PINs.
Project 4 - Police cars with flashing lights

This is a simple project showing the use of Arduino's digital


PINs.

Arduino Bread 2 x 220 Ohm Red LED


Uno R3 or board resistor
compatible
Blue LED USB Dupont male - Printed
connection male cables cardboard
cable
With this project we also learn the use of wiring diagrams
and the symbols to be used to represent the various
components. The wiring diagram to be made is as follows:

Instead, refer to the assembly diagram below for


connections:
After the connections we move on to writing the sketch.
Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.

An empty window opens, or a new empty window must be


opened:
Type the sketch below:
/*
Be Maker - STEM - Project 4 - Police Car
*/
void setup()
{
pinMode(4, OUTPUT); //we declare digital PIN 4 as the output
pinMode(6, OUTPUT); //we declare digital PIN 6 as the output
}

void loop()
{
digitalWrite(4, HIGH); //Put PIN 4 in high state = at 5V i.e. on
digitalWrite(6, LOW); //Put PIN 6 in low state = at 0V i.e., off
delay(1000); // we wait for 1000 milliseconds i.e. 1 second
digitalWrite(4, LOW); //Put PIN 4 in low state = at 0V i.e., off
digitalWrite(6, HIGH); //Put PIN 6 in high state = at 5V i.e. on
delay(1000); // we wait for 1000 milliseconds i.e. 1 second
}
Once you have written the code launch the verification
precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load:

As a result, the two red and blue LEDs will alternately turn
on and off after every second.
If you place the police car, previously printed and cut out, in
such a way that the two LEDs protrude from the car's upper
beacon, drilling two holes at appropriate distances for how
the LEDs are positioned, you will achieve a nice effect.
[For the video related to the project click here].
[For the sketch related to the project click here].
(print and cut out)
LESSON 2 - Insights into Electrical Resistance

We saw in the previous lesson, referring to a watercourse,


that electrical resistance can be defined as the "obstacle"
that water, i.e., electric current, encounters during its
natural path in the riverbed, i.e., electric cables.
Of course, it is easy to see how such difficulty of the water
current (but also of the electric current) depends on several
factors, namely, the length of the route (length of the
electric cables), the width of the riverbed (cross section of
the cables), and the type of soil that makes up the riverbed
(the material used for the electric conductors, whether
copper, aluminum, or other material).
In fact, the longer the course of the river, the higher the
resistance; the larger the cross-section of the riverbed (of
electric cables), the more easily water flows through it, so
the resistance is lower; if the riverbed is made up of fine,
compact sand or a well-smoothed surface, it will offer

less resistance
to water than a riverbed made up of irregular rocks;
likewise, there are materials that have properties such that
electric current will flow through them better than others.
For example, gold is an excellent electrical conductor, as are
silver, copper, aluminum... (all metals are good conductors),
while there are materials that hinder the passage of electric
current to such an extent that they are called "insulators"
such as plastic, rubber,...
Another way to visualize electrical resistance in order to
fully understand its physical principle is as depicted in the
figure below:
The amount of water in the two reservoirs is initially the
same, and the water level represents the electrical
potential, that is, the force by which the water is pushed out
of the pipe. The narrower the outlet pipe is, the more
difficulty the water will have in exiting.
Taking this to an extreme, if we were to have such a small
pipe (imagine a hair's width), it is intuitable that water will
have great difficulty escaping. The tube representing the
electrical conductor, in the case of it being a hair, will
obviously almost totally prevent water from escaping, in
which case the material constituting the conductor is called
an insulator and therefore the current flowing through that
conductor is practically zero.

The electrical resistor, the symbol of which is a zig-zag line,


is indicated by a capital letter " R " , then a subscript "1",
"2",... especially when there are several electrical resistors
of different values, the electric current flowing through it is
indicated by "I", while the electric voltage at the ends of the
electrical resistor is indicated by a "V" (remember the
waterfall seen in Lesson 1.... the water falls from the highest
point "+" to the lowest point "-") .
Observe that the voltage V conventionally is indicated by an
arrow opposite to the direction of the current, and the
arrowhead of the voltage corresponds to the "+." Current,
again conventionally, goes from the positive "+" pole to the
negative "-" pole.
Commercially available electrical resistors are readily
available components and can be found in different types
depending also on the currents they must be able to
withstand. Actually, the seller should be told the value of the
resistor you want and the electrical power (the current is
not given). Electrical power is another important electrical
quantity in electrical engineering and in the case of DC-fed
circuits, as in our case, it is denoted by P and is measured in
watts (electrical symbol "W"). Electrical power is calculated
by making the product of the value of the voltage applied to
the resistor and that of the current flowing through it, but it
is also equal to the product of electrical resistance and the
value of current flowing through it raised to the square, i.e:

For our projects, we will generally refer to electrical


resistance values ranging from a few hundred Ohms up to a
few tens of miles of Ohms, and we will use the resistance to
properly distribute the electrical voltage generated by the
Arduino, i.e., the 5 V, so that our components will work best
in the various electronic circuits we develop. Even for Ohms,
as for other units of physical quantities, there are multiples
and submultiples. We will, however, always stay in the
range of multiples, that is, we will often use "kOhm" (read
kiloOhm) [it is a multiple of Ohm, i.e., 1 kOhm corresponds
to 1000 Ohms]. So when I talk about tens of miles of Ohms,
I am talking about tens of kOhms. The values of current
circulating in the circuits we normally make are very low, on
the order of milli-amperes (mA). From this you understand
very well that the electrical powers involved are very low on
the order of 0.25 W or at most 0.5 W (in the trade, electrical
resistors capable of withstanding such powers are referred
to as ¼ watt or ½ watt).
The figure below shows what the resistor we use in our
circuits looks like.
There is a ceramic substrate on which is wound a wire of a
particular conducting material that has its own electrical
resistance; the number of turns represents its length and
thus its total resistance. The conducting wire terminates at
the ends on two plates with two metal terminals that are the
output connectors. The whole is then covered with another
ceramic material. The ceramic material is insulating, so in
addition to mechanically protecting the resistor, it prevents
short circuits from occurring.

How to read the value of a resistor


The resistance value is indicated on the outer casing by
colored circles or colored bands.
Let's say right away that there are different ways used to
indicate the resistance value, among the most popular ones,
of which standards have been created, are the value
indication with 4 circles in total and the one with 5 colored
circles in total, the one with 6 circles is less common, but
still used mainly for laboratory components.
The table below shows the correlation between circle colors
and resistor values. I would like to immediately and still
point out that one of the circles is always more spaced than
the others (in the case of 6-circle resistor, the most spaced
circles are 2).
The furthest circle indicates tolerance , for color reading
we start from the first circle on the side opposite the spaced
circle.
Resistors with 4 colored circles
The first circle indicates the value of the first digit, the
second circle indicates the value of the second digit and
the third circle indicates the multiplier, and finally the
fourth circle indicates the tolerance.
Let's give an example to get a good understanding of how
to apply the criterion of resistance enhancement.
Suppose we have a resistance like the one in the figure
below:

The first thing we need to identify is the most spaced circle


that is "gold" in color, this circle represents the tolerance on
the resistance value of the component, in this case the
tolerance, that is, the uncertainty on the value, is +/- 5%.
After that we go to see the color of the first circle on the
opposite side of the most spaced, the color is "brown," that
is, the first digit has a value of "1," the second circle is
"black," so the second digit has a value of "0," and the third
circle is "red," that is, a multiplicative factor " x 100."
At this point we know the value of the resistance, in fact:
R = 1 , 0, x 100, +/- 5% i.e. 10 x 100 +/- 5% and thus R =
1,000 Ohm +/- 5%
Our resistance is 1,000 Ohms, which is one kilo Ohm with a
tolerance of 5%.
Because we Makers like math we also go and calculate for
ourselves, in terms of values, what it means to have a 5
percent tolerance:
We calculate 5% of 1,000, i.e., 5 x 1,000 and then divide by
100, so we get 50, so:
R = 1,000 +/- 5% Ohm means that the value of R is
definitely somewhere between (1,000-50) 950 and
(1,000+50) 1,050 Ohms.

Resistors with 5 colored circles


The first circle indicates the value of the first digit, the
second circle indicates the value of the second digit, the
third circle indicates the value of the third digit and the
fourth circle indicates the multiplier, and finally the fifth
circle indicates the tolerance.
Again, let us give an example to get a good understanding
of how to apply the criterion of resistance enhancement.
Suppose we have a resistance like the one in the figure
below:

Again, the first thing we need to identify is the most spaced


circle that is "brown," this circle represents the tolerance on
the resistance value of the component, in this case the
tolerance, that is, the uncertainty on the value, is +/- 1%.
After that we go to see the color of the first circle on the
opposite side of the most spaced, the color is "red," that is,
the first digit has a value of "2," the second circle is
"purple," so the second digit has a value of "7," the third
circle is "black," so the third digit is "0," and finally the
fourth circle is "orange" , i.e. a multiplicative factor " 1 K "
i.e. "x 1000".
At this point we know the value of the resistance, in fact:
R = "2", "7", "0", x 1,000 +/- 1%, and that is R = 270,000
Ohms or even R=270 kOhm (kilo Ohms), with a tolerance of
1%, i.e.: 1 x 270,000 : 100 = 2,700 Ohms. So the true value
of the resistance is a number between 267,300 Ohms and
272,700 Ohms.
Since we are not making space shuttles, for our designs
having tolerances of 1%, 5%, and even 10% does not
involve committing significant errors, then from now on we
will consider tolerance only a component qualifier (i.e., we
will say that a component with a tighter tolerance is better
than one with a wider tolerance), but we will not take it into
account in our calculations.
One last example:

The first circle is red, so 2, the second circle is still red and
so another 2, the third circle is black, so the third digit is 0
and finally the fourth circle is black, so the multiplier is for 1.
So the R = 220 x 1 that is 220 Ohms.
Trivia: What is a Physical Magnitude
and Uncertainty in Measurements
A physical quantity is a property of a body (or phenomenon)
that can be measured. To specify the physical quantity
requires a number (which indicates its value) and a unit of
measurement. The unit of measurement is a reference
quantity of a quantity, which is assigned a value of 1.

Let's take an example to


better understand what I wrote:
One of the fundamental quantities is length to which the
meter [m] has been assigned as the unit of measurement.
But what is the meter?
In Sèvres, France, a rod
is preserved that has a length of 1 in 10 million of the length
of the arc of the Earth's meridian that starts at the North
Pole and passes through Paris, stopping at the Equator. This
rod, thus determined, represents the length of 1 m.
Obviously then for comparison the "meters" used when we
want to take measurements of an object were reproduced.
In fact, to measure a length, all we do is to see how many
times the meter is contained in the length to be measured.
Obviously when measurements of quantities are made,
there are also errors, which can be instrumental errors due
to the instruments not being perfectly calibrated, errors in
the reading of the instrument (the so-called parallax error)...
we are obviously talking about small errors that are related
to the measurement of the quantity. These errors then
introduce a small indeterminacy into the measurement, and
then you have the so-called tolerance in the measurement.
Project 5 - The Traffic Light with Arduino

Let's continue with the use of Arduino's digital PINs and


make a simple project that will give us lots of fun. Let's
make a traffic light with Arduino.
For this project we need:

Arduino Uno Breadboard Dupont USB


R3 or male - connection
compatible cable
male
cables

3 x 220 Ohm 3 x LEDs (red, Printed


resistor yellow and Cardboard
green)

The wiring diagram is:

Instead, follow the diagram below for assembly:


After the connections we move on to writing the sketch.
Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.

An empty window opens, or a new empty window must be


opened:
Type the sketch below:
/*
Be Maker - STEM - Project 5 - Traffic Light
*/
void setup()
{
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}

void loop()
{
digitalWrite(4, HIGH); //Red lit.
digitalWrite(5, LOW); //Yellow off
digitalWrite(6, LOW); //Green off
delay(6000); // 6 sec wait.
digitalWrite(4, LOW); //Red off
digitalWrite(5, LOW); //Yellow off
digitalWrite(6, HIGH); //Green on
delay(4000); // 4 sec wait.
digitalWrite(4, LOW); //Red off
digitalWrite(5, HIGH); //Yellow on
digitalWrite(6, HIGH); //Green on
delay(2000); // Waiting for 2 sec.
}

Once you have written the code launch the verification


precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load:

The result will be: the red LED turns on and stays on for 6
sec, after which the red LED turns off and the green LED
turns on. After another 4 sec, the yellow LED also turns on
and stays on for 2 sec. After that, the yellow and green LEDs
are turned off and the red LED is turned on again.
If you place the card with the traffic light, previously printed
and cut out, it will surely give you a nice effect.
[For the video related to the project click here].
[For the sketch related to the project click here].
Introduction to Coding

The time has come to enter the world of Coding, and the
first thing I would like to introduce is sketching. But first
let's take a little step back to understand what we mean by
Coding.
The term Coding has been around for a very few years and
as the name suggests comes from "coding" or generating
codes, which in turn, in computer terms, refers to
Programming Computers (or more generally: electronic
devices) using a particular programming language.
So, summarizing, the term coding refers to computer
programming and thus to the design and
development of software.
Saying that...you'll tell me, bravo you
copied the definition from the first-year high school book of
computer science....
.... but really: what does it mean to Program a
Computer or Electronic Device????

So I try to explain better--and to


explain, I don't want to start from the birth of Computers,
but from a concrete example.
Suppose we have an industrial process that we wish to
automate, for example, the production of corks from wine
bottles...

The first thing


we do is to
identify in detail
the entire
production
process: taking
the cork sheet,
transferring it to
the press, etc.....
so we define a
well-defined
ordered
sequence of
actions....
The various
actions,
although in a
well-defined
sequence, are
linked together,
and the link is
called an
algorithm.
For example:
before operating
the press check
that the cork
sheet is
positioned
correctly, if yes,
then proceed to
pressing,
otherwise
stop....
The one
described above
is an algorithm
of the logical
type.... But
there are also
mathematical
ones...
Once the
individual steps
of the process
and the
algorithms that
govern them
have been
determined,
then it is
translated into
the
programming
language, and
then you have
the production
of the software
that installed on
the control
machines and
PCs, realize the
desired
automated
process.

Coding -- that's what it means!


Well! After this introduction, let's move on to our Arduino
development platform and look at the sketch...
The sketch
You have surely understood, at least from the last few
projects you have done, that Arduino, since it is nothing
more than a minicomputer, needs to be programmed to do
what we want it to do, and this is done in its development
environment called IDE.

In fact, it is in the sketch that we will write, in a particular,


step-by-step language, what Arduino is to do for us.
The programming language we will use for the sketches is
basically C++
The sketch is made up of two parts, one beginning with
"void setup() { ...... }" and the other with "void loop() {
...... }" both parts enclose within curly brackets the
instructions that Arduino will execute. And in particular, in
the part enclosed by "void setup()..." as also the name
"setup" says, you define the "variables," "set" the Arduino
PINs, call libraries, etc... , however you write all those
instructions and/or all those operations that need to be
executed at least once. While in the "void loop ()..." part you
enter all those instructions that Arduino will execute in an
infinite loop (cycle).
Project 6 - The Stelliere

With this project we learn how to trigger an event on the


Arduino by simply pressing a button. The event, in this
particular case, is turning on an LED, but it could also be an
entire starry sky!
Arduino Uno R3 or Breadboard Resistance 1kOhm Dupont male -
compatible + male cables
220Ohm resistor

USB connection Button Yellow LED Printed


cable Cardboard

The wiring diagram is as follows:

Instead, the assembly diagram is this:


After the connections, let's move on to writing the sketch.
Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application and write the following code...
/*
Be Maker School - STEM - Project 6 - The Stelliere
*/

int val; // we define a variable named "val" of type integer

void setup()
{
pinMode (3, OUTPUT); // we set digital PIN 3 as the "output"
pinMode (1, INPUT); // we set digital PIN 1 as the "input"
}
void loop()
{
val = digitalRead (1); // reads the value taken on digital PIN 1
if (val == LOW ) // check if val has assumed the low state (button NOT pressed)
{
digitalWrite(3,LOW); // if the button is NOT pressed then digital PIN 3 is set to
LOW
} // the LED is kept off.
else
{
digitalWrite(3,HIGH); // if the button is pressed then digital PIN 3 is set to HIGH
} // the LED is turned on
}
Once you have written the code launch the verification
precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load.

Once you start the sketch, whenever you press the button,
Arduino commands the LED to turn on. Position the printed
card so that the yellow LED comes out of the star and you
have become a Stellier !
From this project onward, in order to learn the programming
language for making skatches, we also begin to do sketch
analysis of the projects we will gradually make.
[For the video related to the project click here].
[For the sketch related to the project click here].
Analysis of the sketch: The Stelliere
Analyzing the sketch, we can observe several interesting
things, first of all the usefulness of inserting comments.
Comments (which will be ignored by Arduino) can be
entered in two different ways. The first is with the use of the
split "/" and the asterisk " * " , specifically they are put at
the beginning and end of anything that Arduino should
ignore as a comment:
/* [comment] */ . This method is used when the comment
occupies multiple lines.
The second method is to put the double divided "//", this
way everything to the right of the // and for the entire line is
ignored by Arduino and not executed because it is seen as a
comment. This mode is used when the comment is on the
same line as an instruction to describe what the specific
instruction does.
Another interesting thing I want to point out to you about
the sketch is the definition of the digital PINs in the void
setup() , we said that the digital PINs can take two values:
HIGH and LOW (or even 0 and 1) and we said that the
Arduino digital PINs ranging from No. 0 to No. 13 can be
INPUT and OUTPUT PINs. In this project digital PIN 1 is of
INPUT, in fact when the button is pressed it carries voltage
to the PIN, so it receives a signal that we read with the
digitalRead instruction. Digital PIN 3, on the other hand,
provides a LOW or HIGH signal with the digitalWrite
instruction, so it is an OUTPUT PIN. This functionality of
digital PINs in the sketch, whether of INPUT or OUTPUT must
be declared in the void setup().
Arduino Analog PINs

Arduino has 6 Analog PINs named A0, A1, A2,...A5. Analog


PINs, like Digital PINs, can be configured as inputs or
outputs depending on their use.
A clarification needs to be made: an analog quantity can
actually take on infinite values, since Arduino is in essence a
minicomputer and is therefore characterized by digital
quantities, it cannot reproduce the infinite values required
by an analog quantity, but the quantity is "discretized" and
brought back to a value between 0 and 1023 , that is, in a
range of 1024 possible values. Since the quantities read or
reproduced by the Analog PINs are actually electrical
voltages, and knowing that the Arduino has a maximum
voltage of 5V output from its PINs (whether digital or
analog), it is readily understood that the value 0 is
associated with 0 V and the value of 1023 with 5V.
At this point by applying a simple proportion, we can derive
the value of the magnitude (if the value of the analog PIN is
known), or the value of the analog PIN if what is known is
the value of the magnitude. Let us see the application of
this concept in a Project.
Project 7 - Ohmeter. Using Arduino to measure a
resistance

Suppose we have a resistor whose bands are not readable


or have erased, the question is, how do we determine the
resistance value of an unknown resistor?
This project shows the use of Arduino when we want to
know the value of a resistor whose colored bands above the
component are not shown for whatever reason. We need:
Arduino Uno R3 or Breadboard Resistance 1kOhm Dupont male
compatible - male cables

USB connection Unknown resistor


cable or alternatively.
220 Ohm resistor

The wiring diagram is as follows. We use a 220-ohm resistor


as the Rx:

Instead, the assembly diagram is this:


Note: A 220-ohm resistor was used as the unknown resistor.
Now we double-click on the Arduino icon on the Desktop and
the IDE opens and we copy the following sketch, be sure to
follow each step indicated:
/*
Be Maker- STEM - Project 7 - Ohmeter
*/

void setup() {
Serial.begin(9600); //serial port initialization
}

void loop() {
int read=analogRead(A0); //read the value from pin A0
// I apply Proportion:
// x : reading = 5 : 1023 -> x = (5*reading)/1023
float Vout=(reading*5)/1023.0; //With the proportion I calculate the voltage
float current=(5-Vout)/1000; //Apply Ohm law and calculate current
float ResIncognita=Vout/current; //calculate the unknown resistance

Serial.print("Voltage output: "); //print the results


Serial.print(Vout);
Serial.print(" Resistance value: ");
Serial.println(ResIncognita);
delay(1000); //cycle restarts after 1 sec.
}

Once you have written the code launch the verification


precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load and then on the lens to access the serial
monitor.
Started the Serial Monitor, the result is this:
If you remember the tolerance.... whereby the measured
value (214.71 Ohms) will always be slightly different from
the theoretical value of 220 OhmsCOPY00 in fact, if you
apply the formula of percentages [(220-214.72)/220]*100 =
2.4, you then get an error of about 2.4%, that is, within the
allowable tolerance which is that stated by the resistor
manufacturer (+/- 5%), otherwise you could have asked for
a refund...
Tip ! : When using Arduino to make measurements, always
check the correct functionality of the components,
otherwise you risk going crazy... for example I happened to
use a 1 kOhm resistor that was actually 10 kOhm! So I was
getting values ten times smaller than expected. I solved the
problem by checking the actual value of the resistor with a
tester and then realized that a batch of resistors bought and
sold for 1 kOhm, were actually 10 kOhm.
Sketch Analysis: Ohmeter with
Arduino
Analyzing the Ohmeter sketch, we observe the following:
In the "void setup() { ...... }" enclosed by the two curly
brackets is the following instruction:
Serial.begin (9600);
this instruction sets the communication speed between the
Arduino and the PC to 9600 bits per second, which is the
maximum communication speed on the COM port between
the PC and the Arduino. This instruction is entered when you
want to display the values of variables on the serial monitor
in the IDE. Variables are empty containers that are filled
during sketch execution (we will see more about this topic in
a later lesson).
The instruction "analogRead(...)" is one of the most
important instructions in the Arduino language, in fact
through this instruction it is possible to read the values of
the analog PINs present on the Arduino. The correct syntax
is as follows ("read" is an arbitrary name assigned to a
variable):
int read = analogRead(A0);
At the end of each instruction is the ";" , the semicolon
indicates that the instruction is finished and Arduino will
move on to the next one. After this instruction, the sketch
running on Arduino reads the value on the PIN and gives it a
number from 0 to 1023 (i.e., 1024 values), where "0" if the
value of the voltage read at PIN A0 is 0 V and "1023," if the
voltage read is 5 V (i.e., the maximum voltage that can be
produced on the PIN by Arduino). For intermediate numbers
at these two extremes, and thus to have intermediate
values of voltage read at the PIN, proportions must be
made..... holy Math!!!
In fact, for example, suppose the value read on the PIN is
"184," at which point we apply the proportion:
1024 : 5 = 184 : x
(reads 1024 stands for 5 volts as 184 stands for X volts,
where X is the unknown)
The formula for solving this proportion tells us that to derive
the unknown value X, we must multiply the inner members
of the proportion and divide by the (known) outer member,
so:
X = 5 * 184 /1024 = 0.898 V
So the voltage measured by Arduino at PIN A0 is about 0.9
V. Noting the voltage, applying Ohm's Law, seen in the
previous Lesson, we derive the value of the unknown
resistance. I will stop here with the explanation of the
formulas used, because I do not want to bore you with
further calculations, which we will see in other projects
anyway.
At this point we see the last two instructions:
Serial.print("Output voltage: ");
Serial.println(Vout);
The Serial.print Instruction ("....") prints on the screen, on
the Serial Monitor, the content between the " " (quotation
marks) and printing occurs on the same line. To access the
Serial Monitor, as mentioned earlier, you click on the lens.
The Serial.println (...) instruction prints and then goes to the
carriage return line for the next print.
The instruction Serial.println(Vout); prints the value
contained in the variable Vout (and then goes to the next
line).
[For the video related to the project click here].
[For the sketch related to the project click here].
(print and cut out)
LESSON 3 - Robotics with Arduino

With this lesson we begin to explore the world of sensors


that we can connect to Arduino, and so with that we also
begin to talk about robotics.
Did you know that with Arduino you can build real robots?
Nooo!
And instead Yes!!! It all depends on your imagination.
The word "robot" is assumed to come from the Czech
language meaning "slave" and was a word used in ancient
Europe to refer to people who did the heavy and repetitive
work, but the best use of the word Robot is, in my opinion,
by the great writer Asimov who also set the laws of it:
First Law: "A robot cannot harm a human being nor can it
allow a human being to receive harm because of its failure
to do so."
Second law: "A robot must obey orders given by humans
as long as those orders do not contravene the first law."
Third law: "A robot must protect its own existence as long
as this does not conflict with the first and second laws."
Obviously, today by the word robot we denote anything that
performs operations mechanically in an automatic way
thanks to an electronic controller, with particular reference
to programmable devices used in some sectors of industry,
but also for domestic uses (see for example kitchen robots,
robot vacuum cleaners..).
What enables a machine to have reactions, and thus a
certain behavior, are the SENSORS, which are those
electronic devices that detect the values of a physical
quantity and transmit its changes.
Sensors are also called TRANSDUCERS which can be
classified as active if the transducers generate a current or
voltage signal or passive if the transducers produce a
change in an electrical parameter such as resitance,
capacitance etc. at the output.
Another classification criterion refers to the type of signal
produced at the output.
Analog transducers have an output signal that continuously
follows changes in the input physical quantity. Digital
transducers output the value of the magnitude inn
numerical terms with discrete values. However, don't worry,
by the end of the course you will be very good at
understanding the operation of lots of sensors.
The photoresistor or also called Light
Sensor

In this lecture we will discuss the light sensor. In particular


we will talk about photoresistors its commercial English
name is LDR that is Light Dependent Resistor, which is that
electronic component that as the brightness of the
environment in which it is placed changes its electrical
resistance, and then with that change we can establish
different behaviors for Arduino to perform.
The operating principle of an LDR is based on special
characteristics possessed by certain substances that when
subjected to the action of light (photons), change their
resistivity characteristics. Electrical resistivity, also called
specific electrical resistance, is the ability of a material to
resist the passage of electrical charges. In the International
System, resistivity is measured in ohms per meter (Ω-m).
Resistivity differs from resistance in that it is a specific
property of the material in question and depends primarily
on the microscopic structure of the medium; in contrast,
resistance R is a property of the entire conductor under
consideration (macroscopic property).

The animated figure above shows how some materials when


hit by photons (light) absorb energy and are able to conduct
more electric current when subjected to an electric voltage
(electrons are released from their bond). These materials,
therefore, change their resistivity, lowering it, when affected
by light. In the absence of light, photoresistors act as
materials with high resistivity.
For our projects we will refer to the GL 5528 photoresistor:
As we have said there is a link between amount of light
striking the photoresistor and the value of Resistance that
the sensor takes on, this link is expressed by means of a
graph (logarithmic-based) shown below:
On the x-axis (x-axis), there are Lux (i.e., light intensity); on
the y-axis (y-axis) there are kOhm (i.e., Resistance). As can
be seen from the graph, the greater the light, the smaller
the Resistance.
The gray band represents the uncertainty (tolerance) range
of the LDR - GL5528 sensor.
The circuit in which a photoresistor is inserted is called a
voltage divider and is the same circuit used to measure
the unknown resistance in the ohmmeter seen in the
previous lesson, i.e., you put two resistors in series of which
one is known and measure the voltage value (Vm) at the
junction point of the two resistors. Knowing the voltage
applied to the circuit (5 V), one can determine the value of
the unknown resistance of the photoresistor and thus
measure the brightness:

We have the voltage Vm measured by Arduino by taking the


signal to one of its analog PINs, e.g., A0, at this point,
knowing the voltage Vm, we know the voltage applied on
the known resistor, which is obtained by deduction, i.e.: 5 V
- Vm, consequently we can calculate the electric current "I"
which by Ohm's law (V = R x I) is equal to (using the inverse
formula):
and finally we can calculate the value of the unknown
resistance:

If we also have the correspondence table between the


degree of brightness (which is measured in lux) and the
resistance value, we also know how much light is hitting the
photoresistor moment by moment. For example,
photoresistor manufacturers release what are called data-
sheets (i.e., data sheets) of components (an example is the
figure below referring to the GL5528 photoresistor):
which tells us that with 10-15 lux of brightness, a resistance
value of about 10-15 kOhm corresponds.
Since I believe that I have reached and exceeded the
attention curve... and therefore I am sure that from this
moment on you will not receive anything more..., let us
move on to practical things and therefore let us carry out
the following project.
Project 8 - Crepuscular Switch with Photoresistor
For this project we need:

Arduino Uno Breadboard Dupont male USB


R3 or - male cables connection
compatible cable

220 Ohm Yellow LED Resistance 1 Photoresistor


resistance kOhm GL5528

The wiring diagram is:


The diagram below should be followed for assembly:
After the connections we move on to writing the sketch.
Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.

A blank window opens, or a new blank window needs to be


opened and we write the sketch below:
/*
Be Maker - STEM - Project 8 - Twilight.
*/
void setup() {
pinMode(2,OUTPUT); //we set PIN 2 as the output
Serial.begin(9600); //we set the serial port
}
void loop() {
int read=analogRead(A0); //reads the PIN A0
float Vout=(reading*5)/1024.0; //determines the Vout on the base
//of the value read at PIN A0
float Rnota=1000.0; //value of the known Resistance i.e. 1000 Ohm
float current=(5-Vout)/Rote; //calculates current
float ResIncognita=Vout/current; //calculates unknown resistance

Serial.print("Voltage output: "); //print on the screen the sentence between ""
Serial.print(Vout); //print the Vout value on the screen
//println means it then goes to head
//to the next line
Serial.print(" Resistance value: "); //print on the screen the sentence between
""
Serial.println(ResIncognita); //print the resistance value on the screen

if (ResIncognita>10000) {
digitalWrite(2,HIGH); //puts PIN 2 in high state [5 V].
}
else {
digitalWrite(2,LOW); //puts PIN 2 in a low state [0 V].
}
delay(1000); //waits one second before starting again
}

Once you have written the code launch the verification


precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow for loading and the lens for the Serial Monitor:
Once you start the sketch, do some testing by lowering the
brightness of your room and raising it, when the room gets
dark then Arduino commands an LED to turn on (the
reference value you can lower or raise depending on the
brightness conditions of your room).

Sketch Analysis: Twilight Switch with


Photoresistor
Analyzing the sketch we see that it is basically similar to the
previous one on the Ohmeter, so there would be nothing to
highlight except the use of the "if" control structure.
The control structure works like this: if the condition in the if
brackets is true, then Arduino will execute the instructions
contained in the if brackets, otherwise it means that the
condition is not verified and everything enclosed in the else
brackets will be executed.
The syntax is as follows:
if (condition) {
//statement(s)
}
else ) {
//statement(s)
}
[For the video related to the project click here].
[For the sketch related to the project click here].
Curiosity: What is Light
Until the early 1900s, Light was thought to consist of
electromagnetic waves and as such followed the laws of
classical electromagnetism; the waves consisted of two
sinusoidal components perpendicular to each other (see
animated gif: blue-colored magnetic field and red-colored
electric field):

The frequency of these waves, that is, the periodicity with


which the waves repeat, if it was in the range of 400 to 700
nanometers wavelength (this is called the spectrum, the
range of frequencies), could be visible to the human eye
(spectrum of visible light). Each frequency, of this
spectrum, also defines the color of light, and the sum of all
the frequencies of visible light form the so-called White
Light, which is then that emitted by the sun.
In the early 1900s, particularly between 1900 and 1905,
Max Planck and Albert Einstein, with the theories and
experiments of quantum neo-physics, introduced the
concept of the photon, and thus defined light as being
composed of photons i.e. particles of zero mass, but made
of energy alone.
This particle, the photon, also has the properties of being an
electromagnetic wave.

Project 9 - Luxmeter with Arduino

Also in this project with Arduino we will make a measuring


instrument, namely the Luxmeter. What is the Luxmeter
used for? It is used to measure the intensity of light present
in a given environment or how much light is hitting an
object...you know the instruments that photographers used?
well! those were basically luxmeters; once they measured
the light, they gave indications of the shutter aperture time
and aperture.
For this project we need:

Arduino Uno R3 or Breadboard Resistance 1kOhm Dupont male -


compatible male cables

USB connection LDR GL5528 220 Ohm resistor LED


cable Photoresistor
The wiring diagram is as follows and is identical to the one
above:
As also the assembly scheme is identical to that of the
previous project:

Before we pass are to the sketch, a little


explanation is needed on how to derive the lux value of the
brightness by measuring the value of the photoresistor
resistance, in essence we will use the table already
described previously, namely:
the table refers to GL5528, obviously if another type of
photoresistor were to be used, the table would have to be
rebuilt in the same way as I did above.
For the association of values in the table we will use what in
computer jargon is called the method of "nested ifs" , this
method is generally avoided, but for educational reasons I
propose it.
Now we double-click on the Arduino icon on the Desktop and
the IDE opens and we copy the following sketch, be sure to
follow each step indicated:
/*
Be Maker - STEM - Project 9 - Luxmeter
*/
void setup() {
pinMode(2,OUTPUT); //we set PIN 2 as the output
Serial.begin(9600); //we set the serial port
}

void loop() {
int read=analogRead(A0); //reads the PIN A0
float Vout=(reading*5)/1024.0; //determines the Vout on the base
//of the value read at PIN A0
float Rnota=1000.0; //value of the known Resistance i.e. 1000 Ohm
float current=(5-Vout)/Rote; //calculates current
float ResIncognita=Vout/current; //calculates the resistance of the photoresistor

Serial.print(" Photoresistor value [kOhm]: "); //print on the screen the sentence
between ""
Serial.print(ResIncognita); //print the value of the resistance
Serial.print (" Value Illuminance [lux]: "); //print on the screen the sentence
between ""
if (ResIncognita<=2000) {
Serial.println (" over 100 lux ");
digitalWrite(2,LOW); //puts PIN 2 in a low state [0 V].
}
else {
if (ResIncognita>2000 && ResIncognita<3500) {
Serial.println (" about 80 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=3500 && ResIncognita<4500) {
Serial.println (" about 40 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=4500 && ResIncognita<5500) {
Serial.println (" about 30 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=5500 && ResIncognita<9500) {
Serial.println (" about 20 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=9500 && ResIncognita<29500) {
Serial.println (" about 5 lux ");
digitalWrite(2,LOW);
}
else {
if (ResIncognita>=29500) {
Serial.println (" about 1 lux ");
digitalWrite(2,HIGH); //puts PIN 2 in high state [5 V].
}
}}}}}}
delay(1000); //waits one second before starting again
}

Once you have written the code launch the verification


precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load and then on the lens to access the serial
monitor.

Started the Serial Monitor, the result is this:


Sketch Analysis: Luxmeter with
Arduino
The particularity of the sketch of this project is to have
created ranges of correspondence of resistance values to
illuminance values and then depending on the resistance
value the most appropriate illuminance value is chosen, this
was done using nested ifs, that is, after the if that
theoretically establishes the alternative to a condition and
closes the verification (as happens to the sketch of the
previous project), a new condition is immediately reinserted
to be verified with a new "if" and this happens as many as 6
times. As I said at the beginning, this programming
methodology has only a didactic purpose, generally we try
to avoid nested ifs and C++ also provides other solutions
that we will see in other projects.
[For the video related to the project click here].
[For the sketch related to the project click here].
The PWM signal - Pulse Width
Modulation
We know that Arduino has 14 digital PINs, that is, they are
capable of receiving input, or giving an output signal with
only two states, HIGH and LOW.
Digital PINs are indicated by numbers ranging from 0 to 13,
but paying attention some of them also have in addition to
the number a ripple symbol " ᷉ ". Those PINs are Digital PINs
with the capability of giving an output voltage of the PWM
type, in English Pulse Width Modulation, that is, a Pulse
Width Modulated Electric Voltage. The Digital PINs with such
functionality are the: 3, 5, 6, 9, 10 and 11.
Let's see what we can do with these PINs with a ripple
(slang for "tilde").
The PWM signal is a signal that is always based on the
principle of on or off (so it retains the characteristics of the
two states HIGH and LOW), but if we consider a period of
time (called: cycle) and in this period we go to change the
holding duration of the high state, rather than the low state,
and repeat it for all cycles, the average value of the signal
that we have at the PIN is no longer 0V or 5V, but will be a
value between 0 and 5V.
The adjacent figure explains this concept, but let's look at it
even better with the next figure.
In the
first case, we have that the value of 5 V is not maintained in
the cycle time, so the signal is 0% of the 5 V voltage, that is,
the digital PIN has an average value of 0 V at its output.

In the
second case, 5 V is maintained for 25 percent of the cycle
time, that is, 25 percent of 5V, so the voltage at the digital
PIN output has an average value of 1.25 V.

In the
third case, 5V is maintained for 50% of the cycle time, that
is, 50% of 5V, so the voltage at the digital PIN output has an
average value of 2.5 V.

In the
fourth case, 5V is maintained for 75% of the cycle time, that
is, 75% of 5V, so the voltage at the digital PIN output has an
average value of 3.75 V.
In the
fifth case, 5V is maintained for 100% of the cycle time, that
is, 100% of 5V, so the voltage at the digital PIN output has
an average value of 5V.
A PWM digital PIN can be given values between 0 and 255
(where 0 indicates 0 V and 255 indicates 5 V-essentially 256
values).
The instruction, with its syntax, for assigning a PWM signal
to a digital PIN is as follows:

So summarizing the above in a schematic, and assuming


that PIN No. 11 is used for a PWM-type signal, we have:

Of course, we can also use the intermediate values and not


just the ones given.
The next project shows in a practical way an interesting
application of the PWM signal to digital PINs. In fact, it is
enough to think of an Arduino function that allows us to
adjust the brightness of an LED (but it could be anything
else, e.g., the lights in our house, the rotational speed of a
motor, ....) by acting on the PWM digital PINs, but I will say
more, we can adjust such variation to other external
phenomena as well.
The following project links the measurement of external
brightness detected by a photoresistor to the brightness
that we wish to give in a room, however, before we delve
into the project I would still like to highlight one thing that
will be very useful in so many applications.
Relationship between Analog PINs
and PWM Digital PINs
As explained earlier an Analog PIN takes values between 0
and 1023 (where 0 indicates 0V and 1023 indicates 5V-
essentially 1024 values ), while a PWM digital PIN takes
values between 0 and 255 (where 0 indicates 0V and 255
indicates 5V-essentially 256 values).
At this point, thanks to a simple proportion of our holy
Mathematics, we are able to write a formula that defines the
voltage of a PWM digital PIN as a function of the value
detected by the analog PIN (for example: A0). In fact, the
proportion is as follows:
256 : 1024 = X : reading at PIN A0
(reads: 256 stands for 1024 as the unknown value to be
derived and sent to the digital PWM PIN stands for the
reading at Pin A0)
When the unknown is in the proportional means, we know
that to derive it we do the multiplication between the
proportional extremes and divide by the known term
between the proportional means.
Therefore:

but 256/1024 = 1/4, so to get the corresponding PWM signal


value by having an analog signal, just divide the latter value
by 4.
Project 10 - Night and Day with PWM Signal

Suppose we want to keep the light in a room constant at all


times, so as the sun goes down, gradually artificial lighting
goes to supplement the sunlight to keep the same level of
brightness in the room at all times. Well the project I present
allows precisely this functionality.
For this project we need:

Arduino Uno R3 or Breadboard Resistance 1kOhm Dupont male -


compatible male cables
USB connection LDR GL5528 220 Ohm resistor LED
cable Photoresistor
The wiring diagram is as follows:

While below is the assembly diagram:


Now we double-click on the Arduino icon on the Desktop and
the IDE opens and we copy the following sketch, be sure to
follow each step indicated:
/*
Be Maker School - STEM - Project 10 - Night and Day
*/
void setup() {
pinMode(11,OUTPUT); //we set PIN 11 as the output
Serial.begin(9600); //we set the serial port
}

void loop() {
int read=analogRead(A0); //reads the PIN A0
int valuepwm=reading/4; //converts the reading into the PWM signal
float Vout=(reading*5)/1024.0; //determines the Vout on the base
//of the value read at PIN A0
float Rnota=1000.0; //value of the known Resistance i.e. 1000 Ohm
float current=(5-Vout)/Rote; //calculates current
float ResIncognita=Vout/current; //calculates unknown resistance

Serial.print("Photoresistor resistance [Ohm]: ");


Serial.print(ResIncognita);
Serial.print(" A0 read value: ");
Serial.print(reading);
Serial.print(" PWM value before map: ");
Serial.print(valuepwm);
valuepwm = map(valuepwm, 200, 255, 0, 255); //map value according to new
scale
Serial.print(" PWM value after of map: ");
Serial.println(valuepwm);
if (valuepwm<0) {valuepwm=0;}
analogWrite(11,valuepwm); //sets PIN 11 to a variable voltage between 0 and
5V
delay(200); //holds 200 ms before starting again
}

Once you have written the code launch the verification


precompilation (check mark), it will ask you to save the
sketch (you can change its name) and then click on the
arrow to load and then on the lens to access the serial
monitor.
Starting the sketch on Arduino, if everything has been done
correctly, you have that by shading the photoresistor sensor
(even with a pen cover), the brightness of the LED
increases, while on the contrary, by getting more light to the
sensor, the LED tends to go out, all with a FADE-type effect
i.e., with a gradual change.

Analysis of the Sketch: Night and Day


with PWM signal
There are so many interesting things to analyze in this
sketch. Let's go through them all starting with the main
things:
1) You can see how the PWM signal is applied to the
digital PIN, in fact the analogWrite instruction is used for
a PWM digital PIN instead of the classic digitalWrite
instruction. You can see this in the line where there is:
analogWrite(11,valuepwm);
2) We have seen how to convert a value from an Analog
PIN to a corresponding value from a Digital PWM PIN,
just divide the reading on the Analog PIN by 4, this can
be seen on the line: int valuepwm = reading/4;
3) Since at the time of the execution of the project it was
night and in my room at most I could get 50 lux and no
more, you understand very well that the LED always
started from an on condition. So I used a function called
map, which basically just calculates proportions, and
then what was my possible range of PWM signal values
(unable to run the project in full sunlight) ranging from
a minimum of 200 to a maximum of 255, I remapped it
to a new scale of 0 to 255.

The syntax for the map function is:


map(value, fromLow, fromHigh, toLow,
toHigh)
you see it applied to the sketch at line: valuepwm =
map(valuepwm, 200, 255, 0, 255);
where the variable valuepwm is assigned the new remapped
value of the value that the same variable had before. Since
in remapping it could happen to have negative values that
are considered by the PWM digital PIN as a HIGH value, then
I also had to enter in control with an if to the line: if
(valuepwm<0) {valuepwm=0;}
[For the video related to the project click here].
[For the sketch related to the project click here].
Project 11 - The Return of the Cylons

I have always been a fan of the Battlestar Galactica TV


series, and the thing I was curious about was how they gave
the light movement that was somehow supposed to
represent the Cylon robots' visuals. Well! with the project we
are going to develop you too can make a Cylon head and
why not, use it for carnival.
For this project we need:
Arduino Uno R3 or Breadboard USB connection Dupont male -
compatible cable male cables

No. 5 220 Ohm No. 5 Red LEDs


Resistors
The wiring diagram is as follows:

The assembly diagram is as below:


Now open a new sketch window by double-clicking on the
Arduino application and write the code below and save the
file:
/*
Be Maker - STEM - Project 11 - Cylon
*/
int delay=100;
int delay2=1;

void setup()
{
//configure PWM PINs at the output
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
}

void loop()
{
analogWrite(9, 255);
//cycle of for with i decreasing to make
//gradual switching off of the LED
for (int i = 255; i >= 0; i--) {
analogWrite(10, i);
delay(delay2);
}
delay(delay);
analogWrite(6, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(9, i);
delay(delay2);
}
delay(delay);
analogWrite(5, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(6, i);
delay(delay2);
}
delay(delay);
analogWrite(3, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(5, i);
delay(delay2);
}
delay(delay);
analogWrite(5, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(3, i);
delay(delay2);
}
delay(delay);
analogWrite(6, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(5, i);
delay(delay2);
}
delay(delay);
analogWrite(9, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(6, i);
delay(delay2);
}
delay(delay);
analogWrite(10, 255);
for (int i = 255; i >= 0; i--) {
analogWrite(9, i);
delay(delay2);
}
delay(delay);
}

Important: The sketch above was written in that form to


account for the still limited knowledge of the programming
language for Arduino, but by using arrays the code can be
greatly simplified:
/*
Be Maker School - STEM - Project 11 - Cylon array version
*/

int delay1=100;
int delay2=1;
int myLED[] = {3,5,6,9,10};
int count=0;

void setup()
{
//configure output PWM PINs with for loop
for (count=0; count<6; count++) {
pinMode(myLED[count], OUTPUT);
}
}

void loop()
{
for (count=0; count<5; count++) {
analogWrite(myLED[count], 255);
if (count>0) {
for (int i = 255; i >= 0; i--) {
analogWrite(myLED[count-1], i);
delay(delay2);
}
}
delay(delay1);
}
for (count=4; count>0; count--) {
if (count>0) {
analogWrite(myLED[count-1], 255);
}
for (int i = 255; i >= 0; i--) {
analogWrite(myLED[count], i);
delay(delay2);
}
delay(delay1);
}
}
Load the sketch and you get a nice effect of a peering
robotic eye, especially if you cut out the cardboard and
create the slit in which to insert the LEDs.... The famous
KITT car from Supercar also had a similar effect...

Analysis of the Sketch: Return of the


Cylons
Not considering the second transcribed sketch because the
topics covered will be seen later, from the first sketch we
can observe that the only new topic introduced is the for
loop.
The for loop is used when we need, within the body of the
program , to have repetitive operations performed a certain
number of times. In fact in this case it was using to drive the
LED shutdown in a gradual way using the variable i that
starting from the maximum value of 255, at each cycle it
would decrease and the LED light intensity accordingly also.
The syntax for the for loop is:
for (initialization; condition; increment) {
// statement(s);
}
In our sketch it was using for example:
for (int i = 255; i >= 0; i--) {
analogWrite(10, i);
delay(delay2);
}
The integer variable "i" starts at a value of 255 and
decrements down to zero; as long as this condition is true,
the for loop repeats and in particular performs what is
between the curly brackets, that is, it goes to write into the
PWM digital PIN a value equal to the variable i (which is
decreasing) and then goes to gradually turn off the LED
connected to PIN 10.
[For the video related to the project click here].
[For the sketch related to the NORMAL project click here].
[For the sketch related to the CON ARRAY project click here].
(print and cut out)
LESSON 4 - THE RGB LEDS

We saw in Lesson No. 1 that the LED is made of a special


semiconductor material that when a current is passed
through it emits light. It is called a semiconductor because it
conducts and therefore emits light only if the voltage is
applied properly, that is, the anode (the longer terminal)
must be connected to the positive voltage, while the
cathode (the shorter terminal) is connected to ground.
The semiconductor part occupies less than a millimeter, so
what we see is the outer part of the lens that scatters the
light. We have seen that LEDs can be of different colors, the
RGB LED is basically composed of three LEDs, so it emits
three different wavelengths of light, one red, one green and
one blue (hence the acronym RGB: Red, Green and Blue).
The emission of light with a different wave frequency
depends on the type of substance used as a semiconductor
in the LED. The table above shows, depending on the color
of the LED, the substances used, the wavelength and also
the threshold voltage, which also represents the maximum
voltage that can be applied to the LED otherwise the LED
will be ruined or may even burn out.
For this reason, as mentioned in Be Maker Module 01, the
LED should be protected, and thanks to the table above we
can also calculate what is the most appropriate resistor
value to use. In fact, it can be seen that the threshold
voltage is generally, for various LEDs, about 2 V. Considering
that the maximum current for an LED is about 15 mA, or
0.015 A, applying Ohm's Law:

Once the value is calculated, we need to take the


"commercial" resistance value closest to the calculated
value. Commercial values are the standard resistance
values that we can find commercially, which are
summarized (the main ones) in the table below:

The RGB LED can look different: as a regular 5-mm LED with
four terminals, or in strips of the SMD type (with four wires),
or even mounted on a board (RGB module) with four PINs.

The three main colors mixed together, in different


intensities, produce virtually infinite color combinations:

There are two types of RGB LEDs, one is with COMMON


CATODE (common negative that is connected to GND) and
the other is with COMMON ANODE (common positive and
then connects to 5V).
In the common anode (+) type, there will be three negative
terminals each representing the single color of light emitted;
in the common cathode (-) type, there will be the three
positive terminals and each representing the single color of
light. In series with each LED (and thus each terminal
excluding the common anode or common cathode) a
resistor is inserted that will allow the current circulating in
the diode to be regulated, so three 220 Ohm resistors will be
needed (red, red, brown circles).
The internal circuit of an RGB LED can be represented as
below.

Instead, the wiring diagram with the three protective


resistors is:
Project 12 - RGB LEDs with Arduino
For this project we need:

Arduino Uno Breadboard Dupont USB


R3 or male - connection
compatible male cable
cables

No. 3 LED RGB


Resistors
220 Ohm

The wiring diagram is:


The diagram below should be followed for assembly:
Once the circuit is assembled, the sketch to be written and
uploaded to Arduino is:
/*
Be Maker - STEM - Project 12 - LED RGB
*/

int redpin = 11; // we assign the name redpin the value 11


int bluepin =10; // we assign the name bluepin the value 10
int greenpin =9; // let's assign the name greenpin the value 9
int val;
void setup() {
pinMode(redpin, OUTPUT); // we set in OUTPUT the 11
pinMode(bluepin, OUTPUT); // we set in OUTPUT the 10
pinMode(greenpin, OUTPUT); // we set in OUTPUT the 9
Serial.begin(9600);
}
void loop()
{
for(val=255; val>0; val--)
{
analogWrite(11, val);
analogWrite(10, 255-val);
analogWrite(9, 128-val);
delay(10);
}
for(val=0; val<255; val++)
{
analogWrite(11, val);
analogWrite(10, 255-val);
analogWrite(9, 128-val);
delay(10);
}
Serial.println(val, DEC);
}

Once the sketch is loaded on the Arduino and the serial


monitor is opened, the RGB LED shows the RGB color
combinations according to the values represented on the
monitor.
[For the video related to the project click here].
[For the sketch related to the project click here].
CURIOSITY: Stars shine and change
color.

Stars "shine" and change color because it is a phenomenon


that depends on the fact that starlight, before reaching your
eyes, must pass through the atmosphere.
The atmosphere is made up of many small cells of air. Each
cellette moves in random motion, rising or falling due to
thermal convection: this is called atmospheric turbulence.
When the star's light passes through these air cells, the
path of its rays is randomly deflected, which causes you to
see the star apparently blink and sometimes change color.
The lower the star is on the horizon or the brighter it is, the
more intense the phenomenon.
Of course, if we were observing the starry sky from the
Moon, since there is no atmosphere on the Moon, this
optical phenomenon would not be there.
.
Project 13 - Starlight
For this project we need:

Arduino Uno R3 or Breadboard Dupont male - USB connection


compatible male cables cable

No. 3 Resistors LED RGB Button Resistance 1kOhm


220 Ohm

Potentiometer 1
KOhm

The wiring diagram is:


The diagram below should be followed for assembly:

After the connections we move on to writing the sketch.


Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.

A blank window opens, or a new blank window needs to be


opened and we write the sketch below:
/*
Be Maker School - STEM - Project 13 - Starlight
*/
int redRGB = 11; //select the pin for the red LED of RGB
int bluRGB =9; // select the pin for the blue LED of RGB
int greenRGB =10; // select the pin for the green LED of RGB
int pinBut=4; // select pin for digital input from button
int val; //variable intensity for the color of RGB
int color; //1=red, 2=blue, 3=green
int pushbutton; //variable that tells me if button pressed
void setup() {
Serial.begin(9600);
pinMode(redRGB, OUTPUT);
pinMode(bluRGB, OUTPUT);
pinMode(greenRGB, OUTPUT);
pinMode(pinBut, INPUT_PULLUP);
color=1;
analogWrite(redRGB, 255);
analogWrite(bluRGB, 255);
analogWrite(greenRGB, 255);
}
void loop(){
pushbutton=digitalRead(pinBut);
if(pushbutton==0){
color=color;
}
else {
color++;
if (color>3){
color=1;
}
}
intensity_color(color);
}
void intensity_color(int state){
val = analogRead(A0);
val = map(val,0,1023,0,255);
switch (status) {
case 1:
Serial.print("Color Red ");
analogWrite(redRGB, val);
break;
case 2:
Serial.print("Blue Color ");
analogWrite(bluRGB, val);
break;
case 3:
Serial.print("Green Color ");
analogWrite(greenRGB, val);
break;
}
Serial.print("- Intensity'= ");
Serial.println(val);
delay(200);
}

Once you have written the code launch the verification


precompilation (click on the check mark), it will ask you to
save the sketch (you can change its name) and then click on
the arrow for loading and the lens for the Serial Monitor:
/*
Be Maker - STEM - Project 13 - Starlight
*/

int redRGB = 11; //select the pin for the red LED of RGB
int bluRGB =9; // select the pin for the blue LED of RGB
int greenRGB =10; // select the pin for the green LED of RGB
int pinBut=4; // select pin for digital input from button
int val; //variable intensity for RGB color
int color; //1=red, 2=blue, 3=green
int pushbutton; //variable that tells me if button pressed

void setup() {
Serial.begin(9600);
pinMode(redRGB, OUTPUT);
pinMode(bluRGB, OUTPUT);
pinMode(greenRGB, OUTPUT);
pinMode(pinBut, INPUT_PULLUP);
color=1;
analogWrite(redRGB, 255);
analogWrite(bluRGB, 255);
analogWrite(greenRGB, 255);
}

void loop(){
pushbutton=digitalRead(pinBut);
if(pushbutton==0){
color=color;
}
else {
color++;
if (color>3){
color=1;
}
}
intensity_color(color);
}

void intensity_color(int state){


val = analogRead(A0);
val = map(val,0,1023,0,255);
switch (status) {
case 1:
Serial.print("Color Red ");
analogWrite(redRGB, val);
break;
case 2:
Serial.print("Blue Color ");
analogWrite(bluRGB, val);
break;
case 3:
Serial.print("Green Color ");
analogWrite(greenRGB, val);
break;
}
Serial.print("- Intensity'= ");
Serial.println(val);
delay(200);
}

Once you start the sketch and open the serial monitor, you
can see on the screen which color of the RGB LED is active
and its intensity value, at which point acting on the
potentiometer will change the color of the RGB LED because
you are changing the intensity of the active color.
To change the active color and thus the color to be changed,
you can press the button, again on the screen you will be
shown the new active color and so on.
In this way you can mix the three RGB colors at will and get
the desired color by simulating the color change of the
stars.

Analysis of the sketch: Starlight


There are so many new and interesting things to learn in
this sketch, let's start with the simplest one:
a) Use of "INPUT_PULLUP"; as you can see in the void
setup, the digital input pin that controls whether or not
the button has been pressed has been set as
INPUT_PULLUP. This statement allows Arduino to set
itself up to receive an unstable signal such as that from
pressing a button. Then Arduino will attempt to stabilize
the input signal.
b) Use of the control structure switch(...) ..... case ... ; in
one of the previous projects we had seen the use of the
"nested" if structure, but I had also said that this way of
making the processor make decisions, was not very
suggested especially when there are so many cases to
examine. The use of the switch...case... simplifies the
structure, in fact we only need to define for each
individual case what to do and then have the switch
function do the case selection directly.. The general
syntax of the control structure is:
switch (var) {
case label1:
// statements
break;
case label2:
// statements
break;
default:
// statements
break;
}
Where var is a variable of type int or char and indicates
the number of the "case" you want to process, and
label1 is the label, also a variable of type int or char. In
the syntax example there are only three cases of which
one is the default. The last case, the default case is
selected when you have none of the previous cases.
The structure can also have more cases than those
represented.
c) Use of calling an external "procedure"; in the sketch
you can see that in the void seup, in the final part,
there is: " intensity_color(color); " so we are going to call an
external procedure to the void setup that performs a
particular process.
As you can see the external procedure was defined with
the "void" also since in the procedure there is the
control structure switch...case... to the same procedure,
through its call, we are also passing it a parameter (put
in round brackets) that it will use in its process.
In fact, the procedure is called by putting
procedure_name(eventual_parameter); , the definition
of the procedure is:
void process_name(int eventual_parameter) { process}
[For the video related to the project click here].
[For the sketch related to the project click here].
Project 14 - Starlight 2
This project is the natural continuation of the previous one,
in fact with this project I wish to visually highlight, instead of
reporting it on the serial monitor, what color we are acting
on with the potentiometer adjustment. And this can be done
by integrating three LEDs with their protective resistors to
the previous project. For this project, therefore, we need:

Arduino Uno R3 or Breadboard Dupont male - USB connection


compatible male cables cable

No. 6 Resistors LED RGB Button Resistance 1kOhm


220 Ohm

Potentiometer 1 Blue LED Red LED Green LED


KOhm
The wiring diagram is:
The diagram below should be followed for assembly:

After the connections we move on to writing the sketch.


Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.
A blank window opens, or a new blank window needs to be
opened and we write the sketch below:
/*
Be Maker - STEM - Project 14 - STARLIGHT_2
*/

int redRGB = 11; //select the pin for the red LED of RGB
int bluRGB =9; // select the pin for the blue LED of RGB
int greenRGB =10; // select the pin for the green LED of RGB
int redLED = 7; //select the pin for the red LED
int bluLED =5; // select the pin for the blue LED
int greenLED =6; // select the pin for the green LED
int pinBut=4; // select pin for digital input from button
int val; //variable intensity for RGB color
int color; //0=red, 1=blue, 2=green
int pushbutton; //variable that tells me if button pressed

void setup() {
Serial.begin(9600);
pinMode(redRGB, OUTPUT);
pinMode(bluRGB, OUTPUT);
pinMode(greenRGB, OUTPUT);
pinMode(redLED, OUTPUT);
pinMode(bluLED, OUTPUT);
pinMode(greenLED, OUTPUT);
pinMode(pinBut, INPUT_PULLUP);
color=1;
analogWrite(redRGB, 255);
analogWrite(bluRGB, 255);
analogWrite(greenRGB, 255);
}

void loop(){
pushbutton=digitalRead(pinBut);
if(pushbutton==0){
color=color;
}
else {
color++;
if (color>3){
color=1;
}
}
choice_color(color);
intensity_color(color);
delay(200);
}

void choice_color(int state){


Serial.print(" status=");
Serial.print(state);
switch (status) {
case 1:
digitalWrite(redLED, HIGH);
digitalWrite(bluLED, LOW);
digitalWrite(greenLED, LOW);
break;
case 2:
digitalWrite(redLED, LOW);
digitalWrite(bluLED, HIGH);
digitalWrite(greenLED, LOW);
break;
case 3:
digitalWrite(redLED, LOW);
digitalWrite(bluLED, LOW);
digitalWrite(greenLED, HIGH);
break;
}
}

void intensity_color(int state){


val = analogRead(A0);
val = map(val,0,1023,0,255);
Serial.print(" intensity=");
Serial.println(val);
switch (status) {
case 1:
analogWrite(redRGB, val);
break;
case 2:
analogWrite(bluRGB, val);
break;
case 3:
analogWrite(greenRGB, val);
break;
}
}

Once the sketch is started, in addition to the RGB LED


turning on, the LED whose intensity can be changed via the
potentiometer will also turn on. By pressing on the button
you can change the modifiable active color and this will be
represented by the corresponding colored LED.

[For the video related to the project click here].


[For the sketch related to the project click here].
The Tilt Sensor or also called the Ball
Tilt Sensor.
This sensor can be found commercially as a simple sensor
or even as a pre-assembled module. The operating principle
is the same, and it is basically a digital signal that tells us
whether the sensor has tripped or not.
The working principle is represented by the animated GIF
image I made:
inside an involocro there are two end plates and a metal
ball, when the casing, which has the cylindrical shape is
moved, the ball touches the two end plates and closes the
electrical contact between the terminals.
Basically, it behaves like a button, except that the contact
closure occurs because the ball rolls inside the cylinder.
By appropriately positioning the terminals and sizing the
enclosure, it is also possible to choose with what minimum
degree of tilt the ball contacts the two terminals. In the
following project we see an application of this and how to
connect it to Arduino.
Project 15 - Making an Electronic Hourglass.

For this project we need:

Arduino Uno R3 or Breadboard Dupont male - USB connection


compatible male cables cable

No.6 220Ohm No. 3 Red LEDs Tilt sensor Resistance 1kOhm


Resistors
No. 3 Yellow LEDs
The wiring diagram is:

While the assembly diagram is:


Be careful when positioning the tilt sensor, it should be
positioned so that in the initial position it causes contact
and by rotating it 180° it does not, otherwise the desired
effect will not be achieved.
Now we double-click on the Arduino icon on the Desktop and
the IDE opens and we copy the following sketch, be sure to
follow each step indicated:
/*
Be Maker - STEM - Project 15 - Electronic Hourglass
*/
const byte SWITCH_PIN = 7; // digital PIN for reading the tilt sensor
byte switch_state = 0;
void setup(){ //using the for loop set PINs in Output
for(int i=8;i<14;i++){
pinMode(i, OUTPUT);
}
pinMode(SWITCH_PIN, INPUT_PULLUP);
for(int i=8;i<11;i++){
digitalWrite(i,0);
}
for(int i=11;i<14;i++){
digitalWrite(i,1);
}
Serial.begin(9600);
}

void loop() {
switch_state = digitalRead(SWITCH_PIN);
Serial.println(switch_state);
if (switch_state == 0){
delay(1000); //after one sec.
digitalWrite(13,0);
digitalWrite(8,1);
delay(1000);
digitalWrite(12,0);
digitalWrite(9,1);
delay(1000);
digitalWrite(11,0);
digitalWrite(10,1);
}
if (switch_state == 1){
delay(1000);
digitalWrite(8,0);
digitalWrite(13,1);
delay(1000);
digitalWrite(9,0);
digitalWrite(12,1);
delay(1000);
digitalWrite(10,0);
digitalWrite(11,1);
}
}
Once the sketch is loaded, Arduino will check the status of
the Tilt Sensor, and will appropriately orient the "sand in the
hourglass," that is, it will turn on the appropriate LEDs, of
course once this step is completed, that is, the LEDs are all
on one side, then to restart the hourglass, it will be
necessary to flip the tilt sensor to start the hourglass in
reverse.

Analysis of the Sketch: The Electronic


Hourglass
As can be seen from the sketch, a "for" loop is used in the
setup part to set the PINs to which the LEDs are connected ,
of course they are all set in OUTPU because they generate a
signal that can be either high state (LED on) or low state
(LED off).
The PIN to which the Tilt Sensor is connected is set as
INPU_PULLUP to prepare Arduino to better stabilize the
signal coming to it on that PIN.
The delay instruction, which in its classical syntax is : delay
(milliseconds); is used to scan time and thus to simulate
sand falling from the hourglass.
In fact, as you can see from the sketch , in the design it is
set for a time equal to one second (i.e., 1,000 milliseconds),
the time it takes for an LED at the top of the hourglass to
turn off and for it to turn on at the bottom (transfer of sand
from top to bottom).
[For the video related to the project click here].
[For the sketch related to the project click here].
(print and cut out)
LESSON 5 - THE SOUND

We devote this Lesson to the study of Sound, or rather the


generation and propagation of sound waves and the related
Arduino sensors and modules that exploit this phenomenon
to handle events.

CURIOSITY: What is sound?


Suppose you drop a stone into the water of a pond, you will
see that waves expand from the point where the stone falls,
these waves move away from the point of fall and
propagate in concentric circles.
If we make a body vibrate, these vibrations of the body are
transferred to what surrounds the body (e.g.: air, water, etc.
) and this phenomenon occurs due to the
expansion/compression action of the molecules of the air or
water in which the body that is vibrating is immersed. This
results in the generation of sound.
The sound produced by the vibration of a body propagates
through waves, and to give visibility to this phenomenon,
we gave the example of a stone dropped into the water of a
pond.

Instead, in the animated image above, the


compression/expansion phenomenon is shown with the
example of a foil vibrating in the air; the light blue-colored
arrows indicate the air sucked into the area of depression
created by the movement of the foil. The blue-colored
arrows, on the other hand, indicate the overpressure
created by the same movement in the opposite direction.
The vibration, then, compresses and expands the air
surrounding the body; this compression and expansion is
transmitted to the surrounding air, thus producing waves
called "sound waves" (sound: because at certain
frequencies, to simplify--at a certain speed of vibration, such
waves can also be heard). In fact, these vibrations are then
picked up by the ear, which inside the ear, thanks to the
presence of the "eardrum" and due to the presence of
"ossicles," transfer and transform the vibrations picked up
into electrical impulses that our brain translates into a
sensation called sound.

So sound is a sensation that we receive and comes from


a vibration of a body. If such sensation is pleasant, then we
call it "sound," otherwise it is classified as "noise."
Very important in the propagation of sound is the medium in
which it propagates, which also determines its speed.

In water, the In air, because In iron, the


speed is 1480 the molecules are propagation speed is
m/s. That is, in more rarefied 5130 m/s, that is, in
one second the (they are farther one second sound
sound wave apart) the speed travels about 5 km.
travels about of sound This is because the
1.5 km. propagation is crystallines are much
about 340 m/s, closer together and
that is, in one therefore the
second sound transmission of
travels 340 m. vibration induced by
the action of
compression/expansi
on is more
immediate.

Is it in a vacuum? Obviously in a vacuum, since there is no


compression/expansion of molecules, no sound is
propagated.
The sound wave in its path may encounter an obstacle,
usually a "denser" body. For example, a sound wave that is
propagating in the air, when it encounters a rock wall,
reflects off it and a "reflected wave" is generated and some
of the sound is also reproduced in the rock.

When the reflected wave returns in the same direction as


the source, the phenomenon we call "echo" occurs.
Frequency, which is measured in Hz (pronounced erz), which
is the closeness between the sound waves produced (or
rather: the number of sound waves transmitted in one
second), classifies sound into: low sounds (what we call
"bass") or high sounds (what we call "treble").

Only certain frequencies of sound are audible to the human


ear, those that have a frequency between 20 Hz and 20,000
Hz (or even written 20 kHz). Elephants can perceive sounds
even below 20 Hz, while bats can perceive sounds as low as
120 kHz.
After the theoretical part, which gave us a better
understanding of sound, we move on to the practical part
with a nice project, which was a lot of fun.
Project 16 - The Teresa wasp and the active buzzer.

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable
Buzzer active Print drawing

Before moving on to circuit assembly, it is good to know that


the active buzzer has two PINs, one of which is longer. The
longer one is the positive PIN " + " , the shorter one is the
negative " - ". Generally, the passive buzzer also has a
sticker where the positive PIN is indicated.

The electrical symbol of the active buzzer is:

The wiring diagram to be made is as follows:


The assembly scheme to be carried out is as follows:

Note: The positive PIN of the active buzzer is connected to


digital PIN 8 of the Arduino, and the negative PIN to GND.
Once the circuit is assembled (and the design placed on the
buzzer), the sketch to be written and uploaded to Arduino is:
/*
BE MAKER - STEM - Project No. 16 - Vespa Teresa
*/
int buzzerPin = 8; //I assign PIN 8 the positive PIN of the buzzer

void setup ()
{
pinMode (buzzerPin, OUTPUT); //declare in OUTPUT the PIN 8
}
void loop ()
{
digitalWrite(buzzerPin, HIGH); //enable PIN 8 to 5 V
delay (500); //leaving PIN 8 powered for half a second
digitalWrite(buzzerPin, LOW); ///put out PIN 8

delay (500); //I leave PIN 8 off for half a second

When the sketch is loaded, the buzzer will sound


intermittently; you can change the on/off time of the buzzer
by going to the time indicated in the delay of the sketch.
[For the video related to the project click here].
[For the sketch related to the project click here].
The Passive Buzzer
The Buzzer is a piezoelectric device. Piezoelectricity is the
property of certain crystalline materials to polarize by
generating a potential difference when subjected to
mechanical deformation and at the same time to deform
elastically when subjected to an electrical voltage.

The GIF above shows how a Deformation of the


piezoelectric material generates a Voltage

The GIF above shows how a Voltage applied to the


piezoelectric generates a Deformation
Buzzers can be active, if they have within them an
oscillator (a quartz with a predetermined and fixed
frequency) that when energized with electrical voltage
stresses the piezoelectric material at a certain frequency
and then, this vibration of the piezoelectric material (usually
a membrane), produces sound at a fixed frequency (this is
the so-called Monotone Sound).
Passive Buzzers, not having an oscillator, need a time-
varying supply voltage in order to produce sound. So the
variable voltage with a given frequency is given from the
outside. To do this, we can take advantage of our Arduino's
ability to produce a time-varying voltage through PWM
(Pulse Width Modulation), i.e., a Pulse Width Modulated
Voltage. But at this point the question arises, what if we
vary the frequency? You will get different sounds and at
certain frequencies, you can even reproduce musical notes.
So, the conclusion is that with an Arduino and a passive
Buzzer we can play melodies .

The buzzer is used in alarms, countdowns, keyboard input


confirmation, etc.
The passive buzzer is the one shown in the photo below:

In the table is the correspondence between the main notes


and the frequency.
Project 17 - The passive buzzer and the Piano-Man.

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

Passive buzzer 220 Ohm resistor


Before moving on to the assembly of the circuit, it is good to
know that the passive buzzer has a low resistance, which is
why it is used to put a 220 Ohm resistor in series with the
passive buzzer.In addition, since we will be feeding the
buzzer with a "square half-wave," in order to have a
cleaner emitted sound, it would be useful to couple a filter
(basically a capacitor) to the buzzer.But these aspects,
concerning applied electronics, we will see in a dedicated
course.For the moment, let us just insert a resistor and for
our teaching purposes.
The electrical symbol of the passive buzzer is:

The wiring diagram to be made is as follows:


The assembly scheme to be carried out is as follows:

Once the circuit is assembled, the sketch to be written and


uploaded to Arduino is:
/*
Be Maker STEM - Project 17 Plan_Man Passive Buzzer
*/

#define BUZZER_PIN 9 //we connect to PIN 9 the Buzzer

#define NOTE_C5 523


#define NOTE_D5 587
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_G5 784
#define NOTE_A5 880
#define NOTE_B5 988
#define NOTE_C6 1047

//She builds a vector (variable containing multiple values) with the Notes:
unsigned int melody[] = {
NOTE_C5, NOTE_D5, NOTE_E5, NOTE_F5, NOTE_G5, NOTE_A5, NOTE_B5,
NOTE_C6};

unsigned int duration = 500; //Duration of the note in milliseconds

void setup() {
pinMode(BUZZER_PIN, OUTPUT); //Let's output PIN 9
}

void loop() {
for (int thisNote = 0; thisNote < 8; thisNote++) {
tone(BUZZER_PIN, melody[thisNote], duration); //see more
delay(1000);//It changes note after one second
}
delay(2000);//After two seconds the cycle starts again
}

When the sketch is loaded, the buzzer will play a melody


formed by the scale of Notes.

Analysis of the Project 17 sketch -


The passive buzzer and the Piano-
Man.
In the sketch, it can be seen that to activate the passive
buzzer, the instruction to be given is "tone" with the
following syntax:
tone (num_pin, frequency_note, duration_note);

With this instruction, a PWM signal is generated with


specified frequency and holding the same frequency equal
to the value also specified.
While for active Buzzer activation it was sufficient to put the
Buzzer PIN in the high state with a simple instruction of
digitalWrite (buzzerPin, HIGH);
And to turn it off, of course:
digitalWrite (buzzerPin, LOW);
Another thing I would like to point out is the definition of the
vector, that is, that particular variable we have called
"melody," which as you can observe contains multiple
values. The individual values are placed in an orderly
fashion from position 0 to position "n-1." They can be called
by writing in the sketch the name of the variable and inside
the square brackets, the position of the value we wish to
read:
melody [thisNote]
[For the video related to the project click here].
[For the sketch related to the project click here].
It is possible to experiment with new melodies and practice
with the Tone instruction, using the examples in the IDE. To
open them:

You can also try this tune I found on the Internet (just copy-
paste):
/*
Be Maker STEM - Project 17a_Buzzer Passive
*/

#define NOTE_B0 31
#define NOTES_C1 33
#define NOTES_CS1 35
#define NOTE_D1 37
#define NOTE_DS1 39
#define NOTE_E1 41
#define NOTE_F1 44
#define NOTE_FS1 46
#define NOTE_G1 49
#define NOTE_GS1 52
#define NOTE_A1 55
#define NOTE_AS1 58
#define NOTES_B1 62
#define NOTE_C2 65
#define NOTE_CS2 69
#define NOTE_D2 73
#define NOTE_DS2 78
#define NOTE_E2 82
#define NOTE_F2 87
#define NOTE_FS2 93
#define NOTE_G2 98
#define NOTE_GS2 104
#define NOTE_A2 110
#define NOTE_AS2 117
#define NOTE_B2 123
#define NOTE_C3 131
#define NOTE_CS3 139
#define NOTE_D3 147
#define NOTE_DS3 156
#define NOTE_E3 165
#define NOTE_F3 175
#define NOTE_FS3 185
#define NOTE_G3 196
#define NOTE_GS3 208
#define NOTE_A3 220
#define NOTE_AS3 233
#define NOTES_B3 247
#define NOTES_C4 262
#define NOTES_CS4 277
#define NOTE_D4 294
#define NOTE_DS4 311
#define NOTE_E4 330
#define NOTE_F4 349
#define NOTE_FS4 370
#define NOTE_G4 392
#define NOTE_GS4 415
#define NOTE_A4 440
#define NOTE_AS4 466
#define NOTES_B4 494
#define NOTE_C5 523
#define NOTES_CS5 554
#define NOTE_D5 587
#define NOTE_DS5 622
#define NOTE_E5 659
#define NOTE_F5 698
#define NOTE_FS5 740
#define NOTE_G5 784
#define NOTE_GS5 831
#define NOTE_A5 880
#define NOTE_AS5 932
#define NOTE_B5 988
#define NOTE_C6 1047
#define NOTE_CS6 1109
#define NOTE_D6 1175
#define NOTE_DS6 1245
#define NOTE_E6 1319
#define NOTE_F6 1397
#define NOTE_FS6 1480
#define NOTE_G6 1568
#define NOTE_GS6 1661
#define NOTE_A6 1760
#define NOTE_AS6 1865
#define NOTE_B6 1976
#define NOTE_C7 2093
#define NOTE_CS7 2217
#define NOTE_D7 2349
#define NOTE_DS7 2489
#define NOTE_E7 2637
#define NOTE_F7 2794
#define NOTE_FS7 2960
#define NOTE_G7 3136
#define NOTE_GS7 3322
#define NOTE_A7 3520
#define NOTE_AS7 3729
#define NOTE_B7 3951
#define NOTE_C8 4186
#define NOTE_CS8 4435
#define NOTE_D8 4699
#define NOTE_DS8 4978
#define REST 0
int tempo=114; // change this to make the song slower or faster
int buzzer = 9;// change this to whichever pin you want to use
// notes of the moledy followed by the duration.
// a 4 means a quarter note, 8 an eighteenth , 16 sixteenth, so on
// !!negative numbers are used to represent dotted notes,
// so -4 means a dotted quarter note, that is, a quarter Plus an eighteenth!!!
int melody[] = {
NOTE_E4,4, NOTE_E4,4, NOTE_F4,4, NOTE_G4,4,//1
NOTE_G4,4, NOTE_F4,4, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_C4,4, NOTE_D4,4, NOTE_E4,4,
NOTE_E4,-4, NOTE_D4,8, NOTE_D4,2,
NOTE_E4,4, NOTE_E4,4, NOTE_F4,4, NOTE_G4,4,//4
NOTE_G4,4, NOTE_F4,4, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_C4,4, NOTE_D4,4, NOTE_E4,4,
NOTE_D4,-4, NOTE_C4,8, NOTE_C4,2,
NOTE_D4,4, NOTE_D4,4, NOTE_E4,4, NOTE_C4,4,//8
NOTE_D4,4, NOTE_E4,8, NOTE_F4,8, NOTE_E4,4, NOTE_C4,4,
NOTE_D4,4, NOTE_E4,8, NOTE_F4,8, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_D4,4, NOTE_G3,2,
NOTE_E4,4, NOTE_E4,4, NOTE_F4,4, NOTE_G4,4,//12
NOTE_G4,4, NOTE_F4,4, NOTE_E4,4, NOTE_D4,4,
NOTE_C4,4, NOTE_C4,4, NOTE_D4,4, NOTE_E4,4,
NOTE_D4,-4, NOTE_C4,8, NOTE_C4,2
};
// sizeof gives the number of bytes, each int value is composed of two bytes (16
bits)
// there are two values per note (pitch and duration), so for each note there are
four bytes
int notes=sizeof(melody)/sizeof(melody[0])/2;
// this calculates the duration of a whole note in ms (60s/time)*4 beats
int wholenote = (60000 * 4) / time;
int divider = 0, noteDuration = 0;
void setup() {
// iterate over the notes of the melody.
// Remember, the array is twice the number of notes (notes + durations)
for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {
// calculates the duration of each note
divider = melody[thisNote + 1];
if (divider > 0) {
noteDuration = (wholenote) / divider; // regular note, just proceed
} else if (divider < 0) {
// dotted notes are represented with negative durations!!!
noteDuration = (wholenote) / abs(divider);
noteDuration *= 1.5; // increases the duration in half for dotted notes
}
// we only play the note for 90% of the duration, leaving 10% as a pause
tone(buzzer, melody[thisNote], noteDuration*0.9);
// Wait for the specief duration before playing the next note.
delay(noteDuration);
noTone(buzzer); // stop the waveform generation before the next note.
}
}
void loop() {
// if you want to repeat the song forever, paste the setup code here .
}

[For the sketch related to the MELODIA project click here]


CURIOSITY: The Microphone and the
Loudspeaker or Acoustic Speaker.
At this point, with the knowledge we have gained about
Sound and Piezoelectric materials, we are able to
understand quite well how the microphone works.
The microphone is nothing more than a "Transducer" of the
pressure that sound waves exert on a membrane, into
electrical impulses. This "transduction" (or more simply, this
translation of a vibration into a sequence of electrical
impulses) takes place with the help of a special material
called piezoelectric. In fact, the piezoelectric material as we
have seen is capable of producing a voltage when it is
stressed to a compression or expansion, that is, when it
undergoes a deformation.

In the loudspeaker there is basically the reverse process to


the microphone, that is, the electrical impulse, suitably
amplified, activates an electromagnet that attracts to itself
a permanent magnet attached to a taut membrane. In this
way, the movement of the magnet generates the vibrations
of the membrane and thus reproduces sound waves with
the same frequency induced by the movement of the
magnets.
So with the use of microphones and speakers we are able to
equip our Robot with hearing and speech.

Project 18 - What happens in that house? Let's use


the microphone.

For this project we need:


Arduino Uno R3 or Breadboard Dupont male - USB connection
compatible male cables cable

Microphone 220 Ohm resistor Led of any


module color

Before moving on to the assembly of the circuit, it is good to


know more about the Sound Sensor Module or microphone
that we will be using for educational purposes, in fact, there
are different types of Sound Sensor Modules on the market,
from the more sophisticated ones that also have an
amplification circuit and very sensitive microphones, and
those that are purely for educational purposes, less
sensitive but equally functional. However, the operation is
basically the same.
We will use the Sensor Modules that are commercially found
with the abbreviation KY-037 and with the abbreviation KY-
038 which is the older brother (slightly more sensitive),
these in turn can have 4 PINs because they make both a
digital and analog output signal available, those with 3 PINs
make only the digital signal available.
In addition they may have one or two LEDs, at least one LED
is used to verify the correct sensitivity setting, while the
second one, precisely not always present, indicates the
power supply to the Module. Finally, these Modules always
have a trimmer (i.e., a small potentiometer) that by
adjusting it using a screwdriver, it is possible to establish
the threshold sensitivity that the microphone must have in
order to make the digital signal available in the output state
of LOW or HIGH at the relevant PIN indicated by D0 or by
OUT (in the case of a 3-PIN Module).
At this point we turn to the wiring diagram:

(Note: Use the digital PIN of the D0 Sound Sensor Module or


also indicated with OUT for the 3 PIN Module). The mounting
diagram is instead:
After the connections we move on to writing the sketch.
Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.

A blank window opens, or a new blank window needs to be


opened and we write the sketch below:
/*
Be Maker STEM - Project 18-Sensor_Digital_Room.
*/

int digitalPin = 9; //PIN digital signal of Sound Sensor Module


int digitalValue = 0; // Variable that retains the value 0 or 1 if it exceeds the
threshold
//Takes sensor calibration to create threshold value.
int ledPIN= 3; // PIN to which the LED is connected
void setup ()
{
pinMode (digitalPin, INPUT); //We set PIN 9 as the INPUT
pinMode (ledPIN, OUTPUT); //We set PIN 3 as the OUTPUT
Serial.begin (9600); //We set the serial communication port.
}

void loop ()
{
digitalValue = digitalRead(digitalPin); //read the value at PIN 9
if (digitalValue > 0) {
digitalWrite (ledPIN, HIGH);
delay(3000); //keeps the LED active for 3 sec.
}
else {
digitalWrite (ledPIN, LOW);
}
}

Warning: once the sketch is loaded on Arduino, the sensor


module must be calibrated according to the background
noise present in your environment. So if the LED connected
to PIN 3 remains on, it means that the background noise is
exceeding the calibration threshold, turn the screw present
on the module's trimmer, using a flathead screwdriver, until
the LED goes off. Conversely, in case the LED is off even
with loud noise, adjust until it turns on. Position the screw
just at the limit so that the LED is off and turns on at the
slightest noise slightly louder than in the environment.
[For the video related to the project click here].
[For the sketch related to the project click here].
LESSON 6 - THE ULTRASOUNDS
In the previous Lesson we saw what sound is and how it is
generated, a vibrating body produces sound waves, the
vibration, that is, the oscillation in time of the body,
establishes what is called frequency. So Frequency can be
defined as the number of complete oscillations of the body
in the unit of time (which is the second and is denoted by
"s"). The unit of measurement of frequency is the Hertz
(Hz).
Sounds that have frequencies above 20,000 Hz, or 20 kHz,
are called "ultrasounds," and these sounds are used in
electronics in so many applications, such as in detecting the
distance of a body from the sound source.
To best understand the principle used in distance detection
using an ultrasonic signal, it is necessary to learn some
Physics.

Curiosity: what is Speed?

The speed of an object is the distance traveled by that same


object in the unit of time. So the speed of a sound wave is
the distance (which is measured in meters) traveled by that
same sound wave, in the unit of time (expressed in seconds,
"s"). Of course, there are also multiples and submultiples of
the meter and the second.
Did you know that a hare runs at an average speed of about
60 kilometers per hour (km/h), that is, in one hour the hare
covers a distance of 60 km.
A Sound Wave travels through the air at a speed of 343 m
per second (m/s), or 0.0343 cm per microsecond (cm/☐s).

HC-SR04 Ultrasonic Module. Obstacle


Distance Detection
The ultrasonic module that we will use in our projects is the
HC-SR04. The HC-SR04 is a very convenient distance
sensing sensor that is mainly used for object avoidance in
various robotics projects.
In early cars with parking sensors, it was also used in
detecting obstacles when parking and even to detect the
water level. The HC-SR04 ultrasonic sensor uses an
ultrasonic generator to determine the distance to an object
as bats do. It is a module that offers excellent non-contact
detection with high accuracy, and readings are stable.
Operation is not affected by sunlight or black objects as is
the case with laser detectors.
It is presented to consist of a base plate (which can be blue,
but I have also seen some in yellow, red, or orange), two
cylinders, which look like two eyes, an oscillator that seems
to give the two eyes a mono-eyelash, and four PINs that
look like a mustache...in fact, this module is often used in a
position that looks like a head.... For example in robot cars...
The two cylinders are for: emitting the ultrasonic signal
(cylinder indicated by "T") and receiving the signal (cylinder
indicated by "R"). For the 4 pins: to one you connect the 5V
power supply (Vcc) directly from Arduino, then there is the
ground (GND) pin and then the two pins "Trig" and "Echo"
which should be connected to two analog or even digital
pins of Arduino. One pin is for sending the sound pulse and
the other is for detecting the time the signal is received.
To explain how the module works I have to go back to the
previous physics lesson, but it is also useful for school....so
read it...
The operating principle of the Ultrasonic Module is
simple: the module emits an ultrasonic signal and
calculates the travel time (in microseconds) between the
instant of emission and the instant of reception after the
same signal bounces off the obstacle. Once the time is
measured, the distance traveled by the signal is calculated
accordingly. In fact, for example, if the travel time of the
sound wave in going to the obstacle and then returning
once it has bounced off the obstacle itself was 300
microseconds, by making the necessary equivalences, we
have that the distance traveled by the outward and return
signal is:
distance (in centimeters) = 0.0343 x time (in
microseconds)
or 0.0343 x 300 = 10 cm
Since the time is the "going" and "returning" time, obviously
the distance of the obstacle is half, so it is 5 cm.
Let us see with a graphic representation what has been
explained:

The emitter Tx sends the ultrasonic pulse, the receiver Rx


receives the pulse bounced off the obstacle. The module
calculates the elapsed time between the outward and
return, so the distance the signal travels is twice the
distance there is between the module and the obstacle,
which is why in the calculation to determine the distance
value of the obstacle must be divided by two.
So the "algorithm" to be used to determine the distance is:
Obstacle distance (in centimeters) = [0.0343 x t (in
microseconds)]: 2
After the theoretical part, we then move on to our project.
Project 19 - Detect the distance to an obstacle.

For this project we need:

Arduino Uno R3 or Breadboard Dupont male - USB connection


compatible male cables cable

HC-SR04

The wiring diagram for connection is:


While the assembly diagram is:

Trig and Echo are connected to digital PINs 10 and 9,


respectively. Although these PINs have tilde, that is, they
can be used for sending PWM signals, we will use them as
normal digital PINs.
We click on the Arduino icon and after opening a new file we
copy the sketch below:
/*
Be Maker - STEM - Project 19 - Obstacle Detection with Ultrasonic Module.
*/

const int PortaTrig = 10;


const int PortaEcho = 9;

void setup() {
pinMode(PortaTrig, OUTPUT);
pinMode(PortaEcho, INPUT);
Serial.begin(9600);
Serial.print( "Ultrasonic Sensor: ");
}
void loop() {
digitalWrite ( PortaTrig, LOW ); //sets the trigger output to a low value
digitalWrite ( PortaTrig, HIGH ); //sets the trigger output to a high value, i.e.,
sends a pulse
delayMicroseconds ( 10 ); // the high value is held for 10 microseconds
digitalWrite( PortaTrig, LOW ); //makes the pulse end i.e. puts the trigger output
at LOW
long duration = pulseIn( PortaEcho, HIGH ); //measures time
long distance = 0.0343 * duration / 2; //calculates the distance in cm
Serial.print("distance: ");
Serial.print(distance);
Serial.println(" cm ");
delay(100); //Wait 100 milliseconds before starting again
}

Once the sketch is loaded and the serial plotter is activated,


the distances of the objects in front of the sensor will be
detected

Analysis of Sketch: Project 19 -


Obstacle Detection with Ultrasonic
Module.
In the distance measurement sketch we find two new
functions.
First:
delayMicroseconds ( 10 );
this instruction introduces a delay that this time is
expressed in microseconds (classical delay, remember,
introduces delays in the sketch of milliseconds).
Second:
long duration = pulseIn(PortaEcho, HIGH );
tells Arduino to load into the variable named "duration"
defined as a variable of type "long," that is, a variable that
has many decimal places, the time value calculated from
the time the pulse starts from the Tx to the time the signal
is received by the Rx bringing the PIN state to a high state
(HIGH).
[For the video related to the project click here].
[For the sketch related to the project click here].
CURIOSITY: What are Degrees of
Freedom (DOF) and Electric Drives.

Movements, limb movements, torso rotation.... are the


movements that enable a robot to perform those activities
that we want it to do to accomplish the assigned
(programmed) task.
Let us give an example to better understand the concept of
motion by analyzing one of the most widely used robots in
industrial processes for mass production: the Puma Robot.
This robot, which is nothing more than a mechanical arm, is
widely used in the automotive industry for welding, painting,
moving heavy components, placing components in precise
locations in assemblies and storage, etc.
From this we understand how the first question we must ask
ourselves in designing a Robot is: what should our Robot
do ?
The complexity in designing a Robot lies in the number of
motions to be given and consequently the number of
"motion joints" to be inserted; in the particular case of the
figure, there are six.
But how do we determine how many joints to insert?
The answer lies in determining whether our working point
should be able to move in space, or on a plane, or a line.

Suppose a rigid body can


only translate along its axis (straight line), this possibility of
motion is called in Mechanics "degree of freedom,"
obviously the other motions that cannot be made are said to
be constrained.
Thus, in this case the motion is characterized by only one
degree of freedom.

In the case represented by the figure on the right, however,


we have that the body can translate along the abscissae
and along the ordinates, that is, it can move in a plane, so
the body is characterized by having two degrees of
freedom.

In this other case (see figure at


left) the body moves rigidly in space, so it is characterized
by having three degrees of freedom.

In Physics, but also and particularly in Mechanics, the


position in space of a rigid (solid) body can be identified by
six variables (three of translation and three of
rotation) called degrees of freedom.
Obviously reproducing by means of a single piece of
equipment the position in space of a body is impossible
(...at least with current technological knowledge), because
there are "constraints" imposed by the equipment that
generates the motion, which are normally electrical drives.
This is why the Puma Robot
has six pivot joints (six electric drives), because the
movement that enables each pivot joint, as shown in the
figure, in turn enables the working point that is at the end of
the arm, to reach "any" point in space and its relative
position is always known.

Electric drive (or also called Power Drive System: PDS) is


defined as a system that converts electrical energy into
mechanical energy with the help of power and control
electronic equipment.

The motors used for electric drives are shown in the


diagram below.Obviously, I do not wish to teach a course in
Electric Machinery, but I just wish to show you the
significant number of electric motors we have available to
us in order to give the mechanical motion we want.

After this challenging but necessary first theoretical part to


understand what and how many motors we need to make
particular movements, we move on to more practical
matters.
For our purposes and applications with Arduino we will use
two types of motors: Stepper motors and servo motors.
The Servo Motor - Giving movement
to things.
With the Servo Motor it is possible to give motion to objects,
such as a robotic arm, a lever, etc. Again, for its use, just
follow the following lesson carefully. The servo motor is
composed of an electro-mechanical part and an electronic
part, the electro-mechanical part creates the motion, the
electronic part controls it. However outwardly the servo
motor looks like a plastic shell, a gear that rotates a pin, and
a three-pin cable.

The servo motor we will use in the next project is the SG-90,
which can be powered directly from Arduino and is used for
moving light objects. As shown in the figure below, the
colored cable has three poles: one pole is connected to
Arduino's 5V Vcc voltage, another to ground (GND), and the
third pole is to be connected to an Arduino digital PIN and is
used for control.
For "heavier" applications we can use servomotors with the
commercial designation MG996R or the TD-8120MG, but in
this case, especially if they are more than one servomotor,
power must be supplied by an external power supply.
Project 20 - Controlling a Servo Motor SG-90

For this project we need:

Arduino Uno R3 Micro-servo SG90 Dupont male - USB connection


or compatible male cables cable

First we take our Arduino, servo motor, and wires and


connect them as shown in the figure below. The wiring
diagram is:
For assembly, follow the diagram below:

The Servo Motor usually has three colored leads: orange


(control lead), red (5 V) and brown (GND), in other cases,
depending on the manufacturer, the control lead is white.
We click on the Arduino icon and after opening the IDE we
create a new file and copy the sketch below:
/*
Be Maker - STEM - SG90 Servo Motor Control
*/

#include <Servo.h>//Recalls the Motor Control Library.

//Variables and functions


Servo ServoMotor; //Creates an object called ServoMotor

void setup() {
Serial.begin(9600);
ServoMotor.attach(9); //We declare that the ServoMotor is attached to PIN 9
Serial.print("SERVO MOTOR - ROTATION - ");
}

void loop() {
// Let's rotate the Servo Motor by an angle ranging from 10° to 160°.
for(int i=10;i<=160;i++) {
ServoMotor.write(i);
Serial.print("Angle: ");
Serial.print(i); //print the value of the angle
Serial.println(" °"); //print the unit of measurement, i.e. degrees
delay(30);
}
// Let's rotate the Servo Motor by an angle ranging from 160° to 10°.
for(int i=160;i>=10;i--) {
ServoMotor.write(i);
Serial.print("Angle: ");
Serial.print(i); //print the value of the angle
Serial.println(" °"); //print the unit of measurement, i.e. degrees
delay(30);
}
}
After checking the sketch let's upload it to Arduino in the
usual way and open the serial monitor, we will see the
moving part of the motor (called the rotor) rotate from 10°
to 160° and then back again, and the rotation in degrees is
shown on the monitor.

Analysis of the Sketch: Project 20 -


Controlling a Servo Motor.
Analyzing the sketch above we can observe the following
instruction:
#include <Servo.h>
That is, it calls up the library to drive the servo motor.
This library should already be installed in the Arduino IDE, in
case it is not, you can use the procedure described in the
preparatory activities for the Course.
Among the instructions that the <Servo.h> library
provides, we have the most commonly used ones:
[objectname].attach(PIN) : allows you to specify on
which pin our servo is connected and bind it to the
ServoMotor object;
[objectname].detach(PIN) : removes the link between
the ServoMotor object and the pin it was bound to;
[objectname].read(x) : reads the angular position of our
servo, returns the last value passed with write();
[objectname].write(x) : tells the servo the angle at which
to position itself;
Continuing with the analysis of the sketch...let's look at the
individual instructions in the SETUP area:
Servo ServoMotor; // .....è used to create an object named
ServoMotor
ServoMotor.attach(9); // ...we specify to the IDE that the
ServoMotor is attached to PIN 9
Turning to the LOOP part:
ServoMotor.write(i); // ....the variable "i" is the one
incremented by one by the for loop, so in this way the rotor
will turn one degree at a time.
It can be seen from the "for" loops that the first one
increments from 10 to 160 and the second one decrements
from 160 to 10.
The rest are instructions already seen in previous projects.

[For the video related to the project click here].


[For the sketch related to the project click here].
Project 21 - Radar System Ultrasound

For this project we need:

Arduino Uno R3 or Breadboard Dupont male - USB connection


compatible male cables cable
Micro-servo SG90 Bracket support Module HC-SR04

Since we will be using both the HC-SR04 ultrasonic module


and the SG-90 servomotor for this project, the ultrasonic
module should be attached to the servomotor before
proceeding. Any kind of "craft" methods can be used to do
this, or you can purchase the appropriate mounting
brackets that can be found on major market places such as
Ebay, Amazon, Aliexpress, or others..
In the case of a homemade solution, be careful not to create
a metal bracket that could short-circuit the tracks on the
ultrasonic module. I personally suggest that you purchase
the appropriate brackets for a few euros including shipping
costs.
First we take the bracket and attach, with screws, the HC-
SR04 sensor to it, and then the whole thing we attach, with
more screws, to the servo motor on which we have mounted
the intended bracket.
We take double-sided tape and make the servo motor stand
with the bracket (and sensor) mounted on it. See photo
below for assembly:

1
) + =
2 + =
)
The wiring diagram is as follows:

We make the connections as shown in the assembly


diagram:
Now let's go to the sketch, click on the Arduino icon and
after opening the IDE create a new file and copy the sketch
below:
/*
Be Maker - STEM - Project 21- Ultrasonic Radar System.
*/
#include <Servo.h>//Recalls the Motor Control Library.
Servo ServoMotor; //Creates an object called ServoMotor

//ULTRASOUND MODULE
int triggerPort = 11; //PIN to which the Trigger signal is connected
int echoPort = 10; //PIN to which the Echo signal is connected

//long s=0.0;
//long d=0.0;

void setup() {
Serial.begin(9600);
ServoMotor.attach(6); //The ServoMotor is declared to be attached to PIN 6
pinMode( triggerPort, OUTPUT );
pinMode( echoPort, INPUT );
Serial.print("MOTOR SERVO - ROTATION - ");
}

void loop() {
// Let's rotate the Servo Motor by an angle ranging from 10° to 160°.
for(int i=10;i<=160;i++) {
ServoMotor.write(i);
digitalWrite( triggerPort, LOW ); //ports the trigger output to a low value
digitalWrite( triggerPort, HIGH ); //enable trigger
delayMicroseconds( 10 ); //holds trigger active for 10 microsec (generates
pulse)
digitalWrite( triggerPort, LOW ); //deactivate the trigger
long d = pulseIn( echoPort, HIGH ); //calculates the duration of the bounce
time
long s = 0.0343 * d / 2; //calculates the distance
if (s<100){
for (int t=1;t<s;t++){
Serial.print(".");
}
for (int j=s;j<100;j++){
Serial.print("X");
}
Serial.print (" Obstacle to: ");
Serial.print(s);
Serial.print(" cm ");
Serial.print("Angle: ");
Serial.print(i);
Serial.println(" °");
}
else {
for (int t=1;t<100;t++){
Serial.print(".");
}
Serial.println(" °");
}
}
// Let's rotate the Servo Motor by an angle ranging from 160° to 10°.
for(int i=160;i>=10;i--) {
ServoMotor.write(i);
digitalWrite( triggerPort, LOW ); //ports the trigger output to a low value
digitalWrite( triggerPort, HIGH ); //enable trigger
delayMicroseconds( 10 ); //holds trigger active for 10 microsec (generates
pulse)
digitalWrite( triggerPort, LOW ); //deactivate the trigger
long d = pulseIn( echoPort, HIGH ); //calculates the duration of the bounce
time
long s = 0.0343 * d / 2; //calculates the distance
if (s<100){
for (int t=1;t<s;t++){
Serial.print(".");
}
for (int j=s;j<100;j++){
Serial.print("X");
}
Serial.print (" Obstacle to: ");
Serial.print(s);
Serial.print(" cm ");
Serial.print("Angle: ");
Serial.print(i);
Serial.println(" °");
}
else {
for (int t=1;t<100;t++){
Serial.print(".");
}
Serial.println(" ");
}
}
}

As for the analysis of the sketch, as can be observed from


the listing above, it is nothing more than a combination of
the sketches made to control the sensor and the Servo
Motor.
Now all that remains is to load the sketch and activate the
Serial Monitor and try interposing obstacles in front of the
radar to see its detection.

[For the video related to the project click here].


[For the sketch related to the project click here].
Project 22 - Ultrasonic Radar System with Processing

For the more daring, without modifying what has been


achieved in terms of hardware, there is also a version of the
same project with more attractive graphics. For this version
I had to modify a project already found on the net that uses,
in addition to the Arduino IDE, another Open Source
software called Processing.
Without going into the technical details of Processing
because there will be a Course dedicated to this other
programming environment, if you want, you can try your
hand at this project too (it is a tad more complicated than
the usual projects, but it is worth it!).
Go to the site :
https://processing.org/
The page appears to you:
Click on Download Processing and the page is accessed:
Choose the version according to your operating system (in
my case it is 64-bit Windows):
It is downloaded Processing in its latest version (in this case,
3).
Processing is an Open Source program and is therefore free,
but if you wish you can make a donation, which I
recommend, to keep it updated with new features.
The version I downloaded is processing-3.5.3-
windows64.zipper, unzip it and run the installer.
Click twice consecutively on the "processing" file and the
installation starts:
A message appears after installation saying that files
created with processing version 2 may not work, continue
and click Get Start. At this point the Processing window
opens. You can close it.
Download the files (just click on the name):
- Radar_with_Processing.zipper (file to unzip and
upload to Arduino)
- Radar_Processing_ino.zipper(file to unzip and run
on PC with Processing)
The first thing to do is to check that the settings provided on
the Radar_Processing_ino file are correct, so connect
Arduino to the PC and open the Radar_with_Processing
sketch , check which port Arduino is connected to (look at
the bottom right), in my case Arduino is connected to COM3
(see below):
Now double-click on the file: Radar_Processing_ino ,
obviously after unpacking it.
The following window opens:

Go to line #21 and check that the port number is correct, if


so change the port number (NUMBER ONLY!).

Then go to your desktop and right-click to select screen


resolution. In my case it is set to 1280 x 720 (see figure
below):
At this point return to Processing and check that the
resolution reported on line 19 is correct, if so change it,
however do not put resolutions lower than 1280 x 720! In
case your resolution is lower adjust it to that reported on
Processing.

Now load the sketch on your Arduino and after a few


seconds launch processing, clicking on the "play" button:
A real RADAR appears to you!!!

Since I think I have already stressed you enough, I'll end it


here! And see you at the next class.
[For the sketch to upload to Arduino click here].
[For the sketch to be uploaded to the PC with Processing
click here]
LESSON 7 - Active and Passive Components and
Elements in Series and in Parallel.

With this Lesson we delve into some very important aspects


of electrical engineering that will help us understand so
many things about the electrical circuits we have already
made so far.

The Active and Passive Components.


Components are the basis of electronic devices. They can
be divided into active components and passive
components. The definition of active component, or
passive component, in the bibliography (i.e., how it is
described in books) is not always clear, indeed sometimes it
is even contradictory.
As far as we are concerned, the definition that I am familiar
with and find most relevant refers to the ability to input or
use energy in a given circuit, namely:
A component is said to be ACTIVE if it feeds energy
into a circuit, while it is PASSIVE if the component
uses the energy fed into the circuit.
To give some examples: a battery is an active component
(because it inputs electricity), on the other hand, an LED
(uses electricity to emit light, but also produces heat), a
resistor (uses electricity and produces heat), a servomotor
(uses electricity and produces motion, but also produces
heat),... so, these, are all passive components.

Series and Parallel Connection of


Components.
A component is normally identified by two terminals, one
indicated by "+" and the other indicated by "-" or even
"GND," these terminals identify the conventional direction of
the current, entering from the + and exiting from the - . The
component with two terminals is called a "bipole."

Component
If we connect several bipoles together in such a way that
the incoming terminal of one connects to the outgoing
terminal of the other, we have a Series Connection.

Series Connection
In series connection, all components are passed through by
the same "I" current.
If we connect multiple bipoles by joining the "+" and "-"
terminals together, we have Parallel Connection.
Parallel Connection
In parallel connection, all components are subjected to the
same "V" voltage.

The Series and Parallel Connection of


Resistors.
For the moment let us focus on passive components, and
among them let us see in detail what happens if we connect
resistors in series or in parallel.
The linking principle is the one already described in the
previous paragraphs, so let's start right away by giving
some examples for better understanding.
First, let us review what happens if we apply a voltage V to
a resistor R:

Applying a voltage to Resistance R creates an electric


current I, which is calculated by Ohm's Law:
Suppose we now have two 100-ohm resistors connected in
series and a voltage of 5V is applied to them:

When two resistors are in series, they behave as if there is


only one "Equivalent Resistance" which is given by the sum
of the two resistances, so Req = 200 Ohm.
At this point, again using Ohm's Law, we can calculate the
current delivered by the 5V battery by applying the formula:

Going to replace the letters the numerical values:

Thus the current circulating in the circuit thus made is 0.025


A, or 25 mA.
Let us now calculate the voltage applied to the first resistor,
again using Ohm's Law:
from which:

The voltage applied to the second resistor, is calculated by


doing the difference between the total voltage applied to
both resistors, minus the voltage that is created on the first
resistor. From the calculation it turns out that there is also a
voltage of 2.5V on the second resistor. So a voltage of 2.5 V
is applied on the individual resistors, which is half the
voltage delivered by our battery.
Now suppose instead that we have the two resistors in
parallel:

In this case, the equivalent resistance of two resistors in


parallel is calculated by the formula:

from which, calculating the least common multiple and


solving the sum of two fractions:

going to replace the numerical values:


Hence:

Let us now go on to calculate the current "I" with Ohm's


Law:

So putting two equal resistors in parallel means having an


equivalent resistance equal to half the value of the single
resistor you connect in parallel. While the current will be I =
0.1 A , i.e. 100 mA ( and that is 4 times higher than in the
previous circuit).
So be careful putting resistors in parallel, you risk
burning out the components and our Arduino!
What if the resistors were different, for example, with value
R1 and R2 ? Applying the previous rule, we obtain:

However, the value that results for the equivalent resistance


is smaller than the smaller resistance value between the
two resistances. In fact, if, for example, R1 is 100 Ohms and
R2 is 10 Ohms, the Req = 9.09 Ohms.
I wanted to insist on this theoretical part, which is somewhat
tedious because of the presence of so many calculations, to
make you understand two important concepts:
1) If we put two resistors in series, the current circulating
in the circuit is reduced and a lower voltage is applied
to each resistor than it generated (in technical terms,
when current flows through a resistor, it is said to cause
a voltage drop).
In fact, the principle by which we put a resistor in series
to an LED (considering the LED as if it were a resistor,
because it has its own internal resistance) is just that,
that is, to reduce the voltage applied to the LED and
thus reduce the current flowing through it.
2) If we instead put two resistors in parallel, the voltage
applied to the resistors is still the same, i.e., that of the
battery, the value of the equivalent resistance
decreases and consequently the value of the current
delivered by the battery increases. So with Arduino we
are very careful about putting resistors in parallel,
because beyond certain current values it cannot
withstand and thus burns out.

The Voltage Divider and the


Potentiometer
In the previous Lessons we have already used both the
divider and the potentiometer, they have been used in
specific applications such as, for example, in sensing the
voltage at the ends of a photoresistor (use of the voltage
divider) or to vary the light intensity of an RGB LED (use of
the potentiometer), but we have not yet seen in detail their
actual operation and their field of use, in this Lesson, after
seeing what it means to put resistors in series and parallel,
we will delve into these aspects.

The Voltage divider


Sometimes it happens that we need to create reference
voltages for electrical measurements, as was the case with
the photoresistor. To do this we need only apply two very
important laws of electrical engineering, one you know well
by now and that is Ohm's law, which tells us that by
applying an electric voltage to a resistor, it is passed
through by an electric current given by the formula :
Or, interpreting the law in reverse: a current "I" flowing
through a Resistance "R" produces a "voltage drop V" , that
is:

This principle of producing a voltage drop is used to create a


reference voltage in electrical measurements. For example,
suppose we want to create a reference voltage of 2.5 V from
a Voltage of 5 V, then (without going through all the
calculations we have seen before), all we need to do is to
put two resistors in series of equal value (e.g., 100 Ohm)
and the reference voltage at the ends of one of the resistors
is exactly 2.5 V.

The voltage at the ends of R remains constant at 2.5 V only


if we read it with an instrument called a voltmeter or with
Arduino (for example: by means of one of its analog PINs),
but if we want to use this voltage to supply a 2.5 V load, the
value at the ends of R will change, depending on the load
we are going to connect (in parallel with R!).

The Potentiometer (for electronic


applications it is called a Trimmer).
The working principle of a potentiometer is equivalent to a
voltage divider, with the special feature that thanks to a
knob it is possible to change the resistance and thus change
the voltage at the central point.

- Black Element = wire of definite characteristics and


resistivity wrapped on insulating material and is called
Fixed Resistance.
- Green element = slider made of conductive material
and is the sliding contact that rotates due to the
knob.
Basically, by varying the position of the center slider with
the knob, all we are doing is increasing the length of the
wire over which the current circulates and thus the
resistance of the conducting material, which is given by the
following formula:

Where R is the resistance," r " (pronounced "ro' ") is the


resistivity of the material that makes up the wire wrapped
on the insulating material," l " is the length and " s " is the
cross section of the wire wrapped on the insulating material.
The potentiometer when applied in low-power circuits, such
as those we have made, takes the name of Trimmer, so
between Trimmer and Potentiometer there are no
substantial differences in their principle of operation, but
only constructive ones and thus in the ability to be able to
be traversed by currents with higher values, for the
potentiometer, than lower ones for the trimmer.
Thus the potentiometer is used in higher power circuits than
those for which the trimmer is used.

example of Trimmer
Project 23 - The Use and Connection of the
Potentiometer

To understand in detail how a Potentiometer works and one


of its most usual applications, let us carry out the following
project. For this project we need:

Arduino Uno R3 or Breadboard Dupont male - USB connection


compatible male cables cable

2x 220 Ohm LEDs of any color 10 KOhm


Resistors potentiometer

The purpose is to change the voltage applied to an LED,


thanks to the potentiometer, and then vary the brightness
manually by acting on the knob of the same potentiometer.
To realize this effect, based on the knowledge we have
gained so far, we can make the following circuit:

As can be easily observed from the wiring diagram, in this


case Arduino is used as a simple 5 V battery. The assembly
diagram is as follows:
Pin one of the potentiometer is connected to the Arduino's
5V, from pin two we go to connect the anode of the LED
(yellow) to which the classic 220 Ohm resistor has been
connected in series. Finally, the third pin of the
potentiometer is connected to ground (GND) through a 220
Ohm resistor.
By varying the resistor, that is, by turning the knob on the
potentiometer, you will be able to see the brightness of the
LED vary; in fact, in this way, we have placed another
resistor of varying value in series with the LED resistor; the
higher the resistor the higher the voltage drop across the
resistors and thus the lower the voltage applied to the LED
and thus the lower the brightness.
I would like to point out that in series with the third pin of
the potentiometer, before connecting the same to ground, I
have inserted a 220 Ohm resistor, this is because the
Potentiometer having a variable resistance (theoretically
from 0 to 10 kOhm, or from 0 to 1 kOhm, depending on the
type of potentiometer we use), for low values of resistance
Arduino would deliver high currents with the risk of burning
it out, instead, by putting a resistor in series, however even
when the potentiometer takes low values, we are limiting
the current delivery.

[For the video related to the project click here].


Fun facts: what is Temperature and
what is Humidity

Temperature is that quantity that indicates the thermal


state of a body or environment, that is, how hot or how cold
that particular body or environment is. The unit of
measurement is the degree Celsius [°C] or rather, in the
International System, it is measured in degrees Kelvin [°K].
Humidity is that quantity that indicates how much water
vapor is present in a given environment and is measured in
percentage terms. At 0% humidity, one has a dry and
ascetic environment. A '100% humidity , in practice, you are
immersed in water vapor.
LM35 Temperature Sensor
For the following project we will use the LM35 temperature
sensor, let's give a brief description of it:
The sensor is calibrated to give results in °C , so if we want
°K we need to convert it with the formula that says: 0 °K =
-273.1 °C, that is, if we have 27.9 °C, these correspond to
300 °K. The applicable voltage ranges from 4 V to 30 V, but
we will obviously use it at 5V. For every 10 mV measured,
we have 1 °C. Since the function is linear, as can be seen
from the data-sheet graph, we only need to measure the
output voltage Vout with Arduino and apply the simple
formula:

Project 24-Detect the temperature of a body.

For this project we need:


Arduino Uno R3 Breadboard Dupont male - USB connection
or compatible male cables cable

LM35

The wiring diagram for connection is:

While the assembly diagram is:


We click on the Arduino icon and after opening a new file we
copy the sketch below:
/*
Be Maker - STEM - Body Temperature Sensing with LM35
*/
#define sensorPin A0 //define which Analog PIN I connected the sensor to.

void setup() {
Serial.begin(9600); //We set the port speed to 9600
}
void loop() {
int reading = analogRead(sensorPin); // Get a reading from the temperature
sensor
float voltage = reading * (5000 / 1024.0); // Convert the reading into voltage
float temperature = voltage / 10; // Convert the voltage into the temperature in
degree Celsius
Serial.print(temperature); // Print the temperature in the Serial Monitor
Serial.println(" °C");
delay(1000); // wait a second between readings
}

Once the sketch is loaded and the serial monitor is


activated, the temperatures of the objects that are in
contact with the sensor will be detected. As far as the
sketch is concerned, since there are no special things to
highlight, no analysis is done.
[For the video related to the project click here].
[For the sketch related to the project click here].
Project 25 - Light thermometer.

Based on the previous project, let's make a fun light


thermometer where we will use a decision-making algorithm
based on the "switch-case" function to determine whether a
body is: cold, room temperature, hot, or burning hot.
For this project we need:

Arduino Uno Breadboard Dupont male - USB connection


R3 or male cables cable
compatible

LM35 No. 4 LEDs: Blue, No. 4 220 Ohm


Red, Green and resistor
Yellow

The wiring diagram for connection is:


While the assembly diagram is:

We click on the Arduino icon and after opening a new file,


we copy the sketch below:
/*
Be Maker - STEM - Luminous Thermometer
*/
#define sensorPin A0 //define which Analog PIN I connected the sensor to.
#define scottaPin 3 //define at which PIN Digital LED Red
#define warmPin 4 //define at which PIN Digital LED Yellow
#define environmentPin 5 //define at which PIN Digital LED Green
#define coldPin 6 //define at which PIN Digital Blue LED.
int ignitionLED;

void setup() {
pinMode(scottaPin, OUTPUT);
pinMode(hotPin, OUTPUT);
pinMode(environmentPin, OUTPUT);
pinMode(coldPin, OUTPUT);
Serial.begin(9600); //We set the port speed to 9600
}
void loop() {
int reading = analogRead(sensorPin); // Get a reading from the temperature
sensor
float voltage = reading * (5000 / 1024.0); // Convert the reading into voltage
float temperature = voltage / 10; // Convert the voltage into the temperature in
degree Celsius
Serial.print(temperature); // Print the temperature in the Serial Monitor
Serial.println(" °C");
delay(1000); // wait a second between readings

if (temperature<=10){lightingLED=0;}
if (temperature>10 && temperature<=27){lightingLED=1;}
if (temperature>27 && temperature<=36){lightingLED=2;}
if (temperature>36){lightingLED=3;}

switch (ignitionLED) {
case 0:
digitalWrite(scottaPin, LOW);
digitalWrite(hotPin, LOW);
digitalWrite(environmentPin, LOW);
digitalWrite(coldPin, HIGH);
break;
case 1:
digitalWrite(scottaPin, LOW);
digitalWrite (hotPin, LOW);
digitalWrite(environmentPin, HIGH);
digitalWrite(coldPin, LOW);
break;
case 2:
digitalWrite(scottaPin, LOW);
digitalWrite(hotPin, HIGH);
digitalWrite(environmentPin, LOW);
digitalWrite(coldPin, LOW);
break;
case 3:
digitalWrite(scottaPin, HIGH);
digitalWrite(hotPin, LOW);
digitalWrite(environmentPin, LOW);
digitalWrite(coldPin, LOW);
break;
}
}

At this point we load the sketch on Arduino and with the tip
of the sensor touch the different bodies to measure their
temperature. Depending on the measured temperature
range, a particular colored Led will light up: Blue Led = cold,
Green Led = room temperature, Yellow Led = hot, or Red
Led = hot. We can enrich the design by also putting a card
with holes for the LED head and on the card write the
measured temperature range.
Analysis of the Sketch: Project 25 -
Luminous Thermometer.
Also used for this sketch was the control structure switch(..)
..... case ... ; which we review as being a very important
structure.
This way of having the processor make decisions is used
especially when there are many cases to examine and
decide on which actions to take. The use of the
switch...case... simplifies the structure, in fact it is enough
to define for each case what to do and then we have the
switch function do the case selection directly. The general
syntax of the control structure according to the Arduino
Reference Book is:
switch (var) {
case label1:
// statements
break;
case label2:
// statements
break;
default:
// statements
break;
}
Where var is a variable of type int or char and indicates the
number of the "case" you want to process, and label1 is the
label, also a variable of type int or char. In the syntax
example there are only three cases of which one is the
default. The last case, the default case is selected when you
have none of the previous cases. The structure can also
have more than the represented number of cases.
[For the video related to the project click here].
[For the sketch related to the project click here].
The DHT11 Environmental
Temperature and Humidity Sensing
Sensor.

Sometimes there is a need to detect the Temperature and


Humidity present in a room and according to these values it
is possible to adjust the heating or air conditioning so that
what is called the "optimal thermal comfort" of the room is
achieved.
The DHT11 sensor is nothing more than a mini-arduino
where thanks to its sensors and the presence of a processor
it is able to provide, in digital format, the value of
temperature and humidity.
Why did I want to specify this aspect? The reason is that,
like Arduino, the DHT11 having a processor and sensors, in
turn, would require specific programming and also in a
particularly complicated language effectively making the
use of the DHT11 only for a select few. Instead, thanks to
the presence of millions of makers like you, the use of the
DHT11 sensor module is very simple as there are "Libraries"
of instructions thanks to which we are able to interrogate
the sensor module without worrying about writing hundreds
of lines of program code in a complex language.
Let us now see how to connect the DHT11 Sensor Module:

As you can see, the Module has the third pin from the left
that has no function and therefore should not be connected
to anything.
A 4.7 kOhm resistor is normally connected between the Vcc
pins and Data:

Be aware that there are commercially available DHT11


Sensor Modules, mounted on a baseplate, with the 4.7
kOhm resistor already connected and, most importantly,
with only the 3 PINs needed.

Before moving on to the hands-on project, let's review how


to add in the Arduino IDE a library, although it is already
explained in the preparatory activities for the Course I still
think it is useful to refresh the memory.

What is a Library and how to add it to


the IDE
The concept of a "library" is basically this.... It is a repository
in which you find instructions that simplify and make it
easier to use modules and sensors that would otherwise
require complex operations and instructions that are
difficult to apply.
Let's see how to add the DHT11 Sensor Library; there are
several ways to insert a library into the Arduino IDE, the one
we will use is the easiest and quickest, but be aware that it
will not always be possible to use this method... but don't
worry we will see them all when needed!
Back to us: inserting a new library into the Arduino IDE and
then allowing the IDE itself to load into Arduino the right
instructions needed for Arduino and the add-ons that
connect to it to work.
First we open the application, double-click on the Arduino
icon on the Desktop, and the IDE opens:
Since when you open the IDE generally the last sketch you
wrote is loaded, let's start with a clean sketch so there is no
confusion.To do this we click on "File" and then on "New," as
depicted above. At this point we can close the initial window
where the previous sketch was.
Now we click on "sketch" then on "#include library" and
then on "Manage libraries..."
After a few seconds, the following window appears and we
go to type in the text box "DHT11"
A list of libraries comes up, we select the one produced by
Adafruit...

...and click on "Install."


After a few seconds, the window that says "INSTALLED"
appears. The library is now usable and when compiling the
sketch for Arduino, the IDE will not give an error.
Project 26 - Ambient Temperature and Humidity.

For this project we need:

Arduino Uno R3 or Breadboard Dupont male USB connection


compatible - male cables cable
DHT11 Sensor
Module

The wiring diagram for connection, in the case of using the


sensor, is:

In the case of using the Sensor Module:


For the mounting diagram in the case of using the 4 PIN
sensor:

In the case of using the Sensor Module with 3 PINs):


Caution: Since there is no standard, pay attention to which
PIN is assigned the "S" or "DATA" symbol, as well as the one
with the "+" or "Vcc" symbol where they will connect to
Digital PIN 4 and Arduino's 5V, respectively.
The sketch to be written (directly taken from the example in
the Library):
// Example testing sketch for various DHT humidity/temperature sensors
#include "DHT.h"

#define DHTPIN 4 // Digital pin connected to the DHT sensor


#define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE);

void setup() {
Serial.begin(9600);
Serial.println(F("DHT11 Start"));
dht.begin();
}
void loop() {
delay(2000); // Wait a few seconds between measurements.

float h = dht.readHumidity();
float t = dht.readTemperature(); // Read temperature as Celsius (the default)

Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
}

Then, once the sketch is loaded and waiting a couple of


seconds, the Serial Monitor prints the values.

Sketch Analysis: Project 26-


Environmental Temperature and
Humidity.
It is worth highlighting, because it is very important, the
inclusion of the Library with the command "#include"
#include "DHT.h"
You also need to specify which sensor you are using
because the same library contains multiple types of sensors,
so you need the instruction:
#define DHTTYPE DHT11 // DHT 11
and then the creation of an object called dht is needed:
DHT dht(DHTPIN, DHTTYPE);
from that moment in the void loop(), we can put the
instructions that go to read the digital values of
temperature and humidity.
[For the video related to the project click here].
[For the sketch related to the project click here].
LESSON 8 - Magnetism and the Magnetic Field.

We dedicate this Lesson to the study of the Magnetic


Field. This is an important and challenging subject, so I
realize that it may be a difficult topic for younger people. I
will try to explain it as simply as possible, but if I fail to do
so--don't worry! Just go ahead anyway.
Let us first define what magnetism is: that is, that
property that some bodies possess in attracting
objects of a ferrous nature to themselves.
Bodies with this property are called magnets or magnets.
Magnetite, an iron ore, is an example of a natural magnet. A
magnet attracts ferrous bodies at its ends, which are called
magnetic poles. These two poles are not equal and are
distinguished into north pole (N) and south pole (S). Poles of
the same type (N-N and S-S) repel each other and poles of
the opposite type (N-S and S-N) attract each other.

The poles of a magnet can never be separated; if you split a


magnet it will restore the poles as they were in the original
dimension.
The magnetic field, in physics, is defined as follows: the
magnetic field is a vector field, capable of passing
through bodies, generated in space by the motion of
an electric charge or a time-varying electric field. Let
us try to decipher what physics says in simpler terms. So,
we have materials that are normally magnetized and
materials that can become magnets if a current flows
through them.
First, let us see why physics speaks of a "vector field." The
magnetic field is called "vector" because its lines of force,
that is, the areas of influence, have a definite direction. In
the case of a magnet made by the circulation of current, the
magnetic field produced depends on the direction in which
the electric current is circulating. In the case of permanent
magnets, on the other hand, the lines of force go from the
North Pole to the South Pole of the magnet. In the field of
electronics and electrical engineering, the magnetic field
generated by an electric current is that phenomenon most
widely used for a wide variety of purposes.
The area of influence of the magnetic field is the space in
which we can observe the phenomenon of magnetism.
Obviously, the closer we are to what produces the magnetic
field, whether it is a material through which the current
flows or a permanent magnet, the greater the effect of that
field.
It is also possible to do a very simple experiment to
visualize the force lines of the magnetic field produced by a
permanent magnet. Just take a smooth, white cardboard
and cover (dust) it with iron filings (iron filings are the waste
from ironworking; they are very small iron needles, they
look like many straws). When a magnet is placed, a magnet
is placed under the card; by giving gentle shakes to the
card, the iron filings, magnetized, are arranged along the
lines of force of the magnetic field, composing the pattern
of the projection on the plane of the same lines of force.
The Earth also has its own Magnetic Field, and several
physicists and scholars think it is due to the large amount of
iron and nickel in the core (other theories, however, say that
the magnetic field generated by the Earth is electrical in
nature). However, you have surely had occasion to see a
compass whose needle aligns with the lines of force of the
Earth's magnetic field indicating its magnetic North Pole,
which is slightly different from the geographic North Pole.

As I mentioned earlier, in electrical engineering and


electronics the phenomenon of magnetism is widely used, in
fact in this Lesson we will look at some projects that use this
phenomenon to regulate certain events. The principle used
is the so-called "Hall effect."
Curiosity: The Hall Principle
To measure the Magnetic Field, the so-called Principle of
Edwin Hall, an American physicist, is used, who noted that if
we run a metal (or semiconductor) foil through a direct
current between the " + " and " - " terminals and this foil is
immersed in a magnetic field, the flow of the current (or
rather electrons) is deflected and thus a buildup of charges
is created toward the outer edges of the foil, such that a
measurable potential difference (Hall voltage) is created
between the "a" and "b" terminals. This buildup is the
greater, the larger the magnetic field and consequently the
voltage at the ends of terminals "a" and "b" will be higher.
The signs of Hall voltage depend on the magnetic
polarization and the voltage applied to the foil.

This principle has several applications especially in


mechatronics, in fact exploiting the principle that the
magnetic field is influenced by the type of material in which
it is applied, we can, thanks to the Hall probe, measure its
variations. Thanks to these variations we can check whether
a ferrous product (e.g. from a rolling mill) has been made
correctly (no field variation), or count the number of
revolutions of a crankshaft, etc.
For example, the figure above shows a measuring system,
without contact with the moving part, for measuring the
speed of a rotating disk or the number of revolutions of a
gear, even when these moving parts are inside plastic or
metal enclosures
Another example of a Hall probe application is shown in the
figure below:

Current measurement system without contact with the live


part. This method takes advantage of the principle that an
electric current produces a magnetic field, so by measuring
the magnetic field we can measure electric current without
making contact with the live part.
Project 27 - Magnetic Field Presence Detection -
KY003

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

Hall Effect Sensor


Module - KY003

Hall Effect Sensor Module - KY003 consists of a


component that is sensitive to the effects of the magnetic
field (whose name is unspeakable! a series of meaningless
numbers and letters... ) and the characteristics indicated by
the manufacturer, works well even at high temperatures.
There is a 680-ohm resistor on the module and an LED that
activates when a magnetic field is present.

At the PIN indicated with S the signal is available that will go


to a digital PIN of Arduino, at the PIN indicated with "-" the
GND of Arduino needs to be connected and at the PIN with
"+" or nothing is indicated, or even indicated with Vcc, the
5V power supply from Arduino needs to be given.
The wiring diagram for connection is:
First we take our Arduino, some Dupont male-female leads,
and the sensor, which in English is called the Hall Magnetic
Sensor.
We connect everything as per the assembly diagram below:

Signal PIN "S" is connected to digital PIN 3 of Arduino, and


for the rest just connect the power supply to 5V and ground
to GND of Arduino.
We open the IDE and after opening a "New" window, copy
the sketch below:
/*
Be Maker - STEM - Magnetic Field Detection Switch Sensor
*/

int Led = 13; //LED present on Arduino


int sensor = 3; //PIN to which the sensor signal is connected
int val; //numeric variable

void setup()
{
pinMode(Led, OUTPUT); //set the LED as the OUTPUT
pinMode(sensor, INPUT); //set sensor PIN as INPUT
}

void loop()
{
val = digitalRead(sensor); //The sensor output is read.
if(val == LOW) //If the value of the sensor signal is "LOW"
//then the magnetic field is present and the LED
//on Arduino is turned on
{
digitalWrite(Led, HIGH);
}
else
{
digitalWrite(Led, LOW);
}
}

You upload the sketch to Arduino and at this point, by


moving a magnet near the sensor you can observe that the
LED at PIN13 turns on and off, this depending of course on
the distance between magnet and sensor. When the
magnetic field is strong enough to be detected by the
sensor the LED at PIN 13 on the Arduino will turn on, the
LED located on the module will also turn on (but not all
modules report such an LED).

Analysis of Sketch: Project 27 - Use of


LED on board Arduino.
Sometimes in order not to stand around mounting an LED
and a resistor to check the functionality of a particular
circuit or module, it is possible to use an LED that Arduino
makes available to users. Such an LED is connected to
digital PIN 13, and to be used it must be configured as if
there were an external LED connected to PIN 13.
So it must be defined to which PIN the LED is connected:
int Led = 13; //LED present on Arduino
In the void setup, it should be specified that it is a PIN
output:
pinMode(Led, OUTPUT); //set the LED as the OUTPUT
And finally it should be turned on or off with any LED:
digitalWrite(Led, HIGH);

Most Arduino clones also carry such an LED.


[For the video related to the project click here].
[For the sketch related to the project click here].
Project 28 - Analog Detection of a Magnetic Field -
KY035

With the KY-035 Analog Hall magnetic sensor module, it is


possible to continuously detect the magnetic field since it is
a sensor module that has an analog output.
For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable
Hall Effect Sensor
Module - KY035

Module KY035 has the same pinout as KY003, the only


difference being that at the PIN marked "S" is the analog
signal and not just the ON/OFF of KY003.
The wiring diagram for connection is:

We take our Arduino, some Dupont male-female leads, and


the sensor,
For this project we assemble the circuit as the previous one
with the only difference being that the signal output is taken
to an analog PIN, specifically, in our case, to PIN number A5.
We open the IDE and write the sketch below.
/*
Be Maker - STEM - Analog Magnetic Field Measurement
*/
int sensorPin = A5; // The sensor signal is connected to the analog PIN A5
int sensorValue = 0; // variable in which we store the value received from the
sensor

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

void loop () {
sensorValue = analogRead(sensorPin);
delay(sensorValue);
Serial.println (sensorValue, DEC); // you can graph the results using the serial
plotter
}

Again, once the sketch is uploaded to Arduino, moving a


magnet near the sensor allows us to observe the change in
magnetic field strength, and thanks to the "Serial Plotter"
feature of the IDE, we can also get a plot of the value of the
same magnetic field it has as a function of distance.
To activate the Serial Plotter, go to "Tools" and then click on
"Serial Plotter."

[For the video related to the project click here].


[For the sketch related to the project click here].
Curiosity: The Metal Detector

The operating principle of a Metal Detector is very simple;


we have said that a current produces a magnetic field, and
if this current varies over time, the magnetic field produced
will also vary over time.
In 1834 the Russian physicist Emil Lenz discovered that by
subjecting a conducting material (such as metals are, for
example) to a time-varying magnetic field, an electric
current is produced on it, which in turn produces a magnetic
field that goes against the one generating the current (the
so-called Lenz's Law). Thus, a metal detector, thanks to a
coil run through by a varying current, produces a varying
magnetic field, consequently on the metal that is perhaps in
the ground, a counter magnetic field is produced, and then
it is enough to detect that counter magnetic field that the
metal we are looking for is found.
The more time-varying the magnetic field, the greater the
strength of the magnetic field induced in the metal we are
searching for, and thus the greater the depth of
investigation in the ground we can perform. In this way
metal objects are found, remediation of ordnance is carried
out,.... TREASURES are found!
With the knowledge gained in this lesson we are able to
build ourselves a seeker...magnets!
Project 29 - Magnetic Detector with the Linear
Magnetic Hall Sensor KY024.

For this project we will use neither sensor module KY003 nor
KY035, but sensor module KY024, which is the Linear
Magnetic Hall Sensor. This module differs from the first two
because it has both functionalities, that is, it has an analog
output and a digital output:

The PIN labeled A0 is the analog output, the PIN labeled D0,
on the other hand, is the digital output, while the PIN
labeled G stands for Ground and the PIN labeled "+" stands
for the power supply (at 5 V).
The module also has a trimmer that can be adjusted to
adjust the sensitivity of the sensor and thus the threshold
value for turning on the LED. There are two LEDs on the
module, one is lit when the module is powered and the
other when there is the presence of a magnetic field.
For this project we need:

Arduino Uno R3 or Breadboard Dupont male USB connection


compatible - male cables cable

Hall effect linear Active buzzer


sensor module -
KY024

The wiring diagram is as follows:


So we proceed to the connections as shown in the diagram
below:
We open the IDE and write the sketch below.
The following Arduino sketch will read values from both the
digital and analog sensor interfaces. The digital interface
will turn on the LED at Arduino PIN 13 when a magnetic field
is detected and will emit a sound from Buzzer.
The analog interface starts from an initial value determined
by the input voltage (adjusted by the trimmer), this value
will increase or decrease depending on the strength and
polarity of the magnetic field. For better graphical
representation, the initial value is set to zero.
Try moving the magnetic detector near a magnet to see its
effect and through the trimmer adjust it accordingly.
We always use the Serial Plotter to get the graphical
representation of the values.
/*
Be Maker - STEM - Linear Analog-Digital Magnetic Field Sensor
*/
int ledPin = 13 ; // at PIN 13 the LED on the Arduino
int digitalPin = 3; // at PIN 3 of the Arduino there is the digital signal
int buzPin = 8; // at PIN 8 of Arduino there is active buzzer
int analogPin = A0; // at PIN A0 of Arduino there is the analog signal
int digitalVal ; // reading the digital value
int analogVal = 0; // reading the analog value

void setup ()
{
pinMode (ledPin, OUTPUT);
pinMode (buzPin, OUTPUT);
pinMode (digitalPin, INPUT);
pinMode(analogPin, INPUT);
Serial.begin(9600);
}

void loop ()
{
digitalWrite (ledPin, LOW); //holds off the LED at PIN 13 on Arduino
digitalWrite(buzPin, LOW); //keeps the buzzer off
digitalVal = digitalRead(digitalPin) ; // Reads the digital interface
if(digitalVal == HIGH) //If the value of the sensor signal is "HIGH"
//then the magnetic field is present and the LED
//on the Arduino is turned on and the Active Buzzer is
powered
//then the value of A0 is read and printed
{
digitalWrite(ledPin, HIGH);
digitalWrite (buzPin, HIGH);
analogVal = analogRead(analogPin);
Serial.println (analogVal, DEC);
delay (analogVal);
}
else
{
digitalWrite(ledPin, LOW);
digitalWrite(buzPin, LOW);
analogVal = 0;
Serial.println (analogVal, DEC);
delay (300);
}
}

Analysis of the Sketch: Project 29 -


Magnetic Detector.
The only observation, worthy of the name, to the sketch
concerns the analogRead () instruction, which will
automatically set analog PIN A0 as INPUT , so the instruction
pinMode(analogPIN, INPUT) can also be omitted, but for
teaching reasons I have reported it anyway, that instruction,
to avoid confusion.
In addition, as you can see from the decision logic set with
the if and else, if the magnetic field value is low (less than
the threshold level adjusted with the trimmer), I forcibly set
the analog signal readout variable to 0 and keep Led and
Buzzer off.
Of course, this logic can be modified at will.
[For the video related to the project click here].
[For the sketch related to the project click here].
LESSON 9 - The Display for Arduino

This Lesson we devote it to the immense world of displays


that can be used with Arduino, obviously we will focus on
those that actually turn out to be important to know from
the point of view of the number of possible applications and
we will leave out, at least for the moment, those that
instead have specific uses or those that are particularly
expensive.
First, let's figure out when we need a display: the answer is
simple! all those times when we need immediate return
information, from the Arduino, that would otherwise require:
connection with a USB cable, the availability of a PC, etc.
For example, when we are monitoring a quantity, or when
we want a status of a PIN... of course, I am not referring to
the debugging phase, because in that case I can safely use
the Serial Monitor or Serial Plotter that the IDE provides us
with, but for example, when to have constantly under
control the temperature of an environment, the voltage at
the ends of a component, etc....
7-segment LED display.

As the name also implies, the display consists of 7 LED


segments that are individually activated to dial the digit
(i.e., single number) we wish to show. This type of display is
used for countdown (starting with 9, of course), to indicate
the status of a PIN, to indicate whether or not a process has
been successful, etc.
Since the segments are LEDs in their own right, they follow
the normal LED rules when powered by Arduino, that is,
they should be protected with 220 W resistors. Remember
also that inserting resistors in series with the LEDs reduces
the current delivered by the Arduino while preserving their
functionality.
The Display features the following pinout with the
corresponding segment identification:
The display can be of the "common cathode" type, then
GND will go to the common (DC) and the individual PINs
must be placed in the HIGH state to make the relevant LEDs
light up, or, on the contrary, for the common anode version,
voltage to 5V must be brought to the common (AC) PIN and
the individual PINs, must be placed in the LOW state to
make the relevant LEDs light up.

Project 30 - Let's Make a Countdown.


For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

7segment LED No. 8 220 W


display (common resistors
cathode)
The wiring diagram is as follows:

R resistors are 220 W .


The assembly scheme to be carried out is as follows:
Note: The common PIN is connected to the Arduino GND
because a "common cathode display" is being used.
Once the circuit is assembled, the sketch to be written and
uploaded to Arduino is:
/*
BE MAKER - STEM - Project No. 30 - Countdown with 7-segment led display
*/
// set the IO pin for each segment
int a=11;// set digital pin 7 for segment a
int b=10;// set digital pin 6 for segment b
int c=5;// set digital pin 5 for segment c
int d=6;// set digital pin 10 for segment d
int e=7;// set digital pin 11 for segment e
int f=8;// set digital pin 8 for segment f
int g=9;// set digital pin 9 for segment g
int dp=4;// set digital pin 4 for segment dp

void digital_0(void) // display number 0


{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_1(void) // display number 1
{
digitalWrite(a,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_2(void) // display number 2
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,LOW);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,LOW);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_3(void) // display number 3
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_4(void) // display number 4
{
digitalWrite(a,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_5(void) // display number 5
{
digitalWrite(a,HIGH);
digitalWrite(b, LOW);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e, LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_6(void) // display number 6
{
digitalWrite(a,HIGH);
digitalWrite(b, LOW);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_7(void) // display number 7
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
}
void digital_8(void) // display number 8
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void digital_9(void) // display number 9
{
digitalWrite(a,HIGH);
digitalWrite(b,HIGH);
digitalWrite(c,HIGH);
digitalWrite(d,HIGH);
digitalWrite(e,LOW);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
}
void setup()
{
int i;// set variable
for(i=4;i<=11;i++)
pinMode(i,OUTPUT);// set pin from 4 to 11 as "output"
}
void loop()
{
while(1)
{
digital_9();// display number 9
delay(1000); // wait for 1s
digital_8();// display number 8
delay(1000); // wait for 1s
digital_7();// display number 7
delay(1000); // wait for 1s
digital_6();// display number 6
delay(1000); // wait for 1s
digital_5();// display number 5
delay(1000); // wait for 1s
digital_4();// display number 4
delay(1000); // wait for 1s
digital_3();// display number 3
delay(1000); // wait for 1s
digital_2();// display number 2
delay(1000); // wait for 1s
digital_1();// display number 1
delay(1000);// wait for 1s
digital_0();// display number 0
delay(1000);// wait for 1s
}
}
Starting the sketch, the display will illuminate the digit nine
and after every second, it will decrease by one until it
reaches zero and start again.

Analysis of the sketch: Project 30:


Let's make a Countdown.
There are no special things to report in this sketch even
though it is very long. In fact, the many sketch lines written
are only to drive the 7 LED dialing seeds individually and
nothing else.
It should be remembered that in case we had a Common
Anode display, then those that are PINs with HIGH status
would be PINs with LOW status and vice versa.

[For the video related to the project click here].


[For the sketch related to the project click here].
4-digit 7-segment LED display.

The 4-digit 7-segment LED display functions quite similarly


to the one seen in single digits, the only difference being
that in addition to the PINs that turn on the individual LED
segments, there are an additional 4 PINs to the display that
are used to enable the reference digit.
The diagram of the display with the various PINs is as
follows:
The PINs named A, B, C, D, E ,F and G are the ones that turn
on the segment LEDs, the PIN named dp is the one that
turns on the dot LED, and the ones named D1, D2, D3 and
D4, are the ones that turn on the single digit. Obviously,
since we could only drive one digit at a time in this way, in
case we wanted to represent a two-digit or multi-digit
number, we would always have the individual digits light up
one at a time, but at such a speed that to our eyes it would
appear to be the two, or three, or four digits lit up at the
same time...cartoon style made by quickly scrolling through
the pages of individual drawings.
These displays can also be found in the market in the
Common Cathode type, or Common Anode type. In the case
of the Common Cathode display, then D1, D2, D3, and D4
are placed in the state of LOW (one at a time) and PINs A, B,
C, D, E ,F, and G (and dp, if dot is to be used), are placed in
the state of HIGH.
In the case of Common Anode displays, exactly the opposite
occurs.
Project 31 - Seconds counter.

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

4 digit 7 No. 8 220 W


segment LED resistors
display
(common
cathode)
The wiring diagram is as follows:
The diagram below should be followed for assembly:

After the connections we move on to writing the sketch.


Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.
A blank window opens, or a new blank window needs to be
opened and we write the sketch below:
/*
BE MAKER - STEM - Project 31 - SECONDS COUNTER.
*/
// If the Display is Common Cathode
#define DIGIT_ON LOW
#define DIGIT_OFF HIGH
#define SEGMENT_ON HIGH
#define SEGMENT_OFF LOW
// If the Display is Common Anode
// #define DIGIT_ON HIGH
// #define DIGIT_OFF LOW
// #define SEGMENT_ON LOW
// #define SEGMENT_OFF HIGH
// PIN variables definition second link
int segE = 8;
int segD = 7;
int segDP = 5;
int segC = 6;
int segG = 12;
int digit4 = 1;
int digit1 = 4;
int segA = 10;
int segF = 11;
int digit2 = 3;
int digit3 = 2;
int segB = 9;

#define DISPLAY_BRIGHTNESS 20000


#define OFF 10 //Case no. 10 all segments off.

void setup()
{
// Set all PINs to OUTPUT
pinMode(segA, OUTPUT);
pinMode(segB, OUTPUT);
pinMode(segC, OUTPUT);
pinMode(segD, OUTPUT);
pinMode(segE, OUTPUT);
pinMode(segF, OUTPUT);
pinMode(segG, OUTPUT);
pinMode(segDP, OUTPUT);
pinMode(digit1, OUTPUT);
pinMode(digit2, OUTPUT);
pinMode(digit3, OUTPUT);
pinMode(digit4, OUTPUT);
// All digits set to off
digitalWrite(digit1, DIGIT_OFF);
digitalWrite(digit2, DIGIT_OFF);
digitalWrite(digit3, DIGIT_OFF);
digitalWrite(digit4, DIGIT_OFF);
}

void loop()
{
displayNumber(millis()/1000);
}

void displayNumber(int toDisplay)


{
for (int digit = 4 ; digit > 0 ; digit--)
{
if (digit==4)
digitalWrite(digit4, DIGIT_ON);
else if (digit==3)
digitalWrite(digit3, DIGIT_ON);
else if (digit==2)
digitalWrite(digit2, DIGIT_ON);
else if (digit==1)
digitalWrite(digit1, DIGIT_ON);

ShowNumber(toDisplay % 10);
delayMicroseconds(DISPLAY_BRIGHTNESS);
ShowNumber(OFF);
toDisplay /= 10;
digitalWrite(digit1, DIGIT_OFF);
digitalWrite(digit2, DIGIT_OFF);
digitalWrite(digit3, DIGIT_OFF);
digitalWrite(digit4, DIGIT_OFF);
}
}

// Segment management by number dialing


void ShowNumber(int n)
{
switch (n)
{

case 0:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_OFF);
break;

case 1:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 2:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 3:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_ON);
break;

case 4:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;
case 5:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 6:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 7:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;

case 8:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_ON);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 9:
digitalWrite(segA, SEGMENT_ON);
digitalWrite(segB, SEGMENT_ON);
digitalWrite(segC, SEGMENT_ON);
digitalWrite(segD, SEGMENT_ON);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_ON);
digitalWrite(segG, SEGMENT_ON);
break;

case 10:
digitalWrite(segA, SEGMENT_OFF);
digitalWrite(segB, SEGMENT_OFF);
digitalWrite(segC, SEGMENT_OFF);
digitalWrite(segD, SEGMENT_OFF);
digitalWrite(segE, SEGMENT_OFF);
digitalWrite(segF, SEGMENT_OFF);
digitalWrite(segG, SEGMENT_OFF);
break;
}
}

Once the sketch is started the display will show the seconds
elapsed since you started the sketch on Arduino.
[For the video related to the project click here].
[For the sketch related to the project click here].
Project 32 - Counter of seconds and tenths of a
second.

Keep the same wiring and assembly diagram as in the


previous project.
Install the new SevSeg Library in the IDE:
Go to Sketch, click on #include library and click on Manage
Library and type in the dialog box the name of the library of
interest which is called SevSeg and then once found, click
on install and the library will be installed.
Once the Library is installed, copy the code below into a
new sketch:
/*
BE MAKER - STEM - Project 32: Stopwatch with use of the Library.
EXTRACTED FROM THE LIBRARY EXAMPLES
DISPLAY PIN CONNECTION CONFIGURATION TO ARDUINO
Diital pins D1=4, D2=3, D3=2, D4=1
Segment pins A=10, B=9, C=6, D=7, E=8, F=11, G=12 and dp=5
*/

#include "SevSeg.h"
SevSeg sevseg; //Instantiate a seven segment controller object

void setup() {
byte numDigits = 4;
byte digitPins[] = {4, 3, 2, 1};
byte segmentPins[] = {10, 9, 6, 7, 8, 11, 12,5};
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or
isn't connected

sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,


resistorsOnSegments,
updateWithDelays, leadingZeros, disableDecPoint);
sevseg.setBrightness(90);
}

void loop() {
static unsigned long timer = millis();
static int deciSeconds = 0;

if (millis() - timer >= 100) {


timer += 100;
deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond

if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.


deciSeconds=0;
}
sevseg.setNumber(deciSeconds, 1);
}

sevseg.refreshDisplay(); // Must run repeatedly


}

Load the sketch on Arduino you will see that when the
loading is complete the display will start counting the time
elapsed since the program was launched on Arduino
(seconds and tenths of a second will be indicated)
Analysis of the sketch: Project 32 -
Chronometer with use of the Library.
There are many interesting things in this sketch, let's look at
the most interesting ones. First of all you can see that the
use of the SevSeg Library drastically reduces the code
instructions to be written since special functions are used to
handle the 4-digit seven-segment LED Display.
Among these instructions we find:
byte hardwareConfig = COMMON_CATHODE;
which tells Arduino what type of display we are using
whether common cathode or common anode (in which case
we would write COMMON_ANODE) .
With instructions:
byte digitPins[] = {4, 3, 2, 1};
byte segmentPins[] = {10, 9, 6, 7, 8, 11, 12,5};
we tell Arduino how our display is connected to its pins. In
our particular case: Diital pins D1=4, D2=3, D3=2, D4=1
Segment pins A=10, B=9, C=6, D=7, E=8, F=11, G=12 and
dp=5 .
With education:
bool leadingZeros = false;
we tell Arduino whether there should be zeros in front of the
digit we want to show on the display (in which case we
needed to write "true" or not).
With education:
bool disableDecPoint = false;
we tell Arduino that we plan to use the decimal point of the
display (otherwise we would have written "true")
With education:
sevseg.setNumber(deciSeconds, 1);
we tell Arduino that the numbers it needs to show on the
display, are numbers with only one decimal place.
Let's look at the millis() function instead: when it is called it
returns the elapsed time, in milliseconds, since the sketch
started running on the Arduino. Since we want tenths of a
second, and after ten tenths of a second must trigger the
second, the form to get this is:
if (millis() - timer >= 100) {
timer += 100;
deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
if (deciSeconds == 10000) { // Reset to 0 after counting for
1000 seconds.
deciSeconds=0;
}
Also after 999.9 seconds, it resets the counter to zero and
restarts from zero. Please note, the Arduino Reference
Book says that the type of value returned by the millis()
function is "unsigned long", also to make the variable fixed
for the millis() function call, which is updated from time to
time, it must also be defined as "static" type.
So the correct form is:
static unsigned long timer = millis();
For more details on the use of the library and instructions
in C++ you can refer to the Readme file that accompanies
the library, and for other instructions, to the Arduino
Reference Book [Refence Book click here], while for the
mills() function there is a project, also in this lesson, for
further discussion.

[For the video related to the project click here].


[For the sketch related to the project click here].
Project 33 - Potentiometer Value Display with 4 Digit
Display

The applications of a 4-digit display are really countless, in


this project it is used to numerically represent the value that
the potentiometer takes at that moment. The schematic to
be made, for the display part is identical to the previous one
so you can use the same wiring:
For assembly, follow the diagram below:
It is basically the same schematic as the previous project
with the addition of the 10K potentiometer. Now open the
Arduino IDE and write the following sketch:
/*
BE MAKER - STEM - Project 33: Potentiometer Value Display.
EXTRACTED FROM THE LIBRARY EXAMPLES
DISPLAY PIN CONNECTION CONFIGURATION TO ARDUINO
Diital pins D1=4, D2=3, D3=2, D4=1
Segment pins A=10, B=9, C=6, D=7, E=8, F=11, G=12 and dp=5
*/
#include "SevSeg.h"
SevSeg sevseg; //Instantiate a seven segment controller object
#define pot A0

void setup() {
byte numDigits = 4;
byte digitPins[] = {4, 3, 2, 1};
byte segmentPins[] = {10, 9, 6, 7, 8, 11, 12,5};
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or
isn't connected

sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,


resistorsOnSegments,
updateWithDelays, leadingZeros, disableDecPoint);
sevseg.setBrightness(90);
}

void loop() {
int val = analogRead(pot);
int scale = map(val, 0, 1023, 0, 10000); //potentiometer from 10K

if (scale > 9999 || scale < 1) { // if value > 9999 or < 0 then value to 0
scale = 0;
}
sevseg.setNumber(scale);
sevseg.refreshDisplay(); // Must run repeatedly
}

[For the video related to the project click here].


[For the sketch related to the project click here].
Project 34 - Insight for the millis() function.

The millis() function, as mentioned in the previous


paragraph, once called in the form:
unsigned long timer = millis();
returns the elapsed time, in milliseconds, since the start of
the sketch loaded on the Arduino, but this definition does
not give it the proper importance.
First of all, we can observe that the variable that contains it
is of the type "unsigned long" and that is, it can take a
maximum value of 4,294,967,294, so if we divide by 1,000
and then by 60 and again by 60 and then by 24, it turns out
that the millisecond counter, before it resets to zero, needs
49.7 days to elapse with the Arduino always on and running
the same sketch. Only after the 50 days or so does the
variable reset and start counting from zero again.
This function has multiple uses, all of which are interesting
and all to be discovered by doing several trials.
Among the uses I find most interesting about this feature is
that it gives you the ability to have actions occur at certain
time intervals, so let's look at one application of it right
away with a specific project.
For this project we only need our Arduino connected to the
PC via its USB cable

The purpose of the project is to make writings appear on the


Serial Monitor at certain time intervals (but it could be
turning on one LED, turning off another, etc... the sketch can
be easily adapted to our purposes).
Copy the code below into a new Arduino sketch after
launching the application:
/*
BE MAKER - STEM - Project 34: Deepening mills()
*/
#define INTERVAL_1 3000
#define INTERVAL_2 5000
#define INTERVAL_3 7000
#define INTERVAL_4 15000

unsigned long time_1 = 0;


unsigned long time_2 = 0;
unsigned long time_3 = 0;
unsigned long time_4 = 0;

void print_tempo(unsigned long tempo_millis);


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

void loop() {
if(millis() > time_1 + INTERVAL_1){
time_1 = millis();
print_time(time_1);
Serial.println("I am");
}

if(millis() > time_2 + INTERVAL_2){


time_2 = millis();
print_time(time_2);
Serial.println("A message");
}

if(millis() > time_3 + INTERVAL_3){


time_3 = millis();
print_time(time_3);
Serial.println("Of");
}

if(millis() > time_4 + INTERVAL_4){


time_4 = millis();
print_time(time_4);
Serial.println("Greetings");
}
}

void print_tempo(unsigned long tempo_millis){


Serial.print("Time: ");
Serial.print(time_millis/1000);
Serial.print("s - ");
}
[For the video related to the project click here].
[For the sketch related to the project click here].
LED Matrix Display

As the name implies, the module we will see consists of 24


LEDs arranged in 8 columns and 8 rows. There are several
8x8 LED displays on the market, the one we will analyze is
the classic 16 PIN version. In fact, the number of pins this
mudule has are 16, 8 pins, or PINs, are used to drive the
columns and 8 PINs are used to drive the rows.
Since Arduino has 14 digital PINs, the question arises: how
do we drive the 16 PINs digitally if we only have 14 digital
PINs with Arduino UNO? The answer is equally simple: by
using two of the 5 analog PINs of Arduino, in fact an analog
PIN can be used for all intents and purposes as a if it were a
digital PIN of Arduino, as long as the same instructions as
the digital PIN are used. But we will see this better in the
sketch, now let's move on to a better understanding of how
the 8x8 LED matrix works. LED arrays can also be Common
Anode or Common Cathode, the latter being the most
common.

As you have undoubtedly already learned, in the case of the


Common Cathode, the PIN must be placed in a low LOW
state in order to make the individual PINs light up.So
referring to the figure above, the rows, to which all the
cathodes are connected, must be placed in a LOW state,
while the columns must be placed in a HIGH state in order
to make the LEDs light up.
So as if we were at the game of naval battle, in order to
make the LEDwhich is in column 4 and row 2 light up, we
have to put column 4 in the state of HIGH and row 2 in the
state of LOW and titte the other rows and columns have to
be in the state of LOW.
Having figured out how to make the individual LEDs light up,
it is simple at this point to be able to dial in both letters and
numbers with the matrix.
Let us now turn to the project.
Project 35 - HELLO WORLD IN MATRIX !

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

8x8 LED Matrix No. 8 220 W


Display resistors
(common
cathode)

The wiring diagram is as follows:

Pay attention to the connections in the wiring diagram, you


need to consider the following pin-out of the display (in my
case), obviously in your case I suggest you retrieve the
datasheet from the internet by googling the serial number
of your display, if it matches mine, then follow the same
connections, otherwise you will have to adjust them.
Personally, thanks to the datasheet of the LED matrix I
purchased, I constructed this little table that helped me:
DISPLAY ROW/COLUMN ARDUIN
PIN. DISPLAY RESISTANCE PIN
1 R5 220 W 4
2 R7 220 W 6
3 C2 A0
4 C3 12
5 R8 220 W 7
6 C5 11
7 R6 220 W 5
8 R3 220 W 2
9 R1 220 W 0
10 C4 13
11 C6 10
12 R4 220 W 3
13 C1 A1
14 R2 220 W 1
15 C7 9
16 C8 8

At this point the assembly diagram turns out to be much


easier to make even though there is a considerable number
of dupont wires.
Now we double-click on the Arduino icon on the Desktop and
the IDE opens and we copy the following sketch, be sure to
follow each step indicated:
/*
Be Maker School - STEM - Project 3 - Hello World in Matrix
*/

#define r8 0
#define r7 1
#define r6 2
#define r5 3
#define r4 4
#define r3 5
#define r2 6
#define r1 7

#define c1 8
#define c2 9
#define c3 10
#define c4 11
#define c5 12
#define c6 13
#define c7 19
#define c8 18

#define initr HIGH


#define initc LOW
int analoginit= 0;

#define pause 100


#define screenTime 50

int vRows[8]={r1,r2,r3,r4,r5,r6,r7,r8};
int vCols[8]={c1,c2,c3,c4,c5,c6,c7,c8};

byte A[8][8] = {{0,0,0,1,1,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},


{0,0,1,1,1,1,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,0,0,1,0,0}};
byte B[8][8] = {{0,0,1,1,1,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,1,1,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,1,1,0,0,0}};
byte C[8][8] = {{0,0,0,0,0,0,0,0},{0,0,0,1,1,1,1,0},{0,0,1,0,0,0,0,0},
{0,1,0,0,0,0,0,0},{0,1,0,0,0,0,0,0},{0,0,1,0,0,0,0,0},{0,0,0,1,1,1,1,0},
{0,0,0,0,0,0,0,0}};
byte D[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,0,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,0,0,0,1,0},{0,0,1,0,0,0,1,0},{0,0,1,0,0,1,0,0},{0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0}};
byte E[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}};
byte F[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,0,0,0,0,0},
{0,0,1,1,1,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
byte G[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,1,1,0},{0,0,1,0,0,0,0,0},
{0,0,1,0,0,0,0,0},{0,0,1,0,1,1,1,0},{0,0,1,0,0,0,1,0},{0,0,1,1,1,1,1,0},
{0,0,0,0,0,0,0,0}};
byte H[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,1,1,1,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0}};
byte I[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,0,0,0},{0,0,0,1,0,0,0,0},
{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},{0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0}};
byte J[8][8] = {{0,0,0,0,0,0,0,0},{0,0,0,1,1,1,0,0},{0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0},{0,0,0,0,1,0,0,0},{0,0,1,0,1,0,0,0},{0,0,1,1,1,0,0,0},
{0,0,0,0,0,0,0,0}};
byte K[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,1,0,0,0},
{0,0,1,1,0,0,0,0},{0,0,1,0,1,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0}};
byte L[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},
{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}};
byte M[8][8] = {{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0},
{1,0,1,0,1,0,1,0},{1,0,0,1,0,0,1,0},{1,0,0,0,0,0,1,0},{1,0,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0}};
byte N[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,0,0,0,1,0},{0,0,1,1,0,0,1,0},
{0,0,1,0,1,0,1,0},{0,0,1,0,0,1,1,0},{0,0,1,0,0,0,1,0},{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
byte O[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,1,0,0,0,0,1,0},
{0,1,0,0,0,0,1,0},{0,1,0,0,0,0,1,0},{0,1,0,0,0,0,1,0},{0,0,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}};
byte P[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,0,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,0,0,1,0,0},{0,0,1,1,1,0,0,0},{0,0,1,0,0,0,0,0},{0,0,1,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
byte Q[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,1,0,0,0,0,1,0},
{0,1,0,0,0,0,1,0},{0,1,0,0,0,0,1,0},{0,1,0,0,0,1,1,0},{0,0,1,1,1,1,1,0},
{0,0,0,0,0,0,0,1}};
byte R[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,0,0,0},{0,0,1,0,0,1,0,0},
{0,0,1,0,0,1,0,0},{0,0,1,1,1,0,0,0},{0,0,1,0,0,1,0,0},{0,0,1,0,0,1,0,0},
{0,0,0,0,0,0,0,0}};
byte S[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,1,1,1,0,0},{0,0,1,0,0,0,0,0},
{0,0,1,1,1,1,0,0},{0,0,0,0,0,1,0,0},{0,0,0,0,0,1,0,0},{0,0,1,1,1,1,0,0},
{0,0,0,0,0,0,0,0}};
byte T[8][8] = {{0,0,0,0,0,0,0,0},{0,1,1,1,1,1,0,0},{0,0,0,1,0,0,0,0},
{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},
{0,0,0,0,0,0,0,0}};
byte U[8][8] = {{0,0,0,0,0,0,0,0},{0,1,0,0,0,0,1,0},{0,1,0,0,0,0,1,0},
{0,1,0,0,0,0,1,0},{0,1,0,0,0,0,1,0},{0,0,1,0,0,1,0,0},{0,0,0,1,1,0,0,0},
{0,0,0,0,0,0,0,0}};
byte V[8][8] = {{0,0,0,0,0,0,0,0},{0,0,1,0,0,0,1,0},{0,0,1,0,0,0,1,0},
{0,0,1,0,0,0,1,0},{0,0,0,1,0,1,0,0},{0,0,0,1,0,1,0,0},{0,0,0,0,1,0,0,0},
{0,0,0,0,0,0,0,0}};
byte W[8][8] = {{0,0,0,0,0,0,0,0},{1,0,0,0,0,0,1,0},{1,0,0,1,0,0,1,0},
{0,1,0,1,0,1,0,0},{0,1,0,1,0,1,0,0},{0,0,1,0,1,0,0,0},{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
byte X[8][8] = {{0,0,0,0,0,0,0,0},{0,1,0,0,0,0,1,0},{0,0,1,0,0,1,0,0},
{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,1,0,0,1,0,0},{0,1,0,0,0,0,1,0},
{0,0,0,0,0,0,0,0}};
byte Y[8][8] = {{0,1,0,0,0,0,1,0},{0,1,0,0,0,0,1,0},{0,0,1,0,0,1,0,0},
{0,0,1,0,0,1,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},{0,0,0,1,1,0,0,0},
{0,0,0,1,1,0,0,0}};
byte Z[8][8] = {{0,1,1,1,1,1,1,0},{0,0,0,0,0,0,1,0},{0,0,0,0,0,1,0,0},
{0,0,0,0,1,0,0,0},{0,0,0,1,0,0,0,0},{0,0,1,0,0,0,0,0},{0,1,0,0,0,0,0,0},
{0,1,1,1,1,1,1,0}};
byte space[8][8]= {{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}};
byte escl[8][8]= {{0,0,0,0,0,0,0,0},{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},
{0,0,0,1,0,0,0,0},{0,0,0,1,0,0,0,0},{0,0,0,0,0,0,0,0},{0,0,0,1,0,0,0,0},
{0,0,0,0,0,0,0,0}};

void resetRows(){
for(int i=0;i<8;i++)
digitalWrite(vRows[i],initr);
}
void resetCols(){
for(int i=0;i<8;i++)
digitalWrite(vCols[i],initc);
}

void setup() {

pinMode(r1,OUTPUT);
pinMode(r2,OUTPUT);
pinMode(r3,OUTPUT);
pinMode(r4,OUTPUT);
pinMode(r5,OUTPUT);
pinMode(r6,OUTPUT);
pinMode(r7,OUTPUT);
pinMode(r8,OUTPUT);

pinMode(c1,OUTPUT);
pinMode(c2,OUTPUT);
pinMode(c3,OUTPUT);
pinMode(c4,OUTPUT);
pinMode(c5,OUTPUT);
pinMode(c6,OUTPUT);
pinMode(c7,OUTPUT);
pinMode(c8,OUTPUT);

resetRows();
resetCols();

void lightRows(){
for(int i=0;i<8;i++)
digitalWrite(vRows[i],!initr);
}

void lightCols(){
for(int i=0;i<8;i++)
digitalWrite(vCols[i],!initc);
}

void counter1(){
for(int i=0;i<8;i++){
resetCols();
resetRows();
digitalWrite(vCols[i],HIGH);
delay(pause);
for(int j=0;j<8;j++){
resetRows();
digitalWrite(vRows[j],LOW);
delay(pause);
}
}

void counter2(){

for(int i=0;i<8;i++){
resetCols();
resetRows();
digitalWrite(vRows[i],LOW);
delay(pause);
for(int j=0;j<8;j++){
resetCols();
digitalWrite(vCols[j],HIGH);
delay(pause);
}
}
}

void blinking(){

for(int i=0;i<3;i++){
lightCols();
lightRows();
delay(pause*10);
resetRows();
resetCols();
delay(pause*10);
}
}

void drawSymbols(byte m[8][8]){


for(int k=0;k<screenTime;k++){
for(int i=0;i<8;i++){
digitalWrite(vCols[i],!initc);
for(int j=0;j<8;j++)
digitalWrite(vRows[j],!m[i][j]);
delay(2);
resetRows();
resetCols();

}
}
}

void writeLetter(String wordIn){


for(int i=0;wordIn[i]!=0;i++){
switch(wordIn[i]){
case 'A':drawSymbols(A);
break;
case 'B':drawSymbols(B);
break;
case 'C':drawSymbols(C);
break;
case 'D':drawSymbols(D);
break;
case 'E':drawSymbols(E);
break;
case 'F':drawSymbols(F);
break;
case 'G':drawSymbols(G);
break;
case 'H':drawSymbols(H);
break;
case 'I':drawSymbols(I);
break;
case 'J':drawSymbols(J);
break;
case 'K':drawSymbols(K);
break;
case 'L':drawSymbols(L);
break;
case 'M':drawSymbols(M);
break;
case 'N':drawSymbols(N);
break;
case 'O':drawSymbols(O);
break;
case 'P':drawSymbols(P);
break;
case 'Q':drawSymbols(Q);
break;
case 'R':drawSymbols(R);
break;
case 'S':drawSymbols(S);
break;
case 'T':drawSymbols(T);
break;
case 'U':drawSymbols(U);
break;
case 'V':drawSymbols(V);
break;
case 'W':drawSymbols(W);
break;
case 'X':drawSymbols(X);
break;
case 'Y':drawSymbols(Y);
break;
case 'Z':drawSymbols(Z);
break;
case '!':drawSymbols(excl);
break;
default:drawSymbols(space);
break;
}
}
}

void loop() {
counter1();
counter2();
blinking();
String a="HELLO WORLD!"
writeLetter(a);
}

Once the sketch is loaded, the letter-by-letter Hello World


appears illuminated on the LED array.

Analysis of the Sketch: Hello World in


the Matrix
As you can see from the sketch, we introduced a new type
of variable. We had already seen what arrays were, that is,
variables that could contain multiple values and were
identified with an index. In this sketch we see the array
variable (always called array) being defined in this way:
byte A[8][8] = {{{0,0,0,1,0,0,0},....., {.....}};
where "bytes" indicates the type of variable and how much
memory it occupies, "A[8][8]" indicates the name of the
variable and the size of the array, i.e., 8 rows and 8
columns, and then after the "=" in curly brackets, the
individual values are entered, which in our case represent
the LEDs that must be turned on to make up the letter "A,"
in fact if you notice, zero is set for the LED to be kept off and
1 for the LED to be turned on, so for the variable A:
1 2 3 4 5 6 7 8
1 0 0 0 1 1 0 0 0
2 0 0 1 0 0 1 0 0
3 0 0 1 0 0 1 0 0
4 0 0 1 1 1 1 0 0
5 0 0 1 0 0 1 0 0
6 0 0 1 0 0 1 0 0
7 0 0 1 0 0 1 0 0
8 0 0 1 0 0 1 0 0

In this way you can dial what you want and assign it a
variable name. Alternatively, it is possible to activate
individual LEDs, again in the sketch you can observe the
functions "counter1()", "counter2()" and "blinking()" which
thanks to "for" cycles drive the individual LEDs in the matrix
by acting directly in the variables vCols and vRows.
Returning to the representation on the LED array of the
phrase "Hello World", we can observe the function
writeLetter(...) that for each letter of the string we enter to
it, thanks to the switch... case... structure, calls the variable
of the single letter that makes up the word Hello Word and
represents it on the LED array.

[For the sketch related to the project click here].


The LCD Display

Also using the LCD display represents a good way to


immediately represent some values that we find useful to
keep track of in an ongoing process in Arduino.
Liquid crystal displays (LCDs) consist of liquid crystals
activated by electric current.
Curiosity: how the LCD display works
The process of operation is not the easiest to explain in
detail, so a very simplified description is given here; for any
further study, plenty of material can be found on the
Internet.
As far as we are concerned, it is enough to know about the
LCD display which is made thanks to the presence of liquid
crystals i.e., a particular substance that at the same
temperature can coexist both in the liquid and solid state at
the same time, this substance subjected to polarization, i.e.,
a low-power electric current, has a different behavior that
we are able to drive. Certain parts of the substance,
polarized, orient themselves in a precise configuration, thus
forming the figure of our interest. There are several types
that differ substantially in the number of lines of
alphanumeric information they can display, normally they
are 16 characters and are two-, three- or four-line (for those
used with Arduino).

The liquid crystal display has the distinct advantage of


having low power consumption compared to LED displays.
Its other advantages are its low cost and ease of finding it
on the market. The main disadvantages of LCDs are: a light
source must be added to make the information visible, and
when there is low ambient light, a backlight must also be
added. Other disadvantages are: it can work in a very
limited temperature range (i.e., between 0°C and 60° C),
also it has a short operating life compared to LED displays.
Project 36 - HELLO WORLD WITH LCD DISPLAY.

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

LCD display 16 No. 2 220 W 10 KOhm


x 2 lines resistors potentiometer
The wiring diagram is as follows:

For better visibility of PINs, I partially reproduce the photo of


the display:

The assembly scheme is as follows:


Once the circuit is assembled, the sketch to be written and
uploaded to Arduino is:
/*
Be Maker School - STEM - Project 36 - Hello World LCD
*/

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2; //define variables


associated with link PINs
LiquidCrystal lcd(rs, en, d4, d5, d6, d7); //associating display PINs to Arduino
PINs

void setup() {
lcd.begin(16, 2); //set the display as a 2-line, 16-character display
lcd.print("hello, world!"); //let me play the inscription only once
}
int foo = 0; //set a variable that will act as my seconds counter

void loop() {
lcd.setCursor(0, 1); //position the cursor on the first line down to the position
lcd.print(foo); //print the seconds counter
delay(1000);
foo++;
}

Sketch Analysis: Hello World with LCD


Display
As you can see from the sketch for the operation of the
display we introduce a new library called <LiquidCrystal.h>.
This library significantly simplifies our use of the display, in
fact it only takes a few lines of program code to achieve the
desired result.
Let's see what instructions help us manage our LCD display.
First we need to call the Dedicated Library with #include
<LiquidCrystal.h> , in the void setup part, I can set the
title of the information that is shown, it is printed once on
the display lcd.print("hello, world!");.
In the void loop part instead when the information needs to
be updated lcd.print(foo);
The positioning of the cursor from which to start the writing
is done with the instruction: lcd.setCursor(0, 1); at this
point have fun making changes and see the results.

[For the video related to the project click here].


[For the sketch related to the project click here].
LESSON 10 - Insight into Light: the Infrared

The sun is the source of life for the earth, thanks to it we


have the light and heat we need for our survival. Light is
produced by a transformation of energy; in fact, due to the
high temperatures of the sun's constituent mass, its
incandescence is transferred not only as heat, but also as
light.
The same principle applies to candles, to incandescent light
bulbs, which have a tungsten filament that heats up, due to
the circulation of current, in addition to producing heat,
emits light.
There are other ways to produce light, such as by passing
electrical discharges through a gas (neon lights, or mercury
vapor lights), or by exploiting the electroluminescent
characteristics of particular materials as is the case with
LEDs.
Leaving aside the Quantum Physics of the great scientist
Albert Einstein, let's try to understand a little bit more than
what we learned in Lesson No. 3.
We have already seen that light propagates in waves,
however, unlike sound, it does not need a "material"
medium because they are special electromagnetic waves
(photon waves). Basically, light propagates even in a
vacuum (just think of the light that comes to us from stars,
but also from the sun itself).
The propagation of light occurs on straight trajectories
called "rays," and they, too, may encounter obstacles on
their path. The propagation speed of light, is much higher
than that of Sound. The demonstration of this is when there
is a thunderstorm... lightning generates both light and at
the same time, noise, but we get the lightning first... and
after a few seconds the thunder. Light travels at about
300,000 kilometers per second , that is, in one second light
travels about 300,000 kilometers!
When light meets a transparent body, it manages to pass
through it, only a very small part is reflected. If the body is
opaque, then diffuse reflection occurs. If the body is a
mirror, then the reflection is said to be specular. Through
reflection we are able to see even objects that do not emit
light of their own.
Just to complete the topic of "light" of our interest, I would
like to say that infrared is that particular light whose
spectrum (i.e., wavelength) is below the color red (hence
"infrared"), i.e., a frequency whose wavelength is greater
than 700 nano-meter is of the order of tera-Hertz.

Infrared has countless applications in electronics and


robotics, we will look at some of them.
Infrared Sensor Module KY-032
This sensor module is used as an alternative method to the
HC-SR04 sensor module for obstacle detection. The
operating principle of the sensor is very similar to the
ultrasonic module, in fact it is based on the emission of
infrared signals that are then reflected by any bodies that
are in the path of the incident signal beam and then, once
reflected, are picked up by the receiver:
Comparison of HCSR04 Ultrasonic
Module and KY032 Infrared Module.
For the comparison between Ultrasonic Module HCSR04 and
Infrared Module KY032 for obstacle detection, we construct
a small table to highlight the major differences between the
two modules for the purpose of obstacle detection:

Main
Features
Ultrasonic Module Infrared Module
(Sound) (Light)
Frequencies above Frequency on the
20 kHz (20 kilo-hertz, order of THz
or 20 thousand hetz). (tera-hertz, or
Spectrum Ultrasound is at the trillion hertz).
high end of the Infrared is at the
sound spectrum. lower end of the
light spectrum.
Propagation Compared with solid The maximum
bodies, sound in air propagation speed
propagates at a of light is in
slower speed and vacuum: 300,000
does not propagate km/s (300,000
in a vacuum. In air, kilometers per
the speed of sound is second).
about 340 m/s (340
meters per second)
Ability of the Optimal for solid At the same angle
reflected wave surfaces that are to the sound, with
to return in perpendicular to the light there is a
the same direction of the very good
direction as sound wave, as these reflection in the
the generator. surfaces tilt, relative direction of the
to the direction of generator--even
the wave, the for very inclined
dispersion of surfaces.
reflected sound Light is not
increases. For reflected from
particular very dark-colored
inclinations, the bodies (in which
sound wave does not case light is
return in the absorbed) and in
direction of the the case of
generator, so the transparent
reflection causes the materials (where
sound to scatter. light passes
through the
material).

It is clear from the comparison that the two obstacle


detection modules, although they serve the same purpose,
function differently and the two systems almost
complement each other to form a single system that is safer
in obstacle detection.

Project 37 - The use of KY032 Module with the EN PIN


disabled
For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

IR module KY032
with jumper
inserted on EN

The scheme to be carried out is as follows:


The assembly scheme is as follows:

We click on the Arduino icon and after opening a new file we


copy the sketch below:
/*
Be Maker - STEM - PROJECT 37 INFRARED MODULE KY-032 FOR OBSTACLE
DETECTION.
With EN disabled
*/
int Obstacle = 0; //LOW status means obstacle found!
#define ObstaclePin 8 // selects the pin for sensor KY-032

void setup() {
pinMode(ObstaclePin, INPUT); //setting PIN 8 as INPUT
Serial.begin(9600); //setting the serial port
}

void loop() {
Obstacle = digitalRead(ObstaclePin); //read the status of PIN 8
if (Obstacle == 0) {
Serial.println(" Obstruction eye!!!"); //if PIN 8 status is low
//then the obstacle is present
}
else {
Serial.println (" Street Free"); //otherwise, the street is free
}
delay(50); //cycle repeats after 300 msec.
}
Once the sketch is loaded and the serial monitor is
activated, pass your hand in front of the sensor module at
different distances and verify the detection by the LED on
board the module lighting up and the writing appearing on
the serial monitor. The switching point of the sensor can be
adjusted using the trimmers located on the module.

Analysis of the Sketch: Project 37 -


Form KY032.
Since the Module functions as a switch, i.e., if it finds the
obstacle within the distance calibrated by the trimmers the
module puts the signal PIN in the LOW state, it is suggested
to proceed , before its use, to calibration. This is done with
the help of a ruler and by placing an obstacle at the desired
distance. It will be necessary to adjust the two trimmers
until the obstacle, at that precise distance, is detected.

[For the video related to the project click here].


[For the sketch related to the project click here].
Project 38 - The use of KY032 Module with the EN PIN
enabled

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

IR module KY032
with jumper
removed on EN
The scheme to be carried out is as follows:

The assembly scheme is as follows:


We click on the Arduino icon and after opening a new file we
copy the sketch below:
/*
Be Maker - STEM - DRAFT 38 INFRARED MODULE KY-032 FOR OBSTACLE
DETECTION.
With EN enabled
*/
int ObstaclePin = 8; //Pin to which the sensor is connected
int EnPin = 7; //Pin to which the EN PIN of the module is connected.
int Obstacle = LOW; //LOW status means obstacle not found

void setup() {
pinMode(ObstaclePin, INPUT); //setting PIN 8 as INPUT
pinMode(EnPin, OUTPUT); //setting PIN 7 as OUTPUT
Serial.begin(9600); //setting the serial port
}

void loop() {
digitalWrite(EnPin, HIGH); //enable module operation
Obstacle = digitalRead(ObstaclePin); //read the status of PIN 8
if (Obstacle == LOW) {
Serial.println("Obstruction eye!!!"); //If the status of PIN 8 is low then the
obstacle is present
}
else {
Serial.println ("Street Clear"); //otherwise, the street is clear
}
delay(30); //cycle repeats after 300 msec.
}

Once the sketch is loaded and the serial monitor is


activated, pass your hand in front of the sensor module at
different distances and verify the detection by the LED on
board the module lighting up and the writing appearing on
the serial monitor. The switching point of the sensor can be
adjusted using the trimmers located on the module.
Basically, in this design, as you can see, you only have the
special feature that the operation of the module can be
enabled or disabled as needed. To enable it, the EN PIN
must be put in the high state (HIGH). With the presence of
the jumper the EN turns out to be always enabled.
[For the video related to the project click here].
[For the sketch related to the project click here].
KY-033 Infrared Sensor Module - Line
Tracking

We have seen, in the previous paragraphs, that infrared


when hitting surfaces with particular very dark colors, they
fail to be reflected and therefore not picked up by the
receiving sensor. So, some fellow Makers of yours rightly
thought of exploiting this phenomenon to make a sensor
that could identify a dark-colored line from other colors.
Such a module was called a Line Tracking Module
(English: Line Tracking) and its abbreviation under which it
is commercially sold is KY-033, we will call it a line-tracking
sensor or module.
The operation of such a sensor is simple, and the module is
similar to the previous one:

Basically, when the receiving LED does not pick up the


infrared emitted by the emitting LED, it means that the
sensor is positioned on the BLACK color Line (obviously,
very dark colors must be used to draw the lines, BLACK
being the optimum).
The module has three PINs, one for ground (indicated by G
or GND), one for power supply (indicated by Vcc or V+), and
one for output signal (indicated by S or OUT). The location is
not always as shown in the figure so watch for the
indications on the module.
In addition, the module has a trimmer that is used to adjust
the intensity of the emitting signal, so depending on the
distance between the emitter and the line to be tracked, a
small adjustment has to be made (usually in the middle
position, which is the one shown in the figure above, it
already works very well). It should be noted that the output
signal is analog, so you will need to connect the signal PIN
of the module to an Analog PIN of the Arduino. But let's take
a closer look at the operation of the module in the following
project.
Project 39 - The Use of KY033 Line Tracking Module.

For this project we need:

Arduino Uno R3 Breadboard Dupont male - USB connection


or compatible male cables cable

IR Module KY033
Line Tracking

The scheme to be carried out is as follows:


The assembly scheme is as follows:

We click on the Arduino icon and after opening a new file we


copy the sketch below:
/*
Be Maker - STEM - Project 39 - Line Chase Module -KY033
*/
int sensorPin = A5; // The sensor is connected to the A5 pin.
int ledPin = 13; // selected PIN 13 for the LED on the Arduino
int sensorValue = 0; // Variable that takes the value from the sensor

void setup () {
pinMode (ledPin, OUTPUT);
Serial.begin (9600);
}

void loop () {
sensorValue = analogRead(sensorPin);
if (sensorValue > 500) {
digitalWrite(ledPin,HIGH); //PIN on Arduino turned on
Serial.println ("ON LINE");
}
else {
digitalWrite(ledPin,LOW); //PIN on Arduino off
Serial.println ("OUT OF LINE");
}
delay (200);
}

Once the sketch is loaded and the serial monitor is


activated, pass the sensor over a Line at least a couple of
cm thick and observe the output signal.
Sketch Analysis: Project 39 - KY033
Line Tracking Module.
Analyzing the sketch above we can observe the following
instruction:
int ledPin = 13;
With this instruction we say that the Integer Variable named
LED has a value of 13.
The same can be said about education:
int sensorPin = A5;
Where A5 is the number of the Analog PIN of Arduino where
we connected the "OUT" signal of the sensor.
The Variable named "sensorValue," is assigned a value of 0
initially, with the instruction:
int sensorValue = 0;
Related to the SETUP section, we can observe the
instructions:
pinMode(ledPin, OUTPUT);
which defines as OUTPUT the LED that is on the Arduino
(and is connected right to PIN 13).
In the LOOP section we have the interesting part: first we
have the analogRead(sensorPIN) instruction read; the
value present on PIN A5 and assign it to the variable
sensorValue. At this point when the sensor is above a clear
surface, the module returns a low voltage value (about 83
mV - milliVolts), so remembering that the analog PIN goes
from 0 to 1023, we calibrate the sensor to a value of 500,
i.e.: 5 V/1024*500 = 2.44 V. That is, when the sensor
returns a value greater than 2.44 V (i.e., greater than 500) it
is on a dark surface and for us the sensor is in the correct
position is therefore "ON LINE."
I carried out several tests, also using the adjustment
granted by the trimmer, and observed that, placing the
sensor about 4 to 5 cm from the surface, with the color
brown the sensor returns values between 500 and 600,
while with black it goes between 800 and 1000.
The best sensor functionality, however, is when you put two
of them paired together. They are better able to detect their
relative positioning with respect to the line to be tracked.
[For the video related to the project click here].
[For the sketch related to the project click here].
The Infrared Remote Control - IR
Remote Controller

In addition to being used for sensors in detecting obstacles


or tracking lines, infrared light is also used to transmit
information from one device to another. An example of this
is our TV remote control.
In this part of the Lesson we will concentrate on learning the
operation of an infrared remote control (information
transmitter) and its corresponding information receiving
device (which in our case is an infrared receiver called
KY022). Information from one device to another is
transmitted via Infrared signals (we use the abbreviation IR
for short) of an encoded type.
Normally when one buys the remote control, the
manufacturer of the remote control also indicates in the
manual the encoding with which the remote control
transmits information about IR signal, but we will dispense
with this information, because we will also see how to get
this information from our remote control. So we will perform
two practical projects, one to retrieve the encoding
information (thus decoding the signal) and the other to use
the transmitted encoded information to make Arduino
perform operations.

Project 40 - Decoding the IR signal of a remote


control

For this project we need:

Arduino Uno Breadboard Dupont male - USB connection


R3 or male cables cable
compatible
IR remote IR Receiver KY022 220 W resistor Green LED
control to be
decoded

The scheme to be carried out is as follows:

For assembly, refer to the diagram below:


After the connections we move on to writing the sketch.
Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.

Open a new empty window and write the sketch below:


/*
Be Maker - STEM - Project 40 - Decoding IR Remote Control
*/

#include <IRremote.h>

int pinIRremote = 5; //PIN of Arduino to which the receiver signal is connected


IRrecv receiver(pinIRremote); //instance for object creation
decode_results results;
int ledPin=9;

void setup()
{
Serial.begin(9600); //set the serial port
receiver.enableIRIn(); //enables reception
pinMode(ledPin, OUTPUT);
}

void loop()
{
if (receiver.decode(&results))
{
digitalWrite(ledPin, HIGH); //turns on the LED when it receives the signal
Serial.println(results.value);
delay(1000);
digitalWrite(ledPin, LOW); //shuts down the LED after decoding
receiver.resume(); //ready to receive the next signal
}
}

At this point, once you have loaded the sketch on the


Arduino, open the Serial Monitor of the IDE , point the
remote control at the receiver, and press each button on the
remote control once. With each press, the green light turns
on when the signal is captured and turns off when the
decoding is done. The code of the button pressed appears
on the Serial Monitor. Now all that remains is to write down
the codes corresponding to each button on the remote
control. In my case:
- Power off button: 16580863
- Volume +: 16613503
- Volume -: 16617583
- 1 : 16582903
- 2 : 16615543
- 3 : 16599223
- 4 : 16591063
- Etc...
Sketch Analysis: Project 40 -
Decoding the IR signal of a remote
control.
As you can see from the sketch, we have introduced a new
library: #include <IRremote.h> that makes it very easy to
use the IR Receiver. In fact, you only have to read the
comment lines at the individual command lines that you can
immediately guess what function the individual instruction
performs. Be careful, it is quite normal for the IR Receiver to
also capture other infrared signals, such as those generated
by artificial lighting or even from other remote commands.

[For the video related to the project click here].


[For the sketch related to the project click here].
Project 41 - Piloting Events with IR Remote Control

Thanks to the KY-022 Module, we can drive events with an


Infrared remote control, in fact, once we have stored the
codes corresponding to the individual keys of the remote
control, with the if instruction that establishes which key has
been pressed, we can make a certain event take place. An
example is the following project. For this project we need:

Arduino Uno Breadboard Dupont male - USB connection


R3 or male cables cable
compatible

IR remote IR Receiver KY022 No. 4 220 W No. 4 LEDs of


control to be resistor different colors
decoded

The scheme to be carried out is as follows:


For assembly, refer to the diagram below:

After the connections we move on to writing the sketch.


Connect Arduino to the PC via the USB cable and launch the
Arduino IDE application by double-clicking on its icon.
Open a new empty window and write the sketch below:
/*
Be Maker - STEM - Project 41 - Piloting Events with IR Remote Control
*/
#include <IRremote.h>

int pinIRremote = 5;
int pinLEDgreen = 9;
int pinLEDyellow = 10;
int pinLEDred = 11;
int pinLEDblu = 12;
IRrecv receiver(pinIRremote);
decode_results results;

void setup()
{
pinMode(pinLEDgreen, OUTPUT);
pinMode(pinLEDyellow, OUTPUT);
pinMode(pinLEDred, OUTPUT);
pinMode(pinLEDblu, OUTPUT);
Serial.begin(9600);
receiver.enableIRIn();
digitalWrite(pinLEDyellow,LOW);
digitalWrite(pinLEDred,LOW);
digitalWrite(pinLEDblu,LOW);
}

void loop()
{
if (receiver.decode(&results))
{
digitalWrite(pinLEDgreen,HIGH);
Serial.println(results.value);
if(results.value==16582903){digitalWrite(pinLEDyellow,HIGH);}
if(results.value==16615543){digitalWrite(pinLEDred,HIGH);}
if(results.value==16599223){digitalWrite(pinLEDblu,HIGH);}
if(results.value==16580863){
digitalWrite(pinLEDyellow,LOW);
digitalWrite(pinLEDred,LOW);
digitalWrite(pinLEDblu,LOW);
}
delay(1000);
digitalWrite(pinLEDgreen,LOW);
receiver.resume();
}
}

At this point, once you have loaded the sketch on Arduino,


open the Serial Monitor of the IDE , point the remote control
at the receiver and press the "1" key to turn on the yellow
LED, the "2" key to turn on the red LED and the "3" key for
the blue LED. To turn everything off, press the red power off
key .

Analysis of Sketch: Project 41 -


Piloting events with IR Remote
Control.
Analyzing the sketch above, we can see that in order to get
the IR receiver to work easily, the IRremote.h library must
be loaded:
#include <IRremote.h>
As you can observe the code, with this library, is very
simple:
To create the "receiver" object
IRrecv xxxxxxx (pinIRremote);
To enable the IR receiver
xxxxx.enableIRIn();
To decode the IR signal
xxxxxxx.decode
Once the signal is decoded, the value is entered into the
results variable
results.value
To prepare to receive more IR signal
xxxxxxxx.resume();
[For the video related to the project click here].
[For the sketch related to the project click here].

You might also like