Arduino 3 in 1 Beginners Guide
Arduino 3 in 1 Beginners Guide
Arduino:
Comprehensive Beginners Guide to Learn
Arduino Programming Step by Step
Introduction
Chapter 1: Diving into the World of Arduino
A Brief History
What Is Arduino?
The Microcontroller Chip
Discovering Other Arduino Board
Official Arduino Boards
Arduino Clones
Chapter 2: Hardware and Tools
Power Supply
The Breadboard
Jump Wires
Needle Nose Pliers
Multimeter
Solder and Soldering Iron
Diode
LED
Electronics and Physics
Resistors color code:
The Capacitor
Arduino IDE (Software)
Installation:
Chapter 3: Working with Arduino
Preparing Your Workspace
Working with Your First Arduino
The Simple Blink Code
Altering the Blink Code
Sketch
Using a Resistor
The Physics Behind It
Continuing
More LEDs
Coding
Optimizing
Chapter 4: Diving into the World of Arduino
Further Simple Sketches
Fade
Button
The Serial Monitor
Sensors and Input
Sensors and Actuators
Temperature Sensor
Infrared Emission Sensor
Photoresistor
Sound Sensor
Knock Sensor
Pulse-Width Modulation
Switches
A Sensor Sketch
Arduino Logic
Variables
Constants
Data Types
Structures
Sketch
Arithmetic Operators
Control Structures
Boolean Operators
Comparison Operators
Functions
Digital I/O
Analog I/O
Math
Random Numbers
Bit and Bytes
Chapter 5: Circuits, Arduino Shields and Library
Circuit Diagrams
Shields
Types of Shields
Prototyping Shields and Others
Ethernet, Wi-Fi, GPS… Shields
Sound Shields
Display Shields
Motorz! Shields!
Installing Shields
Preparations
Assembly
Attaching the Header
Soldering
Testing
Soldering
Bad Joints
Plug in
Tricks
Library
Using Library Manager
Manual Installation
Chapter 6: Practical Projects
LED Cube with Arduino
GPS Tracking with LoRa Shield
To design your own PCB:
Coding:
Motion Sensitive Light Switch
Build a Personalized Alarm System
Arduino Digital Clock with RTC
Game Controller with Unity
Traffic Light Controller
Chapter 7: Smart Appliances and The Power of the Web
Connecting Arduino to the Web
Hardware Install
Making Household Appliances Smart
Controlling Arduino with a Smartphone
Wi-Fi Remote Control Using ESP8266
Chapter 8: Troubleshooting Common Problems
Arduino IDE
Drivers
Crash
Direct Connection
Auto-Reset and Bootloader
Syntax in Arduino
Error launching Arduino on Windows
Conclusion
Appendix
URL
Reference
Arduino:
Simple and Effective Strategies to Arduino Programming
Introduction to Arduino
Chapter 1: Basic Programming Concepts Needed To Get Started With
Arduino
Chapter 2: Getting Started with Arduino
Chapter 3: C Language Basics
Chapter 4: Programming with Arduino
Chapter 5: Arduino Electrical Scheme
Chapter 6: The LCD Display Function
Conclusion
Arduino:
Advanced Methods and Strategies of Using Arduino
Introduction
The Shield
Arduino Uno
Download and Install the IDE
Chapter One: Controlling the LED
Arduino Connection
Chapter Two: Alarm Siren & Signal Light
Hardware and Software Required
Test the PWM Output
Install the System with LED
LED Control Using PWM Connector
Chapter Three: MDF Robotic Arm Kit & Recording of Micro SD Card
with Arduino
MDF Robotic Arm Kit with Arduino
Variable Declaration and Void Setup () Function
Void Loop () function
Chapter Four: Home Automation: Presence Sensor & Automation of
Irrigation System with Arduino
Home Automation: Presence Sensor with Arduino
Automation of Irrigation System: Humidity Sensor and Solenoid Valve
Chapter Five: Flammable Gas Sensor & RFID Kit with Arduino
The MQ-2 Sensor
RFID Kit with Arduino: Access Control System
How Does an RFID module work?
Setup () and Lopp () Functions
Chapter Six: Current + Energy Meter & Audio Module WTV020-SD with
Arduino
Audio Module WTV020-SD - Incorporating Audio Elements with Arduino
Chapter Seven: KY039 Heart Rate Meter & Audio Recording and Playback
with Arduino
Audio Recording and Playback with ISD1820 Module
Chapter Eight: Digital Scale with Arduino and Strain Gauge Cell
How a Strain Gauge Sensor Works
Chapter Nine: IoT with Esp8266 WiFi Module & Updating ESP-01
Firmware
The Esp8266 WiFi Module
Talking to the ESP-01 Module through AT Commands
How to Connect to a Network with the ESP-01
Sending Data to the Browser
Receiving Data Sent by Cell Phone
Chapter Ten: RTC - Real Time Clock DS1302, 1307 And 3231
RTC DS3231
RTC 1302
RTC 1307
Differences between Modules
Conclusion
What are the Possibilities?
Accessible Technology >> Movement Maker
Reference and Resources
ARDUINO
This book will seek to teach all aspects of Arduino Programming to a complete
beginner with absolutely no experience writing programs. So, for those who fear
programming as head-cracking work, we will seek to dissuade you from such as
you read through this course.
For those more familiar with Arduino programming, there is still much you
could learn from reading this book. Each step in the programming steps will be
explained to carry everyone along.
This book will act as a starting point for all you will need to know about Arduino
programming. We will provide links to the software you may need to learn
Arduino programming.
Chapter 1
Diving into the World of Arduino
A Brief History
Ivrea is a small town that sits across the Dora Baltea River in Italia. Famous for
its underdog kings, one of which was King Arduin who was eventually deposed
by King Henry II, of Germany.
We take the name of the platform from Bar di Re Arduino, a bar popularly
frequented by Massimo Banzi. The bar’s name was inherited from the Italian
king of 1002, King Arduin.
Arduino was introduced by Massimo Banzi, David Mellis and David Cuartielles
in Italia in 2005 at the Interaction Design Institute Ivrea (IDII) to provide access
to a cheap and simple tool for creating hardware for non-engineers.
It was forked from the work of Hernando Barragán, a student at the IDII who
had created a language called Wiring for his master’s thesis. Wiring was
designed to simplify the creation of interactive electronics for artists and
designers.
What Is Arduino?
Arduino can best be described as an easy to use open-source electronic
prototyping platform based on very flexible hardware and software. Arduino
boards have a microcontroller which can be programmed to do various tasks.
They can to read various different type inputs such as; read mail, light on a
photocell, wind change, a specific sound and turn it into an output; publish a
book, turn off the light, open the door, start the coffee machine.
There are exceptions, some chips are built with larger RAM, storage and
processor. But, most Arduino within the common price range will be within the
above specifications with some deviations allowed.
Most people buy clones of Arduino because they are less expensive than official
Arduino boards. We will warn you to be careful about buying boards from
companies you are not familiar with. If you do not want to buy from Arduino,
these companies are recommended http://www.adafruit.com/ and
http://www.sparkfun.com/. Their products are less pricy but also of similar
quality to official boards.
The board you buy should depend closely on the type of project you want to
undertake. For a small form project, you should consider Arduino pro mini and
for a wearable one, you should consider Sparkfun’s LilyPad board.
Official Arduino Boards
There are many types of Arduino as we have mentioned earlier. The Arduino
you will buy depends on what you want to do with it.
Below are a few examples of the Arduino boards that you will easily find out
there.
Arduino Uno
Arduino can best be described as an easy to use open-source electronic
prototyping platform based on very flexible hardware and software. Arduino
boards have a microcontroller which can be programmed to do various tasks.
They can to read various different type inputs such as; read mail, light on a
photocell, wind change, a specific sound and turn it into an output; publish a
book, turn off the light, open the door, start the coffee machine.
Because of its cheap price and ease of use, Arduino has become very popular for
makers that want to dabble in the creation of interactive hardware.
Unlike most previous programmable circuit boards, Arduino does not require
any extra hardware (Programmer) to load new code into the board.
You can buy Arduino directly from https://store.arduino.cc/ or from retail for a
price range of $22-$24.
The Board usually appears as a blue circuit board the size of a credit card
although varying models come in varying sizes. It comes with an Atmel
microcontroller which is a tiny computer, a USB connector, a power connector
and two rows of headers. The pins of the connectors are connected to the headers
which can be connected to virtually any electronics you can imagine.
There are usually 9 digital pins (I/O) and 4 analogue input channels. The I/O
pins can be used as input pins – to connect light sensors, temperature sensors,
sound sensors, keyboard or mouse, buttons… or they can be used as output pins
– to drive motors, control lights, connect displays, LED’s, check mail…The
USB also allows you to control your Arduino with your computer or control
your computer with the Arduino.
Arduino Leonardo
Arduino Leonardo is based on the ATmega32u. It has 20 digital I/O pins. It
contains everything you will need to support the microcontroller.
Arduino Ethernet
Arduino Ethernet is based on the ATmega328. It has 14 digital Input/Output
pins, six analog inputs and a 16 MHz crystal oscillator.
Arduino Due
Souped-up clock speed and ridiculous amounts of memory are the two things
that truly make the Due stand separate from the others.
Arduino Yun
Arduino Yun is the first of a new line of Wi-Fi products that seek to combine the
power Linux with the ease of use of Arduino. Arduino Yun is the combination of
an Arduino Leonardo (based on the Atmega32U4 processor) board with a Wi-Fi
system-ona-chip that runs Linino.
Arduino Mini
If you need to pack electronics into space not much larger than a postage stamp,
then the Arduino Mini is probably what you want.
For this lesson, we will use the Arduino Uno model as a sample.
Arduino Clones
Some Arduino clones that you may also desire to purchase include:
NodeMCU
NodeMCU is one of a kind. It is one of the most favorite alternatives to Arduino
available right now. It has a similar size to the Arduino mini and Nano, but it
packs a meaner punch.
Teensy 3
Teensy is one of the best Arduino alternatives available right now. They are very
similar to Arduino micro and Nano, much like NodeMCU. And much like the
lauded Node, they are even better than the official Arduino versions. A little bit
more expensive at $30, its processing power surpasses almost every other
microprocessor.
MSP430 Launchpad
Power consumption often proves to be the problem of most DIY builds, this is
why the MSP430 boards are impressive. Drawing in current claimed to be three
times as low as most other Arduino boards, it is exactly what is needed for builds
meant to run for long periods.
There are many Arduino clone other types; The STM32, PocketBeagle, DIY
(Homemade)…
Caution!
Do not fry your Arduino!
It might be a good idea to read this chapter before you actually unpack your
Arduino, Bad things may happen if you do not.
1. An Arduino can only supply 40mA output per pin, so you may not
want to drive a speaker or motor directly and you cannot directly
connect a LED without a resistor.
3. Do not put Arduino on a metal surface, it will short out the pins.
4. Do not draw more than 200mA from the total output pins altogether.
The ATmega chip supplies only 200mA total, so driving 10LED’s
will eventually kill your board.
5. Do not supply more than +5v to your input pins. Even a +0.5v
excess charge may damage your board. This also applies to
sensors… always check your voltages carefully before connecting
anything.
6. Do not supply more than the accepted voltage to the input pins. A
+5v ATmega chip has an absolute limit of +6v and +5v for a +3.3v
one.
7. The vin chip will fry if it takes in more than +12v. There is an
onboard voltage regulator that will fry if it takes more than +12v.
10. Be careful of reverse polarity. Swapping in a GND pin for the vin
or +5v pin will kill the board.
11. Do not connect a load to the vin pin while you are using USB
power.
12. Remove the carpet under your work desk to protect against static
charge.
If this seems needlessly complicated, but do not worry. Just pay special attention
to 1-5 and 10 and you will be fine.
Chapter 2
Hardware and Tools
For you to begin practicing with Arduino, you will probably need a few things to
get started with.
While you can learn Arduino programming with only the contents of your
Arduino Uno Budget Pack, please do make sure you have all the materials listed
below within the pack:
Solder sucker
Scientific calculator
Some/All the above are components you will need if you are to master Arduino
programming.
Power Supply
Arduino rarely comes with a power pack. For most projects, you will use the
USB cable to draw power from your computer. However, for any mobile project,
you will need to consider a 9V AC power supply to make it independent.
The Breadboard
The breadboard is a revolutionary design when it comes to programming a
board. Before its invention, it was necessary for an engineer to perfect his entire
board design on paper before doing any form of prototyping, or spend ruinous
amounts of money soldering and unsoldering the board (the board may get
damaged). The breadboard eliminated that limitation entirely by allowing its
users to program their circuits without permanently soldering anything until they
have perfected their designs.
A breadboard allows the user to prototype and experiment with different circuit
designs before doing any permanent soldering of the board.
The breadboard contains metal clips in the holes on their plastic housing which
are connected to each other by thin strips of conductive materials. These allow
currents to flow freely between one hole to the next, mimicking a circuit.
However, since the breadboard on its own is not self-powered, it requires power
to be sent through jumper wires from the Arduino. These wires are also
sometimes used to form circuits by connecting switches, resistors and other
components.
The jump cables are connected to the breadboard through two power rails clearly
visible on it, for both power and ground connections. The rail in between the
breadboard is to enable circuits to be more easily mounted on it.
Jump Wires
Jumper wires serve the very simple function of connecting your Arduino header
pins to the breadboard. As already stated above, using these to test-drive your
circuit allows you to see if your circuit is accurate without having to solder
Arduino. You will need jumper wires, if you want to use the breadboard.
Multimeter
A multimeter is a very vital part of working with electronics. It is a combination
of a voltmeter (measures voltage {AC and DC}), an ohmmeter (measures
resistance) and an ammeter (measures current). Because of the precision
required when working with Arduino, it becomes almost vital if you are to work
on the board without blowing out your board at the first attempt. It will solve a
lot of the Mathematical issues you will face when learning Arduino
Soldering is done to fix the wire onto the circuit so that it is not easily removed,
as shown below.
The soldering iron is applied (the solder melts onto the wire) and
removed swiftly
Although soldering the way I described above is sufficient for your needs, it is
not necessarily the best way to go about it. There are a lot of different ways to
perform soldering, you will find that the method I will describe below will be the
best way to come out of the process with a functional, undamaged, neat and
well-done board.
Please, stick with lead-free rosin core solder if you are majorly
concerned about your health. While the lead solder is significantly
cheaper, for health reasons, it has become fairly unpopular. If you
are using a lead solder, ensure proper ventilation of your work place.
It is advised that you tin the tip of and keep your soldering iron hot
for about 20 to 30 seconds before starting with any form of
soldering. The temperature should hover around 573K.
Tinning the tip of the soldering iron involves covering the tip of the
soldering iron (360 degrees) with solder.
Once your circuit is set and your soldering iron is ready, place your
solder along the tip of your soldering iron (use a copper wire to keep
the solder stable if you wish) and after about 1 to 2 seconds it should
have melted unto the tip.
Hold the solder on the tip and support it with wire, if you need to.
Now, place the tip containing the solder on the joint between your
two circuit components. Ensure the solder is well placed and remove
your soldering tip in a move that should not take more than 3 to 4
seconds. The solder should have been left between the joint.
Wait for a few minutes for the solder to cool and check it to see if
the soldered joint is solid. Do not attempt to blow wind unto the
joint in an attempt to make it cool rapidly. Once the soldered joint is
confirmed solid and good, you may proceed.
Diode
Diodes are like transistors, a semiconductor device. One of the many interesting
properties of the diode is that they conduct electrons only in one direction.
Arduino boards have a diode in series (directly connected one after the other)
with their power input jack to prevent you from reversing the power, which will
damage the chip.
Diodes are generally built with a forward voltage drop that ranges from 0.5v to
0.7v. If you measure the voltage before the diode and after the diode, the voltage
will be 600mV higher before the diode as compared to after it.
This, of course, has its limits, if the reverse voltage surpasses the diodes limit,
the diode will break, which will cause current to flow freely in the wrong
direction. In some diodes called zener diodes, this will be controlled. Zener
diodes only conduct current if the voltage exceeds a certain value.
This value is specific and constant, so zener diodes can act as a reference in
voltage regulators.
LED
The LED is much like a diode, this means that it will connect electricity only in
one direction. This is an internal limitation deliberately built into its function.
LEDs have both a cathode (negative) and an anode (positive).
The cathode is usually the flat and shorter leg side, while the anode often acts as
the round and longer leg.
LEDs often come in various color, Red, Green Orange, Blue… and with various
forward voltages often written as VL (This will become significant later on).
Since they emit low energy light, their voltage drop is much lower than light
sources that emit UV, Blue… light.
Electricity is the flow of electrons (electric charge carriers) from one point to
another.
Certain materials like wood, plastic, rubber… are called insulators because they
don’t have free electrons and thus cannot conduct electricity.
Any material with more electrons than protons (positively charged sub-particles)
is negatively charged, and any material with more protons than electrons is
positively charged.
An electric current can best be described as the quantifying value of charge per
unit of time, flowing through a medium that conducts electricity. In physics, it is
denoted by the symbol “A”, which stands for Ampere and can be denoted by:
I = C/t
Batteries have two sides, a cathode (the negative side that contains a lot of
electrons) and an anode (the positive side that contains very few electrons).
Since electrons generally seek to move to regions that lack them in sufficient
numbers, the electrons in the cathode will seek to move to the anode, which will
generate an electromotive potential (EMF).
The EMF stored in a battery is what lites an LED and rotates a motor. This EMF
is also called the potential difference, or more popularly Voltage (V/U) and is
represented as J/C.
The amount of energy a battery can release per second varies from one design to
another. This peculiarity of batteries and other voltage generation units is
described as Power and is designated by the unit J/s, which is generally referred
to as Wattage.
When drawing a circuit, the power will be drawn as if it flows from the Anode to
the cathode for convenience. In reality, the current will flow from the cathode to
the anode (due to the difference in the number of electrons on both sides of the
divide).
Most Batteries, are built to regulate how fast this happens, and that determines
their wattage.
Resistors are represented by the symbol “Ω”. They are best described as
electronic components that limit the free-flow of electrons within themselves.
This is useful in reducing the discharge rate, which is how fast electrons move
from cathode to anode. Its also for limiting how strongly (voltage) electrons flow
through the circuit.
It is ideal for most circuits that these values (Voltage/Discharge rate) be limited
because of the delicate nature of most circuit components that come with
Arduino.
To understand the value of the resistor (1000 Ω, 200 Ω, 0.3 Ω…), it is necessary
to calculate for them using the color code.
The first 2 (or 3) bands are the 2 (or 3) first digits of the value, and the 3rd (or
4th) band is the power of ten that comes after those 2 (or 3) digits.
This is sometimes called the multiplier; it is just the number of zeros you have to
add.
The last band is the tolerance and is usually silver or gold. An example is; red,
red, red, gold (22 x 100Ω = 2,200Ω = 22 x 10² Ω = 2.2kΩ with a tolerance of
5%).
Another example will be; green, blue, black, brown, red (560 x 10Ω = 5,600Ω =
5.6kΩ, with a tolerance of 2%).
There exists a relationship between the resistance, the voltage and the current
which can be calculated using Ohm's Law.
I = V/R
where I is the current (Amps), V the voltage (Volts), and R the resistance
(Ohms).
This is the most important formula in any electronic calculation you will do for
Arduino, so please remember it!
The Capacitor
A capacitor is a small electronic component that stores electric charges for a
circuit. Capacitors are used in Arduino to give the programmer more control
over how power flows in the circuit.
Installation:
For Windows:
Go to https://www.arduino.cc/en/Main/Software, select download
and click on Windows installer.
Click download.
Select the appropriate boxes (you will need the Arduino Software
and the USB driver).
An installation folder will be requested, click on next or type in
another folder.
Click install.
You will need to wait for a few minutes, and when the installion is
complete, launch the Arduino IDE.
For Ubuntu:
Go to the site, go to Download, and select the Linux version.
Click download.
cd Downloads
What the above commands do is: opens the Downloads folder, then unzip the
downloaded file, it then moves the unzipped file to “/opt/” folder, and finally, it
will run the install script.
The install script will then create a desktop file, and a MIME type file will also
be created to associate “.ino” files with the IDE. Finally, add “a = append” user
to the 'dialout' group (-G). This will allow the IDE to access the serial ports.
Upon opening the IDE, you will notice the greyed out “Tools > Port”. Upon
successfully adding your chosen ‘dailout’ group to the IDE, the option will
become enabled. You will have to close the IDE and reopen it for this to happen.
You will need the Teensyduino add-on for the Arduino IDE if you have a
Teensy board. A comprehensive installation guide can be found here
https://www.pjrc.com/teensy/td_download.html/.
Teensyduino does not support the latest versions (1.6.10 & 1.6.11) of the
Arduino IDE, for now, so you will have to download this version (1.6.9).
You may come across an error while installing Arduino: If this is the case, try
running the command
Then from the above installation steps for ubuntu, try running: /opt/arduino-
1.6.6/install.sh again.
Chapter 3
Working with Arduino
To begin using Arduino, please make sure you have all the above listed vital
components, and that you have followed the necessary steps to download the
IDE onto your computer.
Once you have done that, you may proceed to the next topic.
2. The next step is to tell the software the type of Arduino you will be
working with. On the header, select Tools, then hover over the
Board option and select Arduino Uno (or whatever other board
you bought).
3. The next step is to plug in your Arduino using the USB cable that
was illustrated above. Please do note carefully the port through
which your Arduino was connected. It will become relevant shortly.
The boards LED will light up upon you doing this.
4. Then you will need to select the communication port the Arduino is
connected to. Do this by selecting Tools from the header and then
clicking on Port. If your port is not already labelled with the
Arduino Uno, please unplug your Arduino from the computer, and
plug it back in again. Once your Board shows up, select the port
containing the Arduino. It should be labelled as “Arduino/Genuino
Uno”. On windows, the port will likely be labelled as “COM3” and
may be labelled as “dev/cu.usbmodem1461” on OS X.
6. This will make the Board LEDs labelled TX and RX to blink, and
the software will display the message “Done Uploading”.
8. Congratulations, you have just told your board what to do for the
very first time.
9. The Next step is thus to alter the code a little bit and see how the
modifications influence what the LED does and how it blinks.
10. The term compiling is often used to describe how the human-
readable code that you wrote is converted to a binary numbers file.
This is how Arduino reads your program (in binary). The binary file
is then uploaded to the Arduino’s memory during the upload.
Note: If the Port selected is not the one connected to the Arduino, an error
message will be displayed once you try uploading the Blink code. Refer to this
for a list of common errors on Arduino and how to solve them
“https://www.arduino.cc/en/Guide/Troubleshooting”.
Now to examine the code. One thing easily noted when you clicked on your
code is that some texts show up on your workspace (the wide typing space that
covers your screen when you open the software). This is the code that tells the
Board what to do.
Arduino has no programming language of its own. The codes you will write to
use your Arduino are simply combinations of the C and C++ programming
languages.
The first 14 or so lines will be lighter than the rest, and examining them closely
will show that they are placed within these signs “*/” and “/*”. This is what is
called a comment: A comment is a line of words that come before or after a code
describing what the code does or other important things to the coder, yet does
not influence what the code does.
This is a setup routine thus it will only run once every single time the Arduino is
started.
Void is a data type whereby is no information is returned by the setup.
The two brackets shown above are something used to pass data every function.
Since setup requires no data, the brackets are empty (This will be covered better
later into the book).
Everything that exists between curly brackets in the code is code that executes
while setup itself is running. Brackets in Arduino sketches are meant to be
closed, please always make sure you do this if you do not want to get error
messages. The software should normally notify you of any unclosed code, by
highlighting the piece for you or simply highlighting the closing bracket.
“pinMode(13, OUTPUT);” The command is the first command within the code
that alters the way your board works.
You might be able to guess by the name; it has to do with the rows of pins on
your board. These pins can either be output or input as described above. We will
want to make out pin number 13 an output. The pinMode is a value already
described by the software itself, thus it is a constant. It designates that what the
values within the brackets change is the mode of the pins (output or input).
Constants are designated with a blue color in the software (if it is not modified).
The first number designates the pin number you are modifying as 13 because the
blinking LED is connected to pin number 13. The comma is to make way for
another constant to be added (the software will treat the comma as a break
between two values describing pinMode).
The output value changes the pin number 13 to an output. The value is 1 as
opposed to input, which has a value of 0. Thus “pinMode(13, OUTPUT)” can
be written as “pinMode(13,1)”.
Every Arduino IDE statement is ended with a semicolon (;), as can be noticed in
the above statement.
What this does is designate the pin number 13 as high, therefore writing
something digitally onto the board. The high value makes pin 13 connect
internally to the 5V pin. Since the LED is now connected across the ground and
to pin 13, there will now be a 5v current passing through the LED, which makes
it light up.
Note: Do not ground the pin 13 once this command has executed. It will fry
your board.
This complimentary value to the “HIGH” value is “LOW”. This value can also
be written as “1” for the former and “0” for the latter or “true” and “false” for
the same. Should the value be “low”, this sets the pin 13 to ground, meaning no
current will now pass through it and the LED will switch off.
The “delay” function, like its name implies, delays the code for exactly the
stated amount of time (in milliseconds: 1000 = 1sec), before allowing the
Arduino to execute the next command.
Once the Arduino reads to line 29 (the end of the “void loop(){”), it starts over
at line 25 again because of the loop you have created.
Interpreting the code shows that we are telling the LED to switch on and the
switch off for 1second (delay), before coming on again and repeat the steps
again. This causes the witnessed blinking that happens.
Note: if the position of “13” within the code is instead written as “led”, you will
see the variable “int led = 13;” written before the rest of the code. This tells the
IDE to let you code “13” as “led”. Therefore, for the rest of the code “led” will
mean “13”. This line of code is called a declaration.
Sketch
On Arduino, A sketch is just another name used to describe what might be a
code when working with anything else, not Arduino. The sketch tells the board
how to behave, and what functions it needs to perform.
Using a Resistor
As you really get into Arduino programming, it gets more complicated. To be
honest, making what passes for a small bulb blink is not something really
impressive. That’s why you will learn how to add a resistor here.
The more LEDs you connect to your Arduino, the greater the true value of your
current and power distorts. This means you will need to know the total resistance
your LEDs will give the Electricity flow within the board.
You will connect the resistor in series with the LED (one resistor connected
directly to the LED). Since we know the voltage of the Arduino output pin is
+5V, adding the voltage of the LEDs to that of the resistors (VL + VR) should
give a value not exceeding 5V.
Since the current passing through the resistor is equal to the one through the
LED; IL = IR.
This will let us calculate the value of the resistor that should be connected to the
LED (R).
Note: substitute 5V for 3.3V if you happen to be using a 3.3V Arduino. Your LED
datasheet will tell you what your LEDs voltage and amperage is (VL and IL).
Your amperage must not exceed 20mA, anything higher will fry your LED as
cautioned in chapter 1. Your calculated R will not be exactly what you have, so
take the resistor with the next higher value to it (it should not exceed +1Ω, or
your LED may light up weakly).
You will also calculate the resistance of your LED using the above method or
online using this application (https://play.google.com/store/apps/details?
id=it.android.demi.elettronica&hl=en) or this tool
(http://led.linear1.org/1led.wiz).
Continuing
The resistor can be connected to either the anode or cathode of the LED without
affecting the circuit, as long as it is in series with the LED.
You will now need to connect a red jumper cable from pin labelled
as 5v to the positive horizontal rail on the breadboard.
Your next step is to plug a yellow pin into pin 13 and the other end
should be plugged in any of the labelled 10 rows on the breadboard
(c10).
You will next need to connect another blue wire from your negative
ground rail to any other row on the breadboard (c18).
The next step is now for you to plug your resistor into row d18 (the
row next to the one you chose above), with the other leg plugged
just under your yellow cable in c11.
Finally, you will need to connect your LED’s cathode to the resistor
at d11 and connect the Anode to the yellow wire at d10.
Uploading your new program will light up your LED again. The
current runs through the resistor, into your LED and back into the
Arduino in a loop with a delay value (????).
Arduino sketch examples in your Arduino IDE are a great way to learn Arduino
programming. Just load the examples, and compare it to your own code
(debugging) to fix any problems that may come up.
Note: You may need to trim the legs of your resistor in order to reduce the
chances of any open leg coming in contact with other wires and shorting the
board.
More LEDs
This is something very easily done with Arduino and a small breadboard. This
will be done similarly to what was done with the resistor, but a little differently.
The next step is similar to what you did in the one LED example
(connect the 5V pin to the bottom of the first positive rail using the
red wire, connect the ground pin to the bottom of the first negative
rail using the blue cord. Connect pin 13 with the yellow cable as
shown before). Repeat the rest of the first tutorial to add the other
blue cable, resistor and LED.
Add the remaining LEDs with the same pattern as the first slowly
going down.
Now you are to change the position of the yellow wire on pin 13 to
pin 6 and add another yellow connecting from pin 5 to f11 on the
breadboard.
Do the same for the remaining pins, slowly going from pin 4 – 3.
Coding
The first step to coding is to perform certain declarations you may need to use in
the rest of your code.
You can start by declaring “int timer = 200;”, this tells the
compiler that an integer called “timer” should have a value of
“200”.
Declare the “void setup() {”, then unlike before within the “{”, you
will declare;
pinMode(thisPin, OUTPUT);
What this means is that the setup will configure the pins 3 to 7 as
output, as the code had declared that “let “thisPin” be 3, let
“thisPin” be < 8, let “thisPin” be all values (integers) greater or
equal to 3 but less than 8, now set “thisPin” as output.
This short piece of code together with the set the code into a
changing mini loop. Each time the loop repeats, the value of
“thisPin” is increased by 1. Thus, by the next loop instead of 3, the
value of “thisPin” will now be set to 4. This will repeat itself over
and over again until the loop is complete.
To continue with the rest of the code, you will now need to set the
digitalwrite(thisPin, HIGH);” together with the rest of the blink
code. If you followed the blink example, then you already know
what that does.
This tells the loop to execute the command once before changing the value of
“thisPin” to the next one.
Since we don’t want to have the LEDs turn on one after the other
before turning off, we will include “digitalwrite(thisPin, LOW);”
after declaring the “delay(timer)”. This makes the LED turn off
after the delay.
However, since the value of “thisPin” changes as the loop repeats,
the LED changes as the light flashes. This causes the LEDs to flash
one after the other in a smooth row, from the one connected to pin 3
to the one connected to pin 7.
This does exactly what the above code does, but instead of increasing the value
of “thisPin” as the mini-loop runs, it decreases it till it gets to 3, before starting
again. “>=” means greater or equal to (the value will include the integer), “<=”
means lower than or equal to (the value will include the integer), “<” means less
than ( the value does not include the integer), “>” means greater than (the value
does not include the integer).
Optimizing
The above code is an example of optimized code. It does everything you need it
to do while requiring only the shortest amount of code.
Optimization in coding is the process of reducing the code to the bare minimum
required for it to carry out the exact function needed. An optimized code is one
containing no extra words that can be done in another way to make it a shorter
code.
There are many ways to write code. The blink code for multiple LEDs, as shown
above, could be written in a different way. Another way to write this code is:
void setup() {
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
}
void loop() {
for (int thisPin = 3; thisPin < 8; thisPin++) {
digitalWrite(thisPin, HIGH);
delay(timer);
digitalWrite(thisPin, LOW);
}
This does exactly what the above code does. However, it is almost twice as long.
This is an unoptimized code.
The mark of a good programmer is the ability to write a code in the shortest
amount of words possible without affecting its action.
Another advantage of optimized codes is that they run faster than normal code
since the computer reads all the declarations faster. This might have no effect on
the speed of the light coming on, but as the code gets larger, the effect slowly
compounds and the code runs slower.
Chapter 4
Diving into the World of Arduino
Connect the LED again much like when you practised the blink
example, but change the pin position of the yellow cable to pin 9
from pin 13. Everything else will be the same. Connect you Arduino
back into the system and make sure your port is selected correctly.
int led = 9;
int brightness = 0;
int fadeAmount = 5;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(30);
}
What the code does is:
Upload your code and restart your Arduino. The LED will start
fading in and out.
Button
Connecting a button to Arduino is not very difficult. It is different from what
you have been doing so far because instead of just doing output code, for the
Arduino to function, you will need to do input. The Arduino will read the input
from the Button and interpret what to do based on the code you uploaded.
Much like you did with your first Arduino, connect the blue and red
cables to the power rails of your breadboard. Then connect the
yellow cable to pin 13 and d6.
Connect your resistor to the negative rail (we are not using another
cable to connect to the breadboard) and to d5.
Connect your LED to e5 and e6 using what you have learned so far.
Now that you have to code what your board looks like into your IDE
void loop() {
buttonState = digitalRead(buttonPin); // reads the state of the
pushbutton:
if (buttonState == LOW) // checks if pushbutton is currently pressed:
{
digitalWrite(ledPin, HIGH); // The LED turns on:
}
else // if the pushbutton is not pressed”:
{
digitalWrite(ledPin, LOW); // The LED turns off:
}
The interpretation for this code is fairly obvious. The Arduino reads the code
top-down, so if the button is pressed (current flows through the button, thus, it is
called HIGH), the LED turns on. If it is not pressed (no current flows through
the button, thus, it is called LOW), the LED goes off. This is the function of the
attributes “if” and “else”.
void loop() {
int buttonState = digitalRead(pushButton);
//reads the state of the pushbutton:
Serial.println(buttonState); // prints out the state of the button:
Delay(3); //this is purely for stability:
You can also do this by opening your file header link in the IDE following these
steps:
File -> Examples -> 01.Basics -> DigitalReadSerial. This opens a similar code to
the one above.
Once this has been done, a window opens up on your IDE at the upper right
corner. The number within the code “serial.begin();” is called the data speed in
bits per seconds.
By changing the values described, you can easily see what is actually happening
on the board, whether the pin 2 is actually HIGH or if it is LOW or if pin 13 is
actually output or input. This makes the serial monitor code a very handy thing
when troubleshooting your Arduino.
A sensor can thus “listen” to the physical environment and interpret it in order to
produce digital data. The actuator on, the other hand, is a device that converts
energy into movement. Both devices are just two sides of a coin. An actuator
converts digital data into output and a sensor converts environmental factors into
an input.
Using the example of a heater, the heater will be designed to increase the
temperature to say “300K”. How does the heater however, know when the
temperature is 300K? This is done by a sensor that will have been included in
the heater’s design.
Arduino is capable of dealing with both Analog and Digital inputs but can only
handle digital outputs. Sensors usually communicate in analog, but most have a
small circuit that is capable of translating analogue into a digital value. This is
because while digital information is presented in binary, analog information is
presented as amplitude variations. Thus, analog pins on Arduino are input.
Temperature Sensor
A temperature sensor does as its name implies; it senses changes in temperature.
A popular basic program is to connect a temperature sensor to an LCD and
Arduino to make it display the current temperature. Most large appliances use it
to monitor their own internal temperature changes to prevent damaging rises in
temperature.
Photoresistor
This is basically a light-dependent resistor. Its resistance varies with the intensity
of the light to which it is exposed. This is used as a sensor to build equipment
that only works when there is light, or that shuts down when there is light, like a
light-sensitive coffeemaker.
Sound Sensor
This has proven to be very popular with makers of voice changers. The sensor is
capable of detecting changes in the surrounding sound, and it interprets these
changes as data. It usually has adjustable sensitivity.
Knock Sensor
This is used to build knock sensitive locks. They detect the sound of a knock.
For most builds, they are connected to LEDs that turn on when the sensor detects
someone knocking.
There are many other sensor types available, and we cannot list them all.
Pulse-Width Modulation
Pulse-Width Modulation is a type of digital signaling that has proven incredibly
useful to programmers everywhere. It is used by engineers and circuit designers
to create circuitry with sophisticated controls.
PWM allows the programmer to change how long Arduino pin spends at HIGH
in analog at a consistent interval.
The term duty cycle is generally used to describe this difference in the amount of
time a signal is high compared to when it is low. This is calculated in
percentages. The “on-time” describes when the signal is high.
Thus, if a signal (5V) has a duty cycle of 50%, you are getting only 2.5V of
electricity in reality.
Apart from dimming LEDs, this is also used to the reduce power consumption of
Arduino by altering digitally how much current is supplied without actually
touching the board.
Switches
A switch is a mechanical device that is capable of either breaking a circuit or
connecting it. It is just one small pushbutton in a completed board. However, its
importance is not depicted by its small size. Any Arduino board that was built
for use must have a switch, this is to give a degree of control to the user,
allowing him/her to control whether the device should be currently working or
not.
A Sensor Sketch
This will be an example using an actual sensor. We will be demonstrating this
using a potentiometer. The attempt is to build Arduino that is capable of sensing
sound waves.
VCC, Echo, Ground and Trig are the four pins that can be found in an HC-SR04
Ultrasonic module. To make Arduino that can sense distance, we connect the
shields VCC pin to the 5V pin on Arduino, the Ground pin connects to the other
Ground pin, while the Trig and Echo pins connect to pin 9 and 10 on the
Arduino.
The code will be found here. The comments within the code explain what the
various code sections do.
https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
The distance is calculated by multiplying the duration by 0.034 and dividing the
result by 2. This is a fairly simple example of a sensor sketch.
Arduino Logic
void setup( ){
statements-1;
.
.
.
statement-n;
}
void loop ( ){
statement-1;
.
.
.
statement-n;
}
The above is a simple example of what an Arduino code should look like. Most
Arduino codes will follow this simple basic design. There are two blocks to
Arduino programming, the Preparation and the Execution. Each block is
always enclosed in curly braces. The setup (), is the preparation block. Loop () is
the execution block, and everything contained within it is what the Arduino
reads to determine its function.
The setup function starts serial communication. It is where you declare whether
your pin is to be output or input as we had explained above. Once setup has been
declared the board starts reading pin numbers and setting them as input/output.
void setup ( )
{
pinMode (pin-number, OUTPUT); // this will set the ‘pin-
number’ as an output
pinMode (pin-number, INPUT); // this will set the ‘pin-
number’ as an input
}
The codes in-between the loop are executed continuously. The code runs from
the beginning of the curly bracket to the end of it, before returning to the
beginning to start again, until the Arduino is switched off.
Void loop ( ){
digitalWrite (pin-number,HIGH); // this will turn ON the
component connected to the ‘pin-number’
delay (500); // this makes the board keep its current configuration
for 0.5s
digitalWrite (pin-number, LOW); // this will turn OFF the
component connected to the ‘pin-number’
delay (500); // this makes the board keep its current configuration
for 0.5s
}
Declaration sometimes comes before the setup, but it is always read as part of
the setup. These usually take the form of the int attribute, which means integer.
They are used to change certain functions about how the code is interpreted once
it starts executing.
Variables
Constants
Floating Point Constants: This variable is similar to integer constants. They
are used to make code readable. They allow the use of scientific variables like e
and E.
HIGH | LOW: These variables specify the two values of a pin (HIGH/LOW).
For Input: HIGH is reported when the voltage at the pin is greater than 3.0V for
5V boards and 2.0V for 3.3V boards OR for Output: HIGH is reported at 5V
for 5V boards and 3.3V for 3.3V boards.
For Input: LOW is reported when the voltage is at 1.5V for 5V boards and 1.0V
for 3.3V boards OR for Output: LOW is reported as 0V for both 5V and 3.3V
boards.
true | false ; These are Boolean constants. False is defined as 0 and true is
defined as 1. Any integer that is non-zero is true, but true is often used to
represent a true statement. It is typed in lower case, unlike the other variables.
Data Types
Variable datatypes that exceed their maximum or minimum capacity are said to
overflow. This causes unpredictable results. To avoid this problem, some
programmers use unsigned datatypes like “unsigned int, unsigned long,
unsigned char”.
String(val); String(val, base); String(val, decimalPlaces); This constructs an
instance of the string class. It will return a single instance of the string class. It
allows multiple data types.
array ; This is variables in a collection that can be accessed with an index
number. Examples are;
int my[6];
int myT[] = {2,4,6,8};
int myTs[6] = {2,4,-8,3,
Char message[6] = “hello”;
All the above methods are valid for the declaration of an array.
This means that the last declarable index for an array is “n-1”. C++ does not
check if the array you declared is legal or not. Be careful not to exceed the
number of arrays you declared if you do not want errors.
float : This is a datatype for numbers with decimal points. It is popularly used to
approximate analog and continuous values due to their greater resolution as
compared to integers.
int: These are the primary datatype. It is a number storage and stores a 2-byte (2
bit) value. They store negative numbers by “2’s complement math” and the
highest bit is called the “sign” bit.
long: these are variables that store 4-byte (32 bit), they are extended size
variables for number storage. L is added to at least a number when doing real
math with integers.
string: There are multiple versions string constructs but they can all be
represented in two ways. A string can be made out of a datatype or from an array
(made from type char) and simply null-terminate it. Examples for the first type
will be described in function. Strings are normally automatically terminated
with a null character “ASCII code 0”. This allows the function “serialPrintln()”
and others like it to tell where a string ends and terminate it there. Strings have
one more character than the text it contains.
char str1[15];
char Str1[8] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’};
char str7[8] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘\g’};
char str8[] = “Arduino”;
char str9[8] = “Arduino”;
char str5[15] = “Arduino”;
All the above strings are correct and will run without error.
Note: Strings are always defined in a double quote (“bvc”) while characters are
in a single quote (‘fds’).
void: This is used only for function declarations. They signify that the function
is not to return any information to the function it was called from.
loop(): This does exactly what its name says. It runs after setup and does so
forever and without end. It is what actively controls the board.
Arithmetic Operators
% (remainder) : This calculates the remainder after an arithmetic division
operation. It does not work on floats and is useful in keeping variables
within range. If its first value is negative, the result will be negative.
Should any of its datatype be float or double, floating point math will be
used to obtain the result.
+ (addition) :
continue : This structure skips the rest of the loops current iteration. It is a
conditional statement containing conditions like (for, while…). The Arduino
checks the condition and proceeds if said condition is met.
do...while : This does the same thing as the while structure, but it will run
after the loop, thus, making the loop run at least once even if it does not
meet the required condition.
else : This allows for the grouping of multiple tests. It will only be executed
if the “if” statement result yields “false”. The tests will carry on until it
yields “true”. If none of the conditions report “true”, the default operation is
carried out. It is normally used with the “if” statement, to grant a bit more
control to the statement.
goto : This will transfer the program flow to a specified point in the
program. It allows the Arduino to skip certain codes. It lets the programmer
place his code without having to worry about where it is.
return : This is used to terminate a function and return the value of that
function should it be called.
&& (logical and) : This is a logic operator that reports “true” only if both
conditions are “true”.
|| (logical or) : This reports as “true” if even one of the 2 operator is “true”.
Comparison Operators
!= (not equal to) : It compares variables from both sides and reports “true”
if they are not the same, otherwise it reports “false”. You should only
compare variables of the same datatype, otherwise you may get
unpredictable results. Negative numbers are less than positive ones.
< (less than) : This compares variables on both sides of the operator. It will
return “true” if the operator on the left is less than that on the right. Negative
numbers are less than positive ones. You should only compare variables of
the same datatype, otherwise you may get unpredictable results.
<= (less than or equal to) : This compares variables on both sides of the
operator. It will return “true” if the operator on the left is less than or equal
to that on the right. Negative numbers are less than positive ones. You
should only compare variables of the same datatype, otherwise you may get
unpredictable results.
== (equal to) : It compares variables from both sides and reports “true” if
they are the same, otherwise it reports “false”. You should only compare
variables of the same datatype, otherwise you may get unpredictable results.
Negative numbers are less than positive ones.
> (greater than) : This compares variables on both sides of the operator. It
will return “true” if the operator on the left is greater than that on the right.
Positive numbers are greater than negative ones. You should only compare
variables of the same datatype, otherwise you may get unpredictable results.
>= (greater than or equal to) : This compares variables on both sides of
the operator. It will return “true” if the operator on the left is greater or equal
to the operator to the right. Positive numbers are greater than negative ones.
You should only compare variables of the same datatype, otherwise you may
get unpredictable results.
For further reading on the types of functions and syntaxes in Arduino, please
visit (http://arduino.cc/en/Reference/HomePage/). This is an Arduino reference
page that lists all the different types of functions for controlling the Arduino
board. Use this to code when coming up with your own projects that may not
have functions already listed in this book.
Functions
Functions in Arduino represent a modular series of code that performs a defined
task and then returns to the area of code from which the function was called. It is
like writing a mathematical equation in the code. For programmers
accomplished in the use of BASIC, functions allow the utility of subroutines.
Functions codify one action in a single place so that, the code only has to be
perfected once. This allows you to debug a single code and use that function an
unlimited amount of times without having to worry about errors.
Functions also influence your coding by making it modular. This makes the
program more readable and gives the programmer significant freedom in time
when coding, since a large part of the code would have been done as functions in
a previous work.
There are two required functions for Arduino to work, “setup()” and “loop()”.
All other functions must be created outside the curly brackets of these two
functions.
Examples:
The above code is a function. It allows for the multiplication of two integers “x”
and “y” and save the result into memory. We declared “myMultiplyFunction”
to be an integer containing two values “x” and “y”. Then, within the declaration,
we declare another integer “result”. By giving result a value of “x * y” (a
multiplication of “x” and “y”), the function is to return the result of that
multiplication and assign it to whatever contains the “myMultiplyFunction”.
Voidloop() {
int h = 2;
int g = 3;
int z;
z = myMultiplyFunction(h, g);
serial.print(z);
delay(3);
}
In the above code, we use the function we had declared by equating “z” to be
“myMultiplyFunction”, this mean that the values of “g” and “h” will substitute
for “x” and “y” in the above declared function and return “z as 6”. The
remaining code does serial print for the Arduino so that we can physically
observe the result.
The “myMultiply function can be declared above or below the rest of the code.
While it is preferable to declare a function before you use the function, it is not a
rule.
void setup(){
Serial.begin(9600);
}
void loop() {
int g = 2;
int h = 3;
int z;
k = myMultiplyFunction(g, h);
Serial.print(z);
delay(500);
}
Do not leave spaces in the declaration of names within your function. Arduino
will only accept 0-9, A-Z and the underscore (_), a function is not allowed to
start with a number.
A functions body must be contained within braces as we have seen with the
“voidloop(){” and “void setup(){” examples. The type of function is declared
first (int, void, const). The name of the function usually follows
(myMultiplyFunction, setup, loop). After this is to be the body of the function
contained within curly braces.
Within a functions body, a return type must always be present, even if it is void
like in “void loop”. The function must be called within the “void setup()” body,
by either simply declaring the name as in the above example or for those that are
not integers;
void DashedLine() {
serial.println( “----------” );
}
void loop() {
}
void setup() {
serial.begin(9600);
DashedLine();
}
As you will notice the function is called without any preceding “int” call. This is
because so far, we had been dealing with integers (numbers), but because the
new function is simply letters, we can call on it without preceding it with any
data type.
There are many different functions out there, we will list a few.
Digital I/O
digitalRead(pin, value) : This function reads the value of a specified digital pin
(HIGH/LOW).
Analog I/O
analogRead(pin) : This function reads the value from the specified analog pin.
analogReference(type) : This function configures the reference voltage for
analog input (DEFAULT/INTERNAL/EXTERNAL/INTERNAL1V1…)
analogWrite(pin, value) : This function writes an analog value to the specific
pin (PWM pins).
Math
abs(x) : This calculates the absolute value of a number. It returns +x if >= 0 and
-x if < 0.
max(x, y) : This calculates the maxima of two numbers. It returns the larger of
the two numbers
min(x, y) : This calculates the minimum of two numbers. It will return the
smaller of the numbers.
sq(x) : This will calculate the square root of a number. It returns the number’s
square root as data type double.
sqrt(x) : This calculates the square of a number. The datatype of the return is
double.
Random Numbers
random(min, max) ; or random(max) : This will generate pseudo random
numbers. It will return a number between min and max-1 with datatype long.
highByte(x) : This will extract the leftmost byte of a word. It will return the data
type byte.
lowByte() : This extracts the rightmost byte of a word. It returns data type byte.
Circuit Diagrams
We discussed resistors and voltages earlier. There is a lot more to learn if you
are to become proficient in Arduino.
A simple electric circuit, as can be seen, has a battery (supplies power), a resistor
(controls the current) and a LED (lights up to signify the circuit is on. More
components can be easily added to this circuit, like more resistors, LED, a
capacitor, a potentiometer, a switch…
The load of a circuit is the total amount of power all the components of the
circuit will need to function. If the power supplied to the circuit is smaller its
load, the circuit will not work (or will work slowly/weakly).
The “-/ -” represents the switch and the rest of the symbols
represent what they stand in for in a normal circuit.
Shields
They are modular circuits that can piggyback on your Arduino to give it extra
functions. Arduino shields are a must if you want to do something more than
light up a LED and print a few things on your computer. While you may be able
to rotate a motor with your Arduino, what if you wanted to connect to twitter
with it?
Shield were built in the same spirit as that of Arduino. Easy to use, cheap, small
and functional are the best words to describe Arduino shields. Much like
Arduino itself, they come in various shapes, sizes and functionalities.
It is possible to add more than one shield to Arduino, in fact, the only thing that
limits the number of shields that can be added to Arduino is the circuit load.
Shields often come with a library or an example sketch. This makes working
with shields a very easy thing to do. For an experienced Arduino user, it is
possible to connect Arduino to a shield and get it working in just 5 minutes.
Arduino shields are built with a similar form as Arduino boards themselves.
Power and ground pins will be on one eight pin header, and there will be other
analog pins on a six-pin header next to the eight pins. Digital pins will usually
occupy the other side, an eight-pin header that is seperate from another ten-pin
by some spacing.
Some shields will require another connection to the Arduino's ICSP header as
shown above (the2- 3 pins at the vertical left). Most Arduino shields will use
every pin available on the board, although some take only a few.
Some shields are capable of communication using SPI, I2C or serial, while others
use analog inputs or Arduino’s interrupts.
Note: Do not use overlapping pins when using multiple Arduino shields.
Types of Shields
Prototyping Shields and Others
Protoshield Kit
This Shield works as a big prototyping area. It is the most popular prototyping
shield. A breadboard can be connected to it, or you can just solder directly to the
board.
Go-Between Shield
This shield solves the issue of overlapping pins by sitting between two shields
and swapping the pins of the top shield.
ProtoSrew Shield
This is a useful tool for linking Arduino to external motors and heavy-duty
sensors. It is similar to the ProtoShield, but each pin is linked to a new screw
terminal.
Danger Shield
This shield typically contains everything from potentiometers, to display, to a
couple of other impressive sensors. The danger shield allows you to mess around
with your Arduino by warning you of danger. It is very important when learning
the ins and outs of using Arduino.
Joystick Shield
This is used to turn the Arduino into a control tool. It contains what might be a
controller, thus allowing you to use your Arduino to control things like robots.
MicroSD Shield
Because of the limited space typical in most Arduino, it might make sense to
connect a microSD shield to the board. This will allow you to input a microSD
in your board and use its memory space for extra storage functions. It typically
comes with an SD library.
XBee Shield
XBee provides Arduino with the ability to communicate wirelessly. While it
cannot connect to world wide web, it can be used to wirelessly start sprinklers,
lights, and coffee machines. It is also very cheap and easy to use.
GPS Shield
Like its name suggests, this shield allows you to use the Global Positioning
system with Arduino. With this, you will always know where you Arduino is.
Spectrum Shield
This allows Arduino to listen to various sounds and turn them into frequencies,
before presenting it in a graphic equalizer display.
Display Shields
Color LCD Shield
This is a small screen component that allows you to display text and pictures
with a 128x128 cell phone color LCD.
CMUCam Shield
This will turn Arduino into a camera. This component is a small camera that
allows the user the option of vision. It is especially useful to users who may be
using their Arduino to control small robots by allowing the user to visually track
it.
Motorz! Shields!
PWM Shield
As I had mentioned earlier, pulse-width modulation can also be used to drive
servo-motors, beyond just dimming LEDs. This shield allows Arduino a fine
range of control over servo motors.
Installing Shields
Preparations
Many shields are made without headers attached. This allows the user a degree
of freedom to alter how the headers are used (Straight male headers rather than
stackable headers or the other way around).
Attaching a header is a simple process with very few steps. You will need a few
things from your kit however. You will need solder, soldering iron, wet sponge,
Arduino board and 4 headers (the original ones or the new R3 ones). You may
also optionally have a soldering iron stand, solder wick and maybe a third hand.
Before you begin, make sure the headers you have match your Arduino footprint
(use the new shield header for R3 layouts and the old headers for Arduino with
that type of header layout).
There are two types of headers. If you will be stacking shields, it is advisable to
use the stackable header and the male header tor single shield works. Male
headers make a lower-profile stack when used to stack shields compared to
stackable headers, but, stackable headers allow you to still insert jumper cables
into the Arduino when the shields are stacked.
Note: stick to headers that have straight, rectangular and male pins for now.
They are easier to work with, and most Arduino components come adapted for
male header pins.
Assembly
Attaching the Header
Headers should be inserted into the shield first. Orientation is of utmost
importance. The headers should face the correct direction. Male pin headers
should enter the top of the shield and extend downwards. Solder the pins only
once you have the header facing the right direction.
Once the headers are inserted properly, flip the board so that the female side
rests on the flat work-table. Align all headers carefully so that they rest
perpendicular to the Shield.
Soldering
Carefully solder a single pin on each inserted header, this ensures that the
headers remain perpendicular to the shield (in the event of a shake). Ensure the
solder is not too much for each pin.
Testing
Carefully Align the Shield with Arduino and plug it in. This ensures that your
Shield headers are properly aligned. If it is not an immediate fit, please realign
the board and perform the above steps again until the fit is exact.
Soldering
Once your shield headers pass the above test, then solder the rest of the pins to
the shield. Once all your pins are soldered, please check for bad solder joints.
Bad Joints
There are possible mistakes when soldering. Please check that your solder
doesn’t link two pins together if you do not want a short-circuit. Also check for
cold solder joints (they are not soldered but look like they are).
Plug in
It is good practice to disconnect your Arduino before working on it. Now plug in
the Shield by matching Arduino headers to the ones on your shield. Please be
careful not to bend your header pin while doing this.
Tricks
A known trick is to use an old shield to aid in aligning the header.
Solder away.
Be careful not to burn your header by leaving the soldering iron on the pins for
too long.
Library
Arduino libraries are useful when a programmer needs to make a complex task
as simple as possible. These are contained as part of the extensive add-ons
available to all Arduino users. An example is writing a code to capacitive touch
sensing, while we could spend a few days writing and perfecting the code on our
own, we could just get a code from a great library and implement it into our
Arduino.
You can learn all about how to download and install libraries at the official
Arduino library website. It comes with great instructions about using the
Arduino IDE library manager. (https://www.arduino.cc/en/Guide/Libraries/).
You may also click on “Add .ZIP library” to install any “.zip” library you have
from elsewhere.
Manual Installation
First, you will have to download the library from the web
Edit the name of your pasted folder to remove any symbol that is
not A-Z and 0-9. If you do not do this, you will not be able to use it.
This is a very good project where you will get the much-needed practice on
soldering.
Arduino UNO
64 LEDs (3.3V)
Craft wire
Prototyping board
Crocodile clips
Because of the limited number of pins available on Arduino UNO, we will build
the 4x4x4 cube using multiplexing. This allows us to break down to 4 layers.
This means that we only need to control just 16 LEDs directly.
We simply need to activate a layer and the control pin to light a specific LED,
meaning that we can control all the 64 LEDs with just 20 pins total.
Each layer will be built with a common cathode which will lead to a single pin.
Each LED will be linked to the one above and below it, and since we have 16
layers of positive and 4 layers of negative LED pins, we can do this easily.
Fold the LEDs short leg and drill the needed holes in your wooden
placeholder. It needs to be very tight. The holes should be
equidistant from each other and the folded legs should be of the
same size. Follow the directions as shown in the picture.
Solder the short legs (cathode) on a thin craft wire as shown above.
Test the above configuration using the blink code by connecting a
resistor and ground to cathode (1 pin for all four), and 5V to each
anode and run it. It should light up all the LEDs. If not, all LEDs
light up, check your connections again.
Now do the same for all the remaining 60 LEDs and ensure the
connections are solid.
Then arrange all the 4 LEDs in a cube configuration and ensure the
vertical legs (anode) are soldered together while the cathode is
similarly linked per layer.
If you cannot get a perfect fit for anodes, use a clip to hold them
together and keep them at appropriate height. And ensure anode
only connects to anode. You may snip any out of place wire/leg to
ensure a smoother build.
Once you have your cube, connect the resistors to your prototyping
board and your board to the cube wire frame in what order you want
(LED to board first before resistor or resistor to board first before
LED).
Once your pins are finally connected (the 4 cathode layers to analog
pins 2 to 5, 16 LED anode pins to digital pin 0 to 13 and analog 0
and 1), and we are done.
Upload your code:
https://github.com/brucetsao/eLedCube/blob/master/LED_1cube_4x4x4_Blank_Show_/LED_
Now you can see what it does. You can modify the code by using
“plane(layer)number” to choose the LED you want to command. Ensure that
all other planes are HIGH before commanding a LED otherwise everything will
light up.
As an Arduino fan, the question should be, can you can build your own GPS
tracker with Arduino? Yes, you can. In this project, our aim is to build an
Arduino based GPS tracker.
We are using LoRa because of its low power requirement and long-distance
operation.
NEO-6M GPS module, a transmitter, a 16x2 LCD, 433MHZ LoRa module (or
whichever one is legalized in your locale), 433MHZ LoRa antenna, connecting
wires, Arduino Uno and the Arduino LoRa shield.
Upload the Gaber file generated by the PCB software and once your
file has been verified, you may use whichever payment option you
want.
Once you get the PCB, you may start assembling the board.
You will need two shields for this project, one for transmission and the other as a
receiver. The receiver will be the one with the LCD attached.
Now that you have the transmitter module ready, you may connect your GPS
module.
Connect the pins D4 to RX and D3 to TX, and ppower it with the 5V pin.
Coding:
Ensure that you have downloaded and installed the two libraries in your IDE
before proceeding.
https://circuitdigest.com/microcontroller-projects/lora-based-gps-tracker-using-
arduino-and-lora-shield
Once our codes are uploaded, power up the transmitter and the LED on the PCB
will start blinking. The receiver will similarly turn on and display the welcome
message we typed in the above code.
Once the transmitter receives data from the satellite, the LCD will immediately
display it.
The next step is to put the transmitter where you want; car, bag, etc. and you will
be able to track whoever is currently carrying the transmitter with the receiver.
The motion sensor will detect the movement of a trespasser and automatically
switch on for 40 seconds. How you code it depends mostly on how you want to
use it.
***Note: you will be connecting your project directly to the mains (230-240V).
Touching any live wire directly will can kill you. Be extra careful.***
We will connect an LED to Arduino’s pin 13 and the PIR data OUT
pin to Arduino’s pin 8. The LED will indicate that the light has
turned on or off.
Pin 9 of Arduino will connect to IN1 pin of the relay module and a
bulb will be connected to the mains of the Relay (one to mains
supply and the other wire to NO relay contact).
COM of the relay will link up with the other wire of main.
The sensor will link up with pin 8 on Arduino and its ground pin to
ground. Its main pin must be connected to the Arduino’s pin 13
through the breadboard.
The code below will then be loaded into the Arduino IDE:
https://www.maxphi.com/pir-motion-sensor-light
Once someone enters the range of the sensor, the sensor detects the movement
through infrared, it’s OUT pin changes from LOW to HIGH, and alerts the
Arduino which changes its configuration from relay pin HIGH to LOW.
Once the intruder leaves, the sensor no longer detects motion and changes its
configuration back to LOW from HIGH. This in turn causes Arduino to assume
a HIGH command at the relay pin.
This design is easily applicable as: Garage Lights, Bathroom Lights and Security
Lights.
From the short list of required hardware, this may very well be the easiest and
least demanding project you will do in this chapter.
From your Arduino board to your sensor, connect VCC to 5V pin
and GND to the GND pin.
Connect the Arduino’s pin 2 (digital) to the output signal pin on the
sensor.
https://maker.pro/arduino/tutorial/how-to-build-an-arduino-powered-motion-
sensor-alarm
The above code, once uploaded and the Arduino, sensor and buzzer set in a
position of our choice, will make the buzzer sound whenever someone is within
6-7m of the sensor.
The Arduino’s digital pin 2 is written as HIGH OUTPUT and this will cause the
condition for “intruder_detect()” to start running.
Intruder detected will be printed on the serial monitor and after a minute of the
intruder leaving the sensor range, the buzzer shuts down.
Sensitivity and time can be modified as liked within the code based on the sensor
type being used and its range.
Arduino Digital Clock with RTC
Much like the above project, we will need a few things:
Arduino UNO
2 LED
DS1307 RTC
The circuit uses a multiplexing technique to reduce the number of wires that are
used to link with Arduino while similarly reducing the power consumption
significantly.
The RTC module, keeps track of the time and compensates for drifts like leap
years. We only need hour and minute information though, so that is all we will
extract from it.
The circuit makes extensive use of the breadboard to link multiple pins to the
same Arduino pin. The colored chart describes what is linked to what.
To set the time, open the IDE include the library “DS1307RTC” you have
downloaded, ensure the time is correct and run the serial monitor.
https://electronics-project-hub.com/arduino-7-segment-display-clock-with-and-
without-rtc/
The next thing to do is to power up the module and watch it display the time.
The RTC though, is still vulnerable to temperature variations. For high accuracy,
you will need an RTC with inbuilt temperature compensated crystal.
Game Controller with Unity
The aim is to design an awesome game controller with very few steps. This
tutorial seeks to design a game controller powered by Arduino UNO with the
Unity game engine. The controller will be tested by using it to avoid objects.
A breadboard
Arduino Uno
An Uniduino plugin
Hook-up wires
You may purchase an Arduino starter kit that contains most of this from here
(https://www.makeuseof.com/tag/4-best-starter-kits-arduino-beginners/).
Once you have your circuit built as described above, open the code
StandardFirmata<Firmata<Examples found in files of your IDE.
Look for the plugin in the asset store and buy it. It is fairly cheap.
While it can be done without the plugin, you may want to go
(http://www.alanzucconi.com/2015/10/07/how-to-integrate-arduino-
with-unity/) here for that.
You can use unity to program a simple game that you can test your
controller with.
You will now need add a new script into the hierarchy by heading into Add
Component < New Script.
Next, you should rename the C Sharp object and add the new script to the
GameObject by clicking on Create < Add.
https://www.makeuseof.com/tag/make-custom-game-controller-arduino-unity/
Read the above code and note the comments to understand what it does.
Save the script and exit back to editor. There you will change the values for pot
pin number to 5, button pin number to 2, left edge to -9.5 and right edge to
9.5.
Add:
void Update ()
{
//We assign the value the arduino is reading from our potentionmeter to our
potValue variable
potValue = arduino.analogRead(potPinNumber);
}
So that we will not have to calibrate and calculate out potentiometer values, we
can add:
https://www.makeuseof.com/tag/make-custom-game-controller-arduino-unity/
Heading back to the script, we will use the remap functions to convert the pot
values into useable ones for our game.
mappedPot = potValue.Remap();
Click on save and the Mapped Pot values will now change with movement of
the potentiometer.
Now, open the script and assign your new values thus;
Now, you can click on play and the movement of your potentiometer will
correspond to your game character.
Hardware components:
10K resistor
A pushbutton switch
The resistors will connect to the LEDs cathode on one end and to D8 to D10 on
the other end. The LEDs on the other end are connected to both the resistor and
ground (cathode), and also connected to the 5V pin on the anode leg.
Once we have our circuit up and running, you can find the code here:
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
As can be seen from the code, it is very similar to blink a single LED.
With the exception of the “changelights()” function, the rest of the code is
almost the same.
The traffic lights can be changed in several ways to satisfy our own timing by
simply changing the values in the code.
And now, we have our traffic light controller.
A fairly nice way to round off right? Wrong.
Why don’t we alter the code to allow someone else to choose when it turns
RED without altering the code?
You would have noticed from the above that you did not use all the hardware
you were told to get.
Follow the circuit below:
The difference between the two circuits is academic. The button in this circuit is
connected to pin D12 and the switch now has a resistor attached to it (10K).
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
What the new code does is wait for 15 seconds after the button is pushed before
the light changes. This allows someone to control the lights by pushing the
button.
The original LEDs are connected as in the previous examples and the
pushbuttons have been removed. The new LED sets are connected to D11- D13
using a similar method to the earlier examples.
https://www.makeuseof.com/tag/arduino-traffic-light-controller/
Unlike the previous examples, when one set of lights is red, the other will turn
green and vice versa.
This is the same method that most street traffic controllers use.
However, since they do this over a large area without any wired input, they must
be communicating over the web.
Arduino can also do this. We will explore this avenue in our next chapter.
Chapter 7
Smart Appliances and The Power of the Web
We will be using Arduino boards and the free web services (http://freeboard.io/)
and (http://dweet.io). After this lesson, you should be able to build your own
internet of things dashboard for household automation applications.
You will need; Arduino Uno, DHT11 sensor (or DHT22), 4.7K resistor,
photocell (with 10K resistor), CC300 Wi-Fi chip (Adafruit CC300),
breadboard and finally, jumper cables.
Hardware Install
Connect the Arduino 5V pin to the positive rail on the breadboard,
and ground the board by connecting the ground pin to the negative
rail.
Place the CC300 board and the DHT sensor on the breadboard.
Connect pin 1 of DHT to the positive rail on the breadboard and pin
4 to the negative one.
Connect the sensor’s pin 2 to Arduino’s pin 7, and connect the 4.7K
resistor between pin1 and pin 2 of the sensor to complete that part of
the circuit.
Connect the cell in series with the 10K resistor on the breadboard
and connect the ground the other end of the resistor.
The common pin on the photocell should then connect to analog pin
A0.
Connect the Wi-Fi module by linking it’s IRQ pin to Arduino pin 3,
CS to pin 10 and VBAT to pin 5.
// Libraries
#include "DHT.h"
// DHT sensor
#define DHTPIN 7
#define DHTTYPE DHT11
// DHT instance
DHT dht(DHTPIN, DHTTYPE);
void setup()
{
// Initialize the Serial port
Serial.begin(9600);
// Init DHT
dht.begin();
}
void loop()
{
// Measure from DHT
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Measure light level
float sensor_reading = analogRead(A0);
float light = sensor_reading/1024*100;
// Display temperature
Serial.print("Temperature: ");
Serial.print((int)temperature);
Serial.println(" C");
// Display humidity
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println("%");
// Display light level
Serial.print("Light: ");
Serial.print(light);
Serial.println("%");
Serial.println("");
// Wait 500 ms
delay(500);
}
The above code is a simple one designed to test if the sensors are working or not.
As you can see, the code is explained using comments. The complete code is in
the library mentioned earlier.
Upload the sketch and the data will display something like:
Temperature: 25 C
Humidity: 36.00%
Light: 83.79%
Now that the sensors are working, we need to make it capable of connecting
electronically to Wi-Fi. Dweet has “things”, this is a place where you upload
data through http requests. Should you upload data to a new thing that has not
been created before, it would be instantly created.
The code below automatically connects to the freeboard server and uploads the
data.
The above code can be modified to suite our own needs as noted by the
comments scattered through it. Now that the data has been sent to freeboard,
Arduino will consistently send code over to the server.
We will be doing this using a 5V relay to switch a power outlet on and off. The
Arduino will use a sensor to determine when to switch the relay.
While it is possible to switch on the device alone directly, due to the dangers of
leaving an unmonitored switch on, it is always better to just control the switch
relay alone. Not to mention, the ability to use a single Arduino to switch on
multiple devices.
The plan is to install a 5V relay inside a power outlet box using a grounded
extension cord.
Arduino UNO, electrical outlet box, electrical outlet, power strip, Signal, VCC
and ground wires, SRD-05VDC-SL-C 5V relay, electrical outlet box cover plate
and a 3/8” NM/SE connector.
Remove a knock out plugs from the outlet box, and install the
NM/SE connector in its place.
Remove some of the outer sheathing of the cord and feed it into the
electric outlet box through the connector (3-4”).
Carefully off 4” of the live wire and remove about ¼” of the cut off
live wire insulator and insert it in the NO terminal of the relay, and
connect the ground, signal and VCC wires to the relay.
Connect the remaining live wire into the C terminal of the relay and
ensure it is a fit.
Secure all the wires and the relay in the box and make sure they can
all fit well.
Secure the live wire from the NO relay terminal to the hot terminal
of the power outlet (the one with the smaller slot) with the gold
screws.
The neutral wire from the power cord should also be secured to the
neutral terminal of the outlet (left side with larger slots) with the
silver screw.
Also, secure the ground wire to the ground terminal outlet (D-
shaped) with the green screw.
Screw the outlet into the box and ensure it fits, then cover it up and
screw in the cover.
We now have an outlet that can be easily controlled by Arduino. All that
remains, is to connect the pins to your Arduino and upload code, and we are
done.
The connections should follow the above design. The USB will lead to the
computer, or you may attach a battery to it using one of the examples given
previously. The bulb can be anything, from your coffee machine to your washing
machine.
#include <dht.h>
dht DHT;
#defines DHT11_PIN 7
int pinOut = 8;
void setup(){
Serial.begin(9600);
pinMode(8, OUTPUT);
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
// DHT.humidity can be changed to DHT.temperature
if (DHT.humidity <= 40){
// the value <= 40 can be changed to any humidity or temperature
digitalWrite(pinOut, HIGH);
} // tells the pin to allow current flow. The bulb turns on
else {
digitalWrite(pinOut, LOW);
} // tells the pin to prevent current flow. The bulb goes off
delay(500);
}
The above code is similar to the one we uploaded previously to send data to the
web. It takes in the humidity and temperature data and tells the power outlet to
switch on when humidity reaches 40%. This can also be done to tell the bulb to
turn on when temperature is below 300K by changing the values as noted in the
code.
We will explain in this tutorial, how to control Arduino directly from your phone
and with a web browser
An Arduino robot
You may completely remove the distance sensor from the Arduino
if you wish and connect pin 9-12 of Arduino to IN1-IN4 of the
Motor module as above, and the Enable pins should connect to 5V
using a jumper.
The code is explained using comments. From what we had done above and a
little experimentation, the code becomes clearer still.
The next step is to open the Bluetooth controller application. The application can
be gotten on google play.
Configure the control keys in app paying attention to how you configured it in
code.
When say the forward key is pressed, Arduino receives the data through
Bluetooth communication as 1 and Arduino will thus make IN1 and IN3 HIGH
while IN2 and IN4 will become LOW. This achieves a forward motion. The
same system will be used for the other motions, granting free command over the
motions of the robot.
As with the Bluetooth example where we did not connect the TX pin because it
was not needed, the same is true for all modules. The circuit you will build with
a module is highly dependent on what you want to do with it, and thus, the kind
of information it will transmit.
The plan for this last project of ours is to build a Wi-Fi controller to any device
with Wi-Fi access using a Wi-Fi nunchuk that has been made from an ESP8266.
While the aim of this tutorial is to produce a serial terminal data, it is very easy
to use another Arduino to read the serial string output and act on it.
We will need the following hardware:
Arduino Mega (this is because it has two serial ports, since using UNO might
make the Arduino impossible to reprogram as the module will assume control of
the programing port once it is running), ESP8266 Wi-Fi module, jumper wires,
breadboard, FTDI chip or another Arduino and battery.
Connect a red jumper to the 3.3V power pin, a brown one to the
3.3V pin (enables chip), a white one to TX, a grey one to RX and a
black one to ground.
To set up a server to communicate with the ESP8266, we use the code on this
instructable page (https://github.com/splatspace/ esprelay/). It allows the
communication of two devices to log on to any computer that is running the
code.
You will need to install Python 2.7 on your PC in order to run the code.
Add a battery to the model because the FTDI module is not built
with a sufficient power source. This will cause the ESP8266 to
restart regularly if it isn’t fixed.
You may add another Arduino in the place of an FTDI chip if you
wish to use the Arduino to control something.
Load the terminal program you are using. The strings from the
nunchuk will be seen scrolling down the screen as they are received.
AT+RST
AT+CIPCLOSE
Type the codes below to enable communication with the transmitter of the
nunchuk;
AT+CIPCLOSE
You can now control what you want over the Wi-Fi.
Chapter 8
Troubleshooting Common Problems
There are a lot of steps to getting Arduino to do what you want, and should any
step be done wrong, it might fail to work/upload. There are a variety of problems
that crop up when using Arduino, yet, most of these problems can often be
traced to a handful of root causes.
Firmware on 8U2
The bootloader
The list of problems that may arise while using your Arduino is too long to list.
So, we will try to go through the most common problems that occur and
recommend ways with which you may quickly fix these issues.
Here are a couple of things to check first, if your Arduino is messing up.
Arduino IDE
The first step to dealing with any problem is to just reinstall Arduino IDE and
reupload your code. If this doesn’t work, you may check the following within
your IDE:
Ensure you correctly selected the right board in the Tools > Board
menu. This is because of differences in the ATmega chips in
differing Arduino types. See
(https://www.arduino.cc/en/Guide/Environment) for more
information on properly selecting your Arduino type.
Make sure that you selected the correct port to which you connected
Arduino. As I had mentioned earlier, unplug and re-plug Arduino to
the computer and carefully monitor the option that appears, if you
did not initially see your Arduino listed under Tools > Serial Port.
If you cannot find Arduino still, then follow the next steps.
Drivers
Drivers are what allows the IDE on your computer to communicate with the
Arduino. What happens when a USB cable is plugged into a system for the first
time is that, the computer accepts drivers that are stored on the board and installs
them. These drivers provide a virtual serial port. Most Arduino use USB CDC
(standard drivers) provided by the operating system while some use FTDI.
If your Arduino type does not appear in the Tools > Serial port menu, then the
driver was not installed.
For windows 7, connect the board again, open the device manager
and update your drivers for Arduino. Right click on the board and
point windows to the “.inf” file. It will be in the drivers/directory
of the IDE file.
After which you should logout and login for the changes to occur. Open Arduino
again and your port should appear.
Crash
Should the software crash at launch or work unnaturally slowly, or the Tools
menu seems to open too slowly.
Disable Bluetooth serial ports and that of any other networked COM
ports using Device Manager. Since Arduino IDE scans all the COM
ports on the computer upon startup and whenever the Tools menu is
open, these networked ports often cause delays and crashes
Ensure that the only program that scans all serial ports currently
open on your task manager is Arduino IDE. Some Applications that
do this are; virtual daemon tools, BlueSoleil, PDA sync apps…
Quit processing, vvv… should you be using them to read data from
the USB cable to Arduino
For Linux, you can try to run the IDE as a root file, and see what
changes
Direct Connection
Sometimes, the problem arises from physical disconnections from
the board.
Try disconnecting everything else from the board and uploading the
code.
Ensure Arduino is not touching anything metallic or conductive. As
we had earlier explained, it may ground the board.
The above steps should solve your problems. If they do not, proceed to the next
step.
The best way to check if your Arduino comes with a bootloader is to press reset.
If your Arduino LED blinks when you plug it in again, you have a bootloader. If
it doesn’t, then you do not have one.
If none of the above options work for you, the you may need to visit the Arduino
help Forum (http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?
board=troubleshoot). Please use the code tags in the forum toolbar to ensure the
output is in the proper format.
You will need to know, your operating system, Arduino type (with a picture if
possible), your exact problem (can’t upload to the board) and the error message
you receive when you try to upload after enabling verbose output (File >
Preferences > Show verbose output).
Syntax in Arduino
The most common error in Arduino syntax is due to the semicolon at the end of
a statement. The second most common error is due to a missing curly bracket.
Look for incorrect spellings, typos, wrong names for declared values, unallowed
lettering uses and wrong cases. Arduino code is case sensitive. If there’s an error
in your code, the software usually highlights the lines with such errors.
“java.lang.StackOverflowError”
This error often occurs because certain strings can confuse the IDE. Arduino
IDE does preliminary processing by manipulating code on the sketch using
regular expressions.
Look for certain sequences that have certain functions like double quotes, single
quotes, comments or backslashes. Some of these codes, while correct, may
confuse the IDE. An example is ‘“/’, or /”.
at com.oroinc.text.regex.Perl5Matcher._match(Perl5Matcher.java)
at com.oroinc.text.regex.Perl5Matcher._match(Perl5Matcher.java)
or
java.lang.StackOverflowError
at java.util.Vector.addElement(Unknown Source)
at java.util.Stack.push(Unknown Source)
at
com.oroinc.text.regex.Perl5Matcher._pushState(Perl5Matcher.java)
Try connecting the TX pin directly to RX, or ground it with a 10K resistor.
For the external battery, the jumper should lie on 2 pins closest that are closest
the power plug.
For USB powered projects, it should be the 2 pins that are closest to the USB
plug.
If you get the above error on your attempt to launch Arduino, ensure the
“Arduino.zip” files were correctly extracted. The lib directory should contain
“pde.jar” and be directly inside the Arduino directory.
Cygwin conflicts
6 [main] ? (3512) C:\Dev\arduino-0006\tools\avr\bin\avr-gcc.exe:
*** fatal error - C:\Dev\arduino-0006\tools\avr\bin\avr-gcc.exe: ***
system shared memory version mismatch detected -
0x75BE0084/0x75BE009C.
The above error displays when you have “Cygwin” running while you are using
Arduino. You can also just delete “cygwin1.dll” from your Arduino directory
and then replace it with “c:\cygwin\bin\”.
Arduino is the new kid in town, and everybody wants to know how it works. It is
our hope therefore, that having read through this book and participated in most if
not all of the projects, that you would have grasped what Arduino is all about.
To learn more about Arduino, you may visit the following websites:
Aswinth Raj, Lora Based GPS Tracker using Arduino and LoRa Shield,
CircuitDigest (2019)
https://blogs.umass.edu/Techbytes/2014/01/14/turkeybytes-arduino/
https://electronics-project-hub.com/arduino-7-segment-display-clock-with-and-
without-rtc/.
Ian Buckley, How to Make a Custom Game Controller With Arduino and Unity,
Makeuseof (2016).
James Bruce, How To Make a Pulsating Arduino LED Cube That Looks Like It
Came From The Future, Makeuseof (2012).
Joe Coburn, Arduino Programming for Beginners: Traffic Light Controller Project
Tutorial, Makeuseof (2019).
Vividz, Make Your Own Smoke Detector Circuit Using Arduino, Autodesk Inc
(2017).
ARDUINO
Arduino boards and Arduino IDE are open-source, meaning they are licenced in
a way that anyone can use their designs and manufacture the boards which had
led to competition and hence the low cost. It also ensures faster development of
the boards and the IDE.
What is Arduino?
Arduino platform consists of various Arduino boards and the Arduino IDE
(Integrated Development Environment), which consists of code editor to write
the programs, a compiler to compile programs, and it is also used to program the
Arduino boards.
Arduino ecosystem has grown many folds over the years and currently has many
boards for all types of applications. Arduino boards are small microcontroller
boards with other peripherals that have a number of connection sockets (GPIO),
which can be used to connect different sensors and actuators to the board. The
microcontroller is essentially the brain of the board, and it can be programmed to
make any control system. The board also has a Universal Serial Bus plug (USB)
to connect it to the computer. The board can be powered through this plug by
computer or can be powered externally by a 9 volts battery. This port is also
used to program the microcontroller on the board through the computer. The
sensors and inputs, like the buttons, are essentially the things that help the
microcontroller sense the environment; based on these inputs, the
microcontroller take actions as per the program and changes its output.
Chapter 1
Basic Programming Concepts Needed To Get
Started With Arduino
In this chapter, we will introduce the basic programming concepts needed to get
started with Arduino, as well as other types of similar embedded systems. To
learn what you can build with these systems, see chapter 2. Since you want to
learn about Arduino and embedded systems, explore all the chapters one after
another of this book.
Here we will explain programming concepts from the start, and you don't need to
know anything about Arduino or computer programming to get started. If you
already have previous programming experience, this chapter may add some extra
to your knowledge.
Overview
The purpose of this chapter is to quickly and easily present the basics of
programming so you can start using Arduino in your projects without having to
read many programming books or articles. The subject of "software
development" as a whole is very broad, so let's focus only on the concepts that
are important for Arduino and embedded systems in general.
There are many other things to learn about software that we won't cover here. In
the next chapters, we have added information for you to follow to learn more
advanced concepts or software concepts that are not widely used in embedded
system programming.
Let's start by explaining how a computer works (remember that Arduino is, at
the bottom, a computer).
Computer
A computer is simply a machine that processes instructions. These instructions
are processed in the "brain" of the computer, which is called a microprocessor.
Every computer has at least one microprocessor. Arduino, for example, is
nothing but a very small computer, and it uses an ATmega microprocessor.
Some microprocessors, such as ATmega, are also called microcontrollers.
Computer Program
A computer program, or software, is a sequence of instructions that are sent to
the computer. Each type of microprocessor (brain) understands a different
instruction set, i.e. its own "language." We also call this language machine
language.
Machine languages are, at the bottom, the only languages that computers can
understand, except that they are very difficult for humans to understand. That's
why we use something called the programming language.
For systems like Arduino (so-called embedded systems), software that runs on
the microprocessor is also called firmware.
Programming Language
We human beings need to convert our ideas into a form that computers can
process, that is, machine language. Today's computers can't (yet) understand the
natural language we use every day, so we need another special "language" to
instruct the computer to do the tasks we want. This "language" is a programming
language, and there are actually many of them.
int led;
In this case, we are declaring a variable of the type installed led. Next, we will
talk more about the data type of a variable.
Data Type
The data type of a variable means, as its name implies, the type of information
that can be stored in that variable. In many programming languages, such as C
++, it is mandatory to define the data type at the time of variable declaration, as
we saw in the variable declaration above. For Arduino modules that use ATmega
processor, the most common types of data we use are:
boolean: true ( true) or false ( false) value
char: a character
byte: one byte, or 8-bit string
int: 16-bit signed integer (-32768 through 32767)
unsigned int: 16-bit unsigned integer (0 to 65535)
long: 16-bit signed integer (-2147483648 through 2147483647)
unsigned long: 16-bit unsigned integer (0 to 4294967295)
float: real precision single number (floating point)
double: double precision real number (floating point)
string: string
void: empty type (no type)
For all data types supported by Arduino, see the "Data Types" section on this
chapter.
Assignment
Assigning a value to a variable means storing the value in it for later use. The
assignment command in C ++ is the =. To assign the value 13 to the variable led
we created above, we do this:
led = 13;
The purpose of this line of code is to say that Arduino pin 13 will be used to
light the LED, and store this information for later use throughout the program.
Fixed values used in the program, such as the value 13above, are called
constants because, unlike variables, their value does not change.
Operator
An operator is a set of one or more characters that serve to operate on one or
more variables or constants. A very simple example of an operator is the
addition operator, the +. Let's say we want to add two numbers and assign them
to a variable x. For this, we do the following:
x = 2 + 3;
After executing the above command, the variable x will contain the value 5.
Each programming language has a different set of operators. Some of the most
common operators in the C ++ language are:
Arithmetic Operators:
+: addition ("more")
-: subtraction ("minus")
*: multiplication ("times")
/: division ("divided by")
Logical Operators:
&&: conjunction ("e")
||: disjunction ("or")
==: equality ("equal to")
!=: inequality ("different from")
!: denial ("no")
>: "bigger then"
<: "less than"
>=: "greater than or equal to"
<=: "less than or equal to"
Assignment Operators:
=: assigns a value to a variable, as we saw above.
As you develop your projects, you will gradually become familiar with all of
these operators. For a complete list, see this Wikipedia page.
Function
A function is roughly a sequence of commands that can be reused multiple times
throughout a program. To create a function and say what it does, we need to
make a function declaration. See how a function is declared in our sample
program:
void setup () {
pinMode (led, OUTPUT );
}
Here we are declaring a function with the name setup(). What it does is execute
the commands of another function pinMode(). The action of executing
previously declared function commands is called a function call. We do not need
to declare the function pinMode()because it is already declared automatically in
the case of Arduino.
Function Call
Calling a function means executing the commands that were defined in your
declaration. Once declared, a function can be called multiple times in the same
program so that its commands can be executed again. To call our function
setup(), for example, we would use the following command:
setup ();
For example, let's create a function that returns something, for example, an
integer. To return a value, we use the command return:
int f () {
return 1;
}
When called, the f()above function always returns the value 1. You can use the
return value of a function to assign it to a variable. For example:
x = f ();
After declaring the function f()and calling the assignment command above, the
variable x will contain the value 1.
Parameters
Another important feature of a function is the parameters. They serve to send
some data to the function when it is called. Let's create, for example, a function
that adds two numbers:
Here we just define a function called soma(), which accepts two integers as
parameters. We need to name these parameters, in which case we choose a and
b. These parameters act as variables that you can use within the function.
Whenever we call the function sum(), we need to provide these two numbers.
The command returns a + b; simply returns the function with the sum of the two
numbers. Let's add 2 + 3 and assign the result to a variable x:
After the above call, the variable x will contains the value 5.
Comments
A comment is a piece of text in your program that only serves to explain
(document) the code without executing any kind of command in the program.
Often, comments are also used to disable commands in code. In this case, we say
that the code has been commented.
Line comment: starts with the characters //, making all the rest of the
current line a comment.
/ *
Programming for Arduino - Getting Started
Sample Program: Blink
* /
/ *
* /
int led = 13;
/ *
function After the setup () function is called, the loop () function is called
repeatedly until
* /
void loop () {
// All following lines are called parameter passing
function // Functions are executed in sequence to make the LED light up and
off
digitalWrite (led, HIGH ); // Assigns high logic level to LED pin, lighting it
delay (1000); // Wait 1000 milliseconds (one second)
digitalWrite (led, LOW ); // Assign low logic level to LED pin, deleting
delay(1000); // Wait 1000 milliseconds (one second)
The following are some of the most common control structures used in general
programming languages. We will also modify our test program to exemplify
better how these structures work.
While
The while loop is a structure that performs a set of commands over and over
again as a certain condition is true. While in English means "while," and
pronounced "wow-ou." It follows the following format:
while(condition) {
...
}
So let's make a modification to our program to better illustrate how while works.
Our goal now is to make the LED flash three times, then wait five seconds, flash
three more times, and so on. We will change the content of the function loop()to
the following:
First, we declare a variable i. This variable will count how many times the LED
has flashed since the beginning of the program or since the last pause of five
seconds. We will initialize this variable to zero because at the beginning of the
function loop(), the LED has not flashed once under these conditions.
Between the characters {and }, we put the code that makes the LED blink, as
before, but we must not forget to add 1to the variable that counts the number of
"blinks." This is done in the following line of code:
Note that after executing all commands between {and }, we will always have in
the variable i the number of times the LED has flashed since the start of the
function loop(). Let's go through the sequence of steps executed each time the
function loop()is called:
II. We add 1to the variable i, making it 1: we know that the LED
flashed once.
After these steps, we reach the end of the function loop(), and as we already
know, it is called again by the Arduino system. This restarts the cycle by
performing the above steps indefinitely.
Run the modified program with the instructions above on your Arduino and try
to vary the number of "blinks" and the number
For
Now that we have learned the while command, it is very easy to learn the for
command, as it is almost the same thing. Let's modify the content of the function
loop()as we did above, but using the for instead of while:
The first modification we made was to declare the variable i without initializing
it with the value 0. We can do that because the command will do it for us. It
follows the following format:
We can then verify that for nothing is more than a while plus a boot command,
and a terminate command. For our test program, these commands are
respectively:
i = 0: Initializes the count of the number of "blinks."
If we run the above program on Arduino, we will see that the result is the same
as we got with the program we did earlier using a while.
If
The if is one of the basic structures in general programming. If stands for "if" in
English, and that is exactly what it does: it checks an expression and, only if it is
true, executes a set of commands. In natural language, he executes a logic like, "
If this is true, then do that."
To illustrate, let's modify our sample program so that it does the same thing we
did with while and for above, but let's do it using one if, which follows the
following format:
if(condition) {
...
}
The logic is very simple: whenever the condition is true, the commands enter
{and } are executed, otherwise the program proceeds without executing them.
Let's see how the function looks like loop():
Here the logic is a bit different: we will keep the function loop()flashing the
LED as in the original program, but we will insert an additional 5 seconds wait
after every 3 flashes. For this, we create a variable i outside the function loop();
it must be declared from outside the function in order to retain its value between
each execution of the function loop(). We call this the global variable. When
the variable is declared within the function body, it does not retain the value
between each execution and is restarted each time the function is re-executed.
We call this the local variable.
We will then use this global variable i to count, again, the number of times the
LED went on and off. In the variable declaration, we initialize it with the value
0to indicate that the LED has not lit up yet. The function loop()then starts
executing by turning the LED on and off. To count the number of times the LED
flashed, we added the following line of code:
i ++; // Increase number of "blinks"
We then use the if to check if we have just lit the LED for the third time. For
this, we use the expression i == 3in the condition of ìf. If this expression is true,
that is to say, that the LED has already lit 3 times, then we insert an additional 5
second pause with the call delay(5000) and restart the number of "blinks" again
with the following command:
i = 0; // Reset the number of "blinks" counter
From then on, the function loop()continues to be called, and the cycle starts
again.
If-else
The if-else, also known as if-then-else it can be seen as an extension command
if. Else in English means "otherwise,"and he does exactly what the name says:"
If that's true, then do that, otherwise do something else." It follows the following
format:
if(condition) {
...
} else {
...
}
To illustrate, let's use the program is that we show up, but this time we will make
the LED on and off four times before giving a five-second pause. Then we will
make the third of each of these four "flashes" light up for a shorter period.
Within the function loop(), we will have the following:
// Variable to count the number of times the LED flashed
int i;
Here what we do is, every time we turn on the LED, check if this is the third
time this happens, by command if with the condition i == 2. If this expression is
true, it means that we have already lit the LED twice and are about to light it for
the third time; In this case we change the time that the LED is random to a
smaller value of 0.2 seconds (a reduction of 0.8 seconds) and the time it turns off
to a larger value of 1.8 seconds (increase of 0 seconds). , 8 seconds).
But what if this is not the third time the LED has been on? This is where o else:
If the condition of if is true, the command block between {and }after if is
executed, otherwise the block between {and }after else is executed. This means
that for the first, second, and fourth "blinks," the default time of one second will
be used.
Libraries
The things we learned in the previous sections are important for implementing
the logic of your Arduino program, but you will usually want to do more than
just light a LED. When you do more complex tasks or use some other circuit
connected to your Arduino, a very important feature is libraries.
A library is basically made up of additional source code that you add to your
project through the include command. Let's see how to add, for example, a
library for controlling a liquid crystal display (LCD):
An Arduino library usually presents itself as one or more classes that have
functions, methods, to trigger devices, configure them, or perform some other
task. Continuing with the example of the LCD display, to use it in your program,
you must first initialize it. What we do in this case is create an object to access
the LCD (technically, this is called instantiating an object). Let's see how this is
done:
When we do this, lcd it becomes an object of the class LiquidCrystal. This is the
equivalent of creating a variable of type LiquidCrystal. The parameters that are
passed in parentheses serve to initialize the configuration of this object, in which
case they correspond to the pin numbers that were used to connect the LCD to
the Arduino.
Arduino libraries almost always have a method begin(), which serves to make
the initial configuration of the device being controlled. To call the function
begin()of the object lcd we created, we do the following:
lCD begin (16, 2);
This method begin()is usually called from within the function setup(), i.e. during
program startup. The method parameters in begin()this case correspond to the
number of columns and the number of rows of the LCD, respectively.
After these steps, we can now write a text on the LCD. We do this using the
print()object method lcdwhenever we need it throughout the program:
The method print()is just one of several methods available in the library
LiquidCrystal. To know all the methods provided by a particular library, you
need to refer to the documentation provided with it.
This is the basic process of using libraries in Arduino. For more information,
read the documentation provided with the library you are using.
Conclusion
In this chapter we look at the basic programming concepts required to program
an Arduino or even other embedded hardware platforms. But this is only the
beginning, and there is still much to learn, both in hardware and software.
Through the next chapter of this book, there are interesting sections and lessons
so you can learn more advanced concepts and expand your possibilities.
Chapter 2
Getting Started with Arduino
If you work with electronics, you probably know or have heard about Arduino
before you start reading this book. If you are from some other area, say art and
design, you have probably heard about this open-source development platform
as well. The Arduino is a project that has become popular throughout the world
because of its practicality, ease of work and competitive price.
In this chapter, we'll introduce what your hardware and software aspects are,
how they came about, as well as a step-by-step lesson to set up an initial desktop
and implement your first project with Arduino.
By the end of this chapter, you are expected to be able to explain and understand
what the Arduino system consists of and also be able to start developing your
first applications. Move on!
The project emerged in Italy in 2015 from a group of developers led by Massimo
Banzi. The initial purpose was to create a low-cost, easy-to-work platform that
could be used by students to develop their prototypes efficiently and cheaply. It
was also thought to assist in the teaching of electronics to art and design
students, particularly to create interactive environments, something very much in
vogue within contemporary design and arts.
The main reasons for using the Arduino platform in your projects are as follows:
Low-cost prototyping
Easy to program
Arduino is not the only electronic prototyping platform on the market. There are
other projects and development kits, the most common being Raspberry Pi and
BeagleBone. Each uses a different microcontroller and has hardware design with
its own characteristics. Prices also vary widely, and some other platforms are not
as popular.
The choice of which prototyping kit to use depends on the demands and needs
your project imposes. Certainly, given the reasons cited above, Arduino is a
strong candidate for most of its projects.
An Overview of Arduino
Arduino is a prototyping platform that enables the development of various
robotic projects, acting as a type of simplified programmable electronic brain,
with several ports for connections to modules and sensors.
Arduino was so successful after its inception that within a few years, it became
known in schools and universities around the world, becoming a low-cost,
extremely functional global fever.
From the beginning of the project development, the founders' main objective was
to create a cheap electronic device with great functionality, and at the same time,
that could be easily programmed.
This explains the great success that the Arduino has achieved, appearing in low,
medium, and high complexity robotic designs, allowing the integration with
electronic modules and sensors of the most diverse types.
Some scholars in the area say that the microcontroller was named after Arduino
after King Arduin, who ruled northern Italy in the year 1002 and was a striking
figure. Massimo still had a bar in the town of Ivre called Bar di Re Arduino,
already inspired by the king.
How does Arduino Work?
Arduino works from programming codes, where it can be freely used for various
types of functions and can control everything from electronic sensors to highly
complex modules.
The programming is done through the IDE program Arduino, which can be
downloaded directly from the official website arduino.cc, in addition, the
connection to the computer is made via USB cable, allowing the commands
defined in the program to be correctly transferred to board.
After recording the codes according to the chosen sensors, it can be installed at
random locations using power supplies or even batteries if it needs to be in an
isolated location.
Both hardware and software are designed to assist designers, hobbyists, hackers,
artists, novices, and anyone interested in creating interactive equipment and
environments. Arduino can interact with sensors, motors, cameras, shields, and
most known electronics.
The Arduino Uno is the best-known model, with 13 digital ports, 6 analog ports,
3 GND ports, a 5V port, and a 3.3V port, as well as other configuration and
power pins.
Among the Arduino digital pins, it is worth remembering that there are some
pins that differ from the others because they have their own characteristics such
as PWM pins that have a "~" before the number and have the ability to vary the
output signal to control motors, for example, pins 0 (RX) and 1 (TX) which are
communication pins.
As for power, it can be done through the USB port, with the possibility of the
programmer choosing to use an external source with a direct connection to the
Arduino p4 jack.
How to Program an Arduino
Arduino programming is done via software on the computer or directly on an
android phone; in any case, the program needs to be downloaded from the
manufacturer's website and installed directly on the machine.
After that, you need to connect the card with the USB cable, which is usually
included, and select the desired card, and then you have to upload a ready-made
code or create one from scratch in C language.
This is not to say that you will need an expensive microcontroller to have the
special functions because, with a simple one like UNO, you will be able to
install any extra modules that can even pass the functionality of the complete
model, everything will depend on the type of project that you want to develop.
For those just starting out and still wondering what the best Arduino to start
with, keep in mind that the Arduino UNO is currently the “standard” card on the
market and probably the best choice for those starting with this line of
controllers.
Have you ever come across a rising light with your simple presence, clapping, or
varying ambient light? Maybe you have seen carts that follow a line, dodging
obstacles, receiving commands through mobile phones, these are two of the
main electronic movements involving Arduino, Home Automation and Robotics.
There is not just one Arduino model. There are several cards available, each with
different levels of complexity and different functionality. There are 6 classes of
Arduino prototyping platforms available on the market today. Are they:
Let's focus on Arduino UNO, an entry-level card, and one of the most popular
and most affordable models. It is an ideal card for those who are taking their first
steps in electronics and the Arduino universe.
As seen in figure 1, the board has a number of available connector pins and
connectors for interfacing with the outside world. The MCU is an ATmega328p
(datasheet). The main features of the board are:
14 digital I / Os, of which 6 can be used as PWM
6 Analog Inputs
16MHz Oscillator
USB connector
Power connector
ICSP header
Reset button
The card can be powered by both USB cable and AC / DC adapter. All features
of the microcontroller are available to interface with the outside world. In
general, analog inputs are used to read external sensors, and PWM outputs and
digital outputs are used to control motors and actuators and drive drivers for
external loads.
The Software of Arduino
The Arduino IDE is also open source. Its graphical environment was developed
in Java and based on Processing and other open-source languages. The
programming environment is available for Windows, MAC and Linux. The
download can be done directly on the official page.
This high degree of abstraction and library set are largely responsible for making
programming more intuitive and fast, as the developer does not need to know the
registers, memory details, and dynamics processor.
Arduino UNO IDE.
Just below this main menu are some shortcut icons. They are (from left to right):
Shortcut toolbar.
Verify: Identify syntax errors in code
Upload: Loads software on board
New: Creates a New Blank Sketch Tab
Open: Opened a Sketchbook Sketch
Save: Save Sketch in Development
In the next couple of chapter, you will learn more about Arduino programming
and C / C ++ languages.
Getting Ready to Program Arduino
Now that we know what Arduino's hardware and software features are let's
prepare and configure our development setup.
From a hardware standpoint, simply power the card and connect the USB cable
to the computer. The IDE does all other settings. See the steps below:
Open Tools tab, select Board option and then select Arduino
Uno
Open the Tools tab, select the Serial Port option and then select
the COMX port, where X is the number the PC has associated
with the serial port assigned to Arduino.
After these settings, the IDE is ready to load programs developed in Arduino and
run any available example.
Programming the First Application
Let's now make the first example in Arduino. The simplest example, usually the
first made to test a board or when learning for the first time, is the famous "Led
Blink," that is, let's write a program to make a led flash.
The Arduino UNO platform has an onboard led previously connected to the
logic state of pin 13. So we can use this led to our example.
Another good news is that IDE has a good and complete library of examples that
can be used as a basis for a wide range of applications. To access the Led Blink
example, go to Files → Examples → Basics → Blink.
In the following figure, we see the code of this example:
In the example above, we can see the two parts that will always be present in all
your Arduino projects. The void Setup() function and the void loop () function.
The first is responsible for configuring and making all the necessary settings for
a given application. For example, in the case of Led Blink, we see the line:
pinMode (Led, OUTPUT).
This line of code is responsible for initializing the digital ports as outputs. Other
settings, such as PWM signal frequency, port initialization as input, serial
channel settings, among others, are all made in this function.
The second routine consists of the infinite loop that will be repeated throughout
the application. That is, after Arduino is energized, the first piece of software
that will run is the void setup () function, and soon after, the software enters the
void loop () routine, and repeats the code within that routine continuously. It is
in this infinite loop that the code for the application itself must be placed.
In the case of Led Blink, we have the following code in the infinite loop:
After waiting for this time, the digitalWrite () function is called again, but this
time to assign a low logic level to pin 13, i.e. to turn off the led connected to pin
13. Finally, the delay function (1000) is again call to pause another second.
This way, the led flashes at continuous intervals of one second. Here's our
example Led Blink! Simple, isn't it ?!
To upload the code on the board, just click the Upload icon. The firmware will
be written to the board's Atmel microcontroller, and the first flashing application
will be ready. Each time the Arduino is energized, the pin 13 led will flash at
regular one-second intervals.
If you have come this far, then you already know what the Arduino platform is
and how it works. The Led Blink example is a very basic application, and we
recommend that you explore the other examples available in the IDE and follow
the blog posts here. There is a great documentary that we highly recommend
about Arduino history and how it all started ( see here! ).
The simplicity of the Arduino IDE has made it one of the most popular in the
world - it's easy enough for beginners and fast for advanced users. Millions of
people have used it as their daily tool for programming projects and applications.
However, we have listened to your comments, and the time has come for a new,
enhanced version with features that will appeal to the most advanced developers
among you - continuing with the simple, classic Arduino IDE that many of you
are familiar with.
Key features of this initial alpha release of the new Arduino Pro IDE are:
Modern and complete development environment
Dual Mode, Classic Mode (identical to Arduino's classic IDE) and
Pro Mode (File System view)
Ninth Board Manager
New Library Manager
Board List
Basic Autofill
Git integration
Serial monitor
Dark mode
But the new architecture opens the door to the features requested by the Arduino
community that will follow shortly:
Sketch Sync with Arduino Create Editor
Debugger
Fully open to third party plugins
Support for additional non-C ++ languages
For those who love and appreciate Arduino's classic IDE, don't worry, it will
remain available forever.
Chapter 3
C Language Basics
General Considerations
Many languages have been developed and for many years used for different
purposes and characteristics, such as Fortran, Cobol, Basic, Algol, Pascal, and so
on. But what is C? C is the name of a language currently used in different areas
and purposes. It is now part of an advanced language developed at Bell Labs in
the 1970s.
It is a medium level language, as it can work at a level close to the machine level
or as a high-level language like existing ones.
The need to write programs that make use of machine language resources in a
simpler and more portable way meant that the main use of C was the rewriting of
UNIX operating systems. Its indication is mainly in the development of
programs such as compilers, interpreters, text editors, databases. Computer
graphics, image manipulation, and processing, process control…
Basic Elements
Identifiers
They are used to name constants, variables, functions, and various user-defined
objects. The rules for forming these names are:
2. May not contain special symbols. After the first character can be
used: letters, underscores and / or digits.
Comments:
2. The word int can be omitted. Ex: unsigned long int Û unsigned
long
Declaration of Variables
The general form for declaring a variable is:
variable_type variable_list;
Examples:
Constants
In C, constants are fixed values that cannot be changed by a program.
Code Meaning
\The audible signal
\B cursor backspace
\ f form feed
\ n new line
\ r car return
\ t horizontal tab
\ ' quotation marks
\ ' apostrophe
\ 0 null (zero)
\\ backslash
\ v vertical tab
\The beep
\ N octal constant (where N is octal)
\ xN hexadecimal constant (where N is hexadecimal)
Instructions
A C language statement is an expression followed by a semicolon. It can be an
assignment, a function call, a deviation test, or a loop test.
Where the equal sign (=) is the assignment operator. Note that the left operand of
the assignment operator is always a variable and that the right operand must be
of a data type compatible with the type of the variable.
Operators
Arithmetic Operators
Addition +
Subtraction -
Division /
Multiplication *
Rest %
Comments:
1. All operators are defined for integer and noninteger types except
the remainder (%) operator, which is not defined for variables of
noninteger types.
2. For any integer type, adding one to the largest track number of that
type produces the smallest track number. Overflow errors are not
always detected, so the programmer must be careful when sizing
program variables so that they do not occur.
Example:
unsigned char x;
x = 255;
Relational Operators
Logical Operators
Truth table:
p && p
P Q !P
q || what
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
Combined Assignment Operators
+ = - = * = / =
Examples:
a + = b; / * a = a + b; * /
a - = b; / * a = a - b; * /
a * = b; / * a = a * b; * /
a / = b; / * a = a / b; * /
Comments:
int a, b, c;
a = 6;
Address Operators
& - return variable address
* - return the contents of the address stored in a pointer variable
To learn more about address operators, see Pointers.
Other Operators
sizeof ( operand ) - provides the size in bytes of your operand
Ex:
int x;
float y;
char c;
x = sizeof (int); / * gives the size of type int (2 bytes) * /
x = sizeof (y); / * gives the size of variable y (4 bytes) * /
x = sizeof (c); / * gives the size of variable c (1 byte) * /
Expressions
Operators, constants, variables, and functions are expressions. The main
algebraic rules are considered in the expressions. Some aspects of expressions
are C language-specific and are explained below.
1. All operands of type char and short int are converted to int. All float
operands are converted to double.
Example:
float x, res;
char c;
...
res = x / c; / * the value of x / c is converted to a float, although c is
originally a char * /
Type cast operations are very useful in expressions where some operation results
in loss of precision due to the type of variables or constants involved. For
example:
float res;
int op1, op2;
op1 = 3;
op2 = 2;
res = op1 / op2; / * res gets 1 since op1 and op2 are both
int numbers and the result of their
division is also int * /
res = (float) op1 / op2; / * res gets 1.5 as type cast
forced the op1 operand to be a float
In this operation. The result of the division,
therefore it is also float * /
Example:
a = b / 9.67-56.89 * x-34.7;
a = (b / 9.67) - (56.89 * x) - 34.7; / * equivalent * /
Structure of a C program
An interesting feature of program C is its modular and functional aspect, where
the main program itself is a function. This form of language presentation
facilitates the development of programs, as it allows the use of structured and
modular forms found in other languages.
The structure of a C program has the following elements, and those enclosed in
brackets are optional:
[ preprocessing settings ]
[ type definitions ]
[ global variable declarations ]
[ function prototypes ]
[ functions ]
main ()
{
/ * variable definitions * /
/ * main function body, with declarations of its variables,
its commands and functions * /
}
Example:
Main () is the main function of a C program, containing the code that will
initially be executed when the program itself is executed. Every C program must
contain the main () function, otherwise, an error will be generated during the
program generation process (more specifically, in the binding step).
Basic I / O Functions
This section describes some of the basic I / O functions that will initially be used
to provide the programmer with a keyboard data input channel and a monitor
data output channel.
where data string and format are literal data to be displayed on the monitor (for
example, any text) plus an optional set of format specifiers (indicated by the%
symbol and a character set). These specifiers will determine how the contents of
the var1 through varN arguments are displayed.
1)
int n = 15;
printf (“The value of n is h% d”, n);
/ * displays ´The value of n eh 15´. Note that all contents of the data string
and format are displayed literally, except for the% d specifier, which is
replaced by the integer value of variable n * /
2)
where the format string contains the format specifiers in sequence and relative to
each of the data to be received. For a list of commonly used format specifiers,
see printf () Function (stdio.h Library) section.
var1 through varN identify the variables in which the values received
by scanf will be stored in the same order as determined by the format
specifiers. The number N must be equal to the number of format specifiers
provided.
Examples:
1)
int t;
printf (“Enter an integer:“);
scanf (“% d,” & t); / * waits for a type number to be entered
int. The number entered is stored in the
variable t when the user types ENTER * /
2)
char char1;
int i;
printf (“Enter a comma-separated character and int:“);
scanf (“% c,% d”, & charac1, & i);
/ * In this case, the format specifiers% c and% d are
comma-separated, meaning that the user must enter the values also
comma-separated and in the correct order * /
Because it stops execution until a key is pressed, the getch function can be used
at the end of a console program to allow the user to view the output of the
program before its window closes.
Example:
Note: The getche function works similarly, but displays the typed character on
the screen (the name means “get char with echo”).
Control Structures
Simple Command
A command line in C always ends with a semicolon (;)
Examples:
x = 443.7;
a = b + c;
printf (“Example”);
Command Block
Braces ({}) are used to delimit command blocks in a C program. They are most
commonly used in grouping statements for execution by conditional and
repeating structure clauses.
Conditional Structures
if-else Structure
Format:
if (condition)
{
command block 1
}
else
{
command block 2
}
Examples:
1)
int num;
printf (“Enter a number:“);
scanf (“% d”, & num);
if (num <0) / * tests if num is less than zero * /
{
/ * command block executed if condition is true. In this case, as printf is a
single command the keys could be omitted * /
printf (“\ nThe number is less than zero”);
}
else
{
/ * command block executed if condition is false.
In this case, as printf is a single command the keys
could be omitted * /
printf (“\ nThe number is greater than zero”);
}
2)
3)
if (m == 3)
{
if ((a> = 1) && (a <= 31)) / * this if is part of the previous if
command block * /
{
printf (“Date OK”);
}
else / * this else is from the nearest if (which does
part of the command block) * /
{
printf (“Invalid Date”);
}
}
Switch Structure
Format:
switch (expression)
{
case value1:
seq. of commands 1
break;
case value2:
seq. of commands 2
break;
. . .
case valueN:
seq. N commands
break;
default:
seq. standard
}
The default clause is executed if no match is found. This clause is optional and,
if not present, no action will be taken if all matches fail. It is typically used to
direct any free end that may be pending in the switch statement.
COMMENTS:
2. never two case constants on the same switch can have equal values.
Examples:
1)
int dia;
printf (“Enter a day of the week from 1 to 7”);
scanf (“% d”, & dia);
switch (day) / * tests the value of the variable day * /
{
case 1:
printf (“Sunday”);
break;
case 2:
printf (“Monday”);
break;
case 3:
printf (“Tuesday”);
break;
case 4:
printf (“Wednesday”);
break;
case 5:
printf (“Thursday”);
break;
case 6:
printf (“Friday”);
break;
case 7:
printf (“Saturday”);
break;
default:
printf (“This day does not exist”); / * only enters here if the user does not
enter a day between 1 and 7 * /
break;
}
Repetition Structures
While Structure
Format:
while (condition)
{
command sequence
}
The while command evaluates the logical condition value; if the logical value is
true ( true ), the command sequence is executed, otherwise, the program
execution continues after the structure while. If the command sequence consists
of a single command, the use of keys is optional.
After the command sequence has been executed, the logical condition value is
reevaluated, and if it remains true, the command sequence is executed
again. This behavior is repeated until the truth value of the condition is false
( false ) when the execution of the structure while it is stopped and continued on
the next instruction.
Each of the command sequence runs is called a loop iteration. In the case of
the while structure, the number of iterations can range from 0 to N, where N is
the number of the iteration, after which the condition test results in a false
logical value.
NOTE: If the condition is true on the first test and the command sequence is
executed, it must make the condition false at some point; otherwise, the
condition will always be reevaluated as true, and the command sequence will be
executed in an infinite number of iterations.
Example:
int x = 0;
/ * prints x values from 0 to 9
the value 10 is not printed because when testing the condition for
x equals 10, the logical value is false and the while execution
is interrupted * /
while (x <10)
{
printf (“\ nx =% d”, x);
x ++; / * makes the condition false
at any moment */
}
do-while Structure
Format:
of {
command sequence
} while (condition);
NOTE: As with the while structure, if the condition is true on the first test, the
command sequence must make the condition false at some point.
Example:
int num;
of {
printf (“Enter a number from 1 to 9:“)
scanf (“% d”, & num);
} while (! ((num> = 1) && (num <= 9))); / * in this case, obtaining
of the value of one way
scanf may make the condition false * /
for Structure
Format:
for (initialization; condition; increment)
{
command sequence
}
After initialization, the logical value of the condition is tested. If true, the
command sequence is executed, otherwise, execution continues after the for
structure. At the end of the command sequence execution, the command
corresponding to the increment is executed, and the condition is retested.
The cycle is repeated until the test condition results in a logical false value (
false ) when then execution continues after the structure is. If the command
sequence consists of a single command, the use of keys is optional.
The for the structure is equivalent to a while structure of the following format:
boot
while (condition)
{
command sequence
increment
}
COMMENTS:
Examples:
1)
3)
4)
/ * two variables are initialized, tested and incremented * /
for (x = 0, y = 0; x + y <100; x ++, y ++)
printf (“% d”, x + y);
Interrupt Commands
Break Command
The break command can be used to interrupt the execution of a loop at any
time. Only the innermost loop is broken, and execution continues on the
command following that loop.
Example:
Continue Command
The continue command works similar to break, except that only the current
iteration is interrupted; that is, loop execution continues from the beginning of
the next iteration
Example:
Modularization in C
Functions
Return Type specifies the type of value that will be returned to the caller of the
function. When the return type is void, this means that it is a function that
behaves like a subroutine; that is, the function does not need to return any value,
just to be called.
The return command is used to perform the function return; This can be used at
any point in the function that you want to finish executing and return the value
(if the function returns any value) to the caller.
Return Value is the value to be effectively returned and can be either a variable
or a constant; In cases where the function returns no value, the return command
must be used alone, or you can simply omit it, which will automatically return
the function to its end.
Parameters param1 through paramN identify the parameters that you want to
pass to the function. Each of these parameters becomes a local variable of
the type1 to typeN function and is initialized to the value that was passed to you
at the time of the function call. Functions that take no value as a parameter must
be declared with the word void in parentheses.
/ * two parameters, one int and one char. The ... refers to any return type *
/
... Func1 (int var, char var2)
{
}
... Func2 (void) / * receives no parameter * /
{
}
Example of C function and program that calls it:
int func1 (char charac, integer int, floating float) / * function declaration * /
{
/ * one can declare other variables in here, as in a normal program snippet
these variables are local to the function * /
int other;
/ * use of received variables as parameter * /
printf (“% c”, charac); printf (“% f”, floating);
scanf (“% d”, & other);
printf (“% d”, integer + other);
return another one; / * returns the value of the variable 'other' * /
} / * end of function * /
void main (void) / * main program * /
{
char c1;
float f;
int result;
int integer;
/ * this 'integer' variable exists within the scope of the 'main' function, so
it has nothing to do with the 'integer' variable that is created in the 'func1'
function when passing parameters * /
/ * reads an integer, a character and a float * /
scanf (“% d,% c,% f”, & integer, & c1, & f);
/ * call function 'func1' with parameters in correct order * /
result = func1 (c1, integer, f);
printf (“% d”, result); / * prints result of function * /
}
Comments:
2. The result of the function 'func1' in the example above need not
necessarily be assigned to a variable (in this case,
'result'); otherwise, the return value of the function will simply be
lost. However, as the function was made to return an integer value
this should be avoided because it constitutes a bad structuring and
use of the function;
3. All variables declared within the body of a function are local to it;
that is, they only exist while the function is being executed.
All functions must be “known” wherever they are used, i.e., your statement must
come before use. If you do not want to implement the function before where it
will be used, you can write a prototype as follows:
The prototype must be placed before the function call, signaling to the compiler
that that function exists and will be implemented later. In our example, if we
wanted to write function 'func1' after function 'main,' we should include a
prototype of 'func1' before it.
CAUTION!! The prototype is not exactly the same as the function header; it has
one more semicolon at the end!
Global Variables
In C is considered as a global variable, all those variables declared outside the
scope of any function (including the function 'main'). Any variable is known
only after its declaration, so it is usually declared all global variables at the
beginning of the program, before the implementation of the functions that use it.
int c;
char t;
/ * function that returns an integer value and receives no parameter * /
int func1 (void)
{
/ * there is a t variable that is global, but it works as a local variable * /
int t;
/ * c is global, so it can be used within function 'func1' * /
if (c! = 0)
{
c ++;
t = c * 2;
/ *, in this case, the value of t returned is that of the local variable since local
definitions override global definitions in the scopes where they exist * /
return t;
}
else return 0;
}
void main (void)
{
int return;
printf (“Enter a character:”);
scanf (“% c”, & t);
printf (“Enter an integer:”);
scanf (“% d”, & c); / * tec variables can be used here because they are
global * /
return = func1 (); / * call function func1 and return value in variable
'return' * /
printf (“\ nResult:% d”, return);
}
Parameter Passing by Value
In pass by value, a copy of the value of the argument is stored in the called
function parameter. Any change to this parameter is not reflected in the original
value of the argument.
The cstdarg library provides some data types and functions used to obtain the
parameters of a list:
va_list - type of variable parameter list, used to declare a structure (see chapter
“Data structures”) containing the received variable parameters.
void va_start (va_list list, last) - macro used to initialize the va_list parameter
list . Last is the identifier of the last parameter on the right that does not belong
to the variable list of parameters.
va_arg type (va_list list, type) - allows, from the list the type va_list, get the kind
of value type of the next argument list.
void va_end (va_list list) - finalizes the list parameters.
To declare a variable list function:
Return type function_identifier ( type1 param1, type2 param2, ... );
Where the ellipse ( ...) Denotes the beginning of the variable list of parameters.
An example: a function that takes n values and returns its average:
Vector Definition
Vector in C is a variable composed of a data set with the same name (identifier)
and individualized by an index.
Vector Declaration in C
Where type is the type of each of the vector elements and size is the number of
vector elements.
name [index];
IMPORTANT! The index of the first element of a vector is ALWAYS ZERO!
Thus, the index can range from 0 to size value - 1.
For example, for the declaration of a vector called test whose data type
is char, and that has 4 positions, it states:
char test;
The index of the last indexable element of the vector is 3 because, in C, the first
position used is position 0. In this case, the positions available in the vector are
as follows:
test [0]
test [1]
test [2]
test [3]
Passing Vector as Parameter to Function
In all cases the function receives a reference (address). Note that in the last way
a pointer is used, which will be explained later.
Because a reference is passed, changes made to the vector elements within the
function will be reflected in the original vector values (since its actual memory
position will be used).
For example:
{
int aux;
v [0] = v [1];
v [1] = aux;
}
void main (void)
{
int nums [2];
nums [0] = 3;
nums [1] = 5;
exchange (nums); / * The argument is the name of the vector * /
/ * prints '5, 3' as the nums vector values have been changed within the
'change' function * /
printf (“% d,% d”, nums [0], nums [1]);
}
Matrix Statement
Where dim1 and dim2 are the two dimensions of the matrix (in the case of a
two-dimensional matrix). To access an array element the syntax is:
Where ind1 and ind2 follow the same rules as the one-dimensional vector
indices (that is, they can assume values between 0 and dimension - 1),
where ind1 is the row index and ind2 the column index.
M [0]
0100
[0]
M [0]
0101
[1]
M [1]
0102
[0]
M [1]
0103
[1]
M [2]
0104
[0]
M [2]
0105
[1]
Passing Array as Parameter to Function
In the first case, dim2 must be provided so that the compiler can calculate the
offset in bytes from the address of the first element for a given position.
In the second case, m can only be used through pointer arithmetic (explained
below).
Example:
If the number of initialization values is less than the size of the vector, the
remaining positions will be filled with zeros. For example:
int test [5] = {1, 2, 3}; / * test [3] and test [4] get 0 * /
For arrays, each line is padded with braces, with values separated by
commas. All lines are enclosed in braces.
Example:
int m [5] [3] = {{1, 2, 3}}, {3, 2, 1}, {3, 3, 2}, {1, 2, 1} {3, 2, 0}} ;
Example:
int m2 [3] [4] = {{3,2,5}, {4,6,6}, {1,2,3,4}};
3 2 5th 0
4 6th 0 0
1 2 3 4
Pointers
Pointer in C is a variable that, instead of storing data of a certain type, stores the
address of a data of a certain type:
C Pointer Statement
type * name;
Where name is the pointer identifier and type is the data type to which it can
point.
Example:
int * d;
short int * ptr;
float * ptr2;
Pointer Operators
Operator &: Referencing operator. Returns the address of a variable. It can be
used to initialize a pointer.
Example:
int x, a;
int * ptr;
x = 30;
ptr = & x; / * ptr <- address of x * /
.
a = * ptr; / * a receives the contents of the given address * /
int * ptr;
int x;
x = 10;
* ptr = 3; / * ADDRESS CONTENT POINTED BY ptr gets 3 * /
ptr = & x; / * ptr gets the ADDRESS of x * /
int * ptr;
int x = 3;
* ptr = x; /* ERROR! Where does ptr point ??? * /
Pointers must point to data of the same type as your declaration, otherwise,
misinterpretation may occur in the dereferencing operation. For example, the
following code does not store the value 56 in variable f, since
the floatpointer will attempt to read the size of a given float from the memory
address of variable x and not the size of an int, which is the declared type. of
variable x.
int x = 56;
float * ptr;
float f;
ptr = & x; / * Pointer to float points to int * /
.
.
.
f = * ptr; /* ERROR! F value is not 56 * /
Pointer Arithmetic
Integer numeric values can be added or subtracted from a pointer. The result is
an address that follows the rules of pointer arithmetic, that is:
int x, y;
int * ptr;
ptr = & x; / * ptr receives address 120 * /
y = * (ptr + 4); / * y receives the contents of address 120 + 4 * (int size) ==
address 128 * /
Another example:
float * ptr;
ptr = (float *) 100; / * pointer is 'forced' to end. 100 * /
.
* (ptr + 3) = 15; / * Number 15 is stored at address 100 + 3x4 = 112 * /
Pointer-Vector Relationship
When a vector is declared, the vector identifier marks the start address of the
memory area allocated by it. Thus, the vector name can be used as an address
reference with the same operators as pointers. Therefore:
In many cases, it is interesting for a function to provide more than one output
value as its result. But the C language syntax allows only one direct return value
(via the return command ).
Using pointers creates an alternative for a function to provide more than one
output value, based on the fact that the concept of address in a program is scope
independent. That is, if a calling function provides the calling function with the
addresses of its variables, the called function can receive them in pointers and
fill in values at these addresses, which in turn will be available for direct access
by the calling function.
Example:
Strings
String Definition
Strings are miscellaneous strings. They are known as "literals" in structured
algorithm theory and are represented in quotation marks. Some examples of
strings:
“So-and-so,”
“? Question? “,
“1,234”,
"0".
String Statement
char phrase [6] = {'T', 'e', 's', 't', 'e', 0); / * initialized as a common character
array, 'forcing' the terminator character * /
In the case of the first and second example, the vector representation of
the phrase string is:
'P' 'r' 'i' 'm' 'and' 'i' 'r' 'The' '' 'f' 'r' 'The' 's' 'and' 0
Where each square represents one byte of memory (one char size ).
String Operations
To operate on strings, functions from the string.h library is used. This library has
a few dozen functions with various variations, and for simplicity, only some of
the main ones will be explained in this material. For details on other functions,
see library documentation (usually available in the development environment
help files).
strlen
Prototype:
Example:
char name [] = “So-and-so”;
printf (“Name has% d letters”, strlen (name));
strcpy
Prototype:
Description: Copies the contents of string2 to string1 and returns the string
address.
Example:
strcmp
Prototype:
0 if string1 = string2
Example:
gets
Prototype:
Example:
Comments:
1. the gets () function allows the user to provide more characters than can be
stored in the vector, which can cause an error. To avoid this problem, you can
use the fgets function:
In the example shown, fgets would take 9 characters (or until the user hit enter)
and store the data entered in the string name by adding the string terminator
character. It is important to note that if the user typed enter before 9 characters,
the newline character ('\ n') would also be stored in the vector.
2. gets () ends when the user enters a space, preventing typing sentences with
more than one word. To work around this issue, you can use scanf data pickup
options:
scanf (“% s,” str); / * Get a string until the first space is inserted * /
scanf (“% [\ n] s,” str) / * Receives a string until sent the ASCII character \ n,
which corresponds to enter * /
int * v;
int n;
printf (“How many elements in the vector?”);
scanf (“% d”, & n);
v = (int *) malloc (n * sizeof (int)); / * Allocate n times the size of an 'int' * /
if (v == 0)
{
printf (“Error”);
}
else
{
/ * here could come the code for vector manipulation
.
.
.
* /
free (v);
}
The free () function is called at the end of using dynamically allocated memory
space to free this space, allowing it to be used by other dynamic allocation
operations. The free prototype is as follows:
void free (void * ptr)
where ptr contains the starting address of the memory area to deallocate.
Chapter 4
Programming with Arduino
To develop your application and put your ideas into practice with Arduino, there
is no escape from programming. The writing of the software, but well called in
this case “firmware,” that is, a program that will be embedded in a
microcontroller is the most important step of the project execution.
Once you've done the architecture and designed the wiring layouts for all
hardware that will interface with Arduino, the next step is to get your hands dirty
and write the code that will run on your board. Let's remind you of the basics of
structured languages that are important and give you the conditions to develop
your first applications and walk with your own legs. Come on!
i. Open the Tools tab, select the Board option and then select
Arduino Uno (or any other model you are using)
i. Open the Tools tab, select the Serial Port option and then select
the COMX port, where X is the number the PC has associated
with the serial port assigned to Arduino.
After these three steps, the Arduino IDE is ready to use and to write the code on
your board.
The Arduino language uses a number of libraries and features so that the user
does not have to manipulate microcontroller bits and registers. From the user's
point of view, only function calls and logical procedure writing are used.
If you have already programmed any of these languages, Arduino will not be a
problem for you. If you have never programmed in C / C ++, or even any
language, there are no problems either! Arduino is very intuitive, and the whole
complex part is encapsulated in libraries and functions.
Compiling, in the context of programming, means checking all the syntax of the
code and, if everything is written within the rules of the language, creating the
so-called object code, which is another program, semantically identical to what
you wrote, but which is written in microcontroller language. The file generated
by the compilation process is exactly the file uploaded to Arduino at the time of
writing it.
To compile a program in the Arduino IDE, simply use the shortcut ctrl + R or
access the compile command in the Sketch -> Verify / Compile tab.
If so, just use the shortcut Ctrl + U, and the code will be uploaded to the board.
Or, access the upload command from the File -> Upload tab.
Components of a Code
Variables
A program variable is a predefined size memory space associated with the type
of the created variable. For example, if you need to do a simple arithmetic
account in your program, you could create a variable of type Integer named X.
So you could write the following line of code:
X = 2+ 3;
The memory space associated with variable X will be filled with the value 5.
Variables can have different types. In Arduino, variables can be of the following
types:
boolean: true or false
char: one character
Byte: 8-bit size
int: 16-bit signed integer
unsigned int: 16-bit unsigned integer
long: signed 16-bit integer
unsigned long: unsigned 16-bit integer
float: simple precision real number (floating point)
double: double precision real number (floating point)
string: string
void: empty type (no type)
In the example above, a whole variable name was created X, and a type float
variable name Y. Using the assignment signal, we store the value 5 in the X and
1.3 for Y.
For example, if you are writing a program and need to do a calculation of adding
some variables several times throughout the code. Instead of writing this
calculation multiple times throughout the code, you can create a function named
similar (x, y, z) and call that function each time you want to do the math.
Function Type: This is the type of value the function returns. In our
example, the result returned by the function is an integer, so the type
of the function will be Int. It is declared before the function name
(in red in the example). If the function returns nothing, the type
must be Void.
Function Name: This is the name you will use throughout the code
to call the function. It is blue in our example above.
All of this is done through the flow control structures. We will highlight the top
five of them by dividing them into two groups: Decision Making and Flow
Control.
Decision Making
If..else
The basic structure for decision making is if..else. As its name suggests, he
makes a decision based on a logical assessment. If the result of this evaluation is
true, the structure executes code subsequent to if, if the result is false, code
follows to else is executed .
The syntax is as follows:
If (logical expression)
…
Else
… ..
Example:
In the example above, variable X will be given 5, because the result of the
logical expression in parentheses in if is true. If it were false, the value of X
would be 2.
There are some variations, such as if… elseif… .else, and also some abbreviated
ways of writing the structure. However, if you understand the basic if..else, all
other variations will be natural to you.
switch ()
The switch is a decision-making structure that evaluates the value of a control
variable and directs the code to a specific case. Let's see what the syntax is like
to understand it better.
Using Arduino switch ().
In the structure shown above, the variable x controls decision making. If the
value of x equals 1, the code goes to line Case 1. If x equals 2, Case 1 is ignored,
and the code executed is as follows in Case 2. The number of cases is undefined,
but it is recommended to be no more than a dozen and no less than three.
In the event that there is no Case corresponding to the value of the control
variable, the code executed is Default, usually written at the end of the Switch.
The breaks in the middle of the switch say to the compiler to and out of the
switch, continuing the code that comes just below the closing of the keys that
define the switch. They are placed after each Case to prevent unnecessary
evaluations from being made.
Flux Control
Flow control structures are the famous loops used to iterate and perform tasks.
The two main ones are for and while.
For
The for syntax is as follows:
Using for with Arduino.
This structure means that the code entered between the keys following the for
will be executed x times. That is, if x equals 5, the loop will run 5 iterations. At
each iteration, the value of the control variable i is iterated as well. Thus, in the
first iteration, the value of i is zero, the second is one, the third is two, and so on
until i is equal to or greater than x.
While
While is also a widely used looping structure. The code snippet inserted
between the keys following the while is always executed as long as the logical
expression is true. The moment the logical expression of while is false, the loop
will not be executed anymore.
Example:
While with Arduino.
In the example above, the loop will be iterated fifteen times. Note that when
starting While the control variable is zero. And inside while there is a line: i + +.
The ++ operator causes the variable to be summed to 1 unit. That is, at each
iteration of while, the variable i is summed by 1 unit. Thus, in the first iteration, i
starts with zero but is summed by 1 unit and becomes one. In the second
iteration, i starts equal to one, is iterated and becomes two. And so on until i
equals fifteen. At this point, the while logical expression becomes false, and the
while body is no longer executed.
Libraries are collections of functions and parameter and variable definitions that
instead of being included in the main program, are saved in a separate file and
included in the main program through a line of code. Thus, all functions and
definitions within these libraries are available in your code. Libraries are very
useful as they allow you to split a complex program into more than one file.
Library files generally have the extension .h.
See the figure below for an example in which two libraries are included, one for
working with strings and one for controlling LCDs:
Includes in Arduino.
This default structure, in conjunction with the other concepts you just learned,
will be the core code tools of all your Arduino programs.
Continue to learn from reading the next section of this chapter. There we will
talk about the hardware interfaces of the Arduino board and how to control and
use them in your applications.
Hardware Interface
In the first part of this chapter on how to program Arduino, we covered only
software development issues. Functions, libraries, decision structures, and loops,
are tools used in your code to implement the logic you need.
But we also have the hardware!
Some things end up repeating in every program. Configuring digital and analog I
/ Os, establishing a serial communication channel, and generating/reading PWM
signals are basic concepts you will always need for most of your applications.
Thinking about it, let's understand how this is done in this session.
Digital I / Os
The Arduino has 14 digital inputs/outputs. These I / Os are used to read and
generate signals of a digital nature, that is, signals that assume only two states:
high (5 V / 3.3V) or low (GND).
Before using a digital pin, you must set it as input or output. By default, pins are
configured as input, but it is good programming practice to make this explicit in
your code.
The functions you will use to configure, read, and set a digital pin are:
void pinMode ()
Where pin is the digital I / O number you want to configure and mode can be
INPUT, INPUT_PULLUP and OUTPUT. For example, to set pin thirteen as a
digital output, you would write:
int digitalRead ()
The function used to read the state of a digital pin. In this case, you must have
set the pin as an input. The syntax of this function is:
digitalRead (pin);
Where pin is the number of the digital pin, you want to read. For example, if you
want to know if pin 13 is high or low, you should write the following line of
code:
X = digitalRead (13);
void digitalWrite ()
Finally, the function to write in the pin, or as it is said, “set” the pin to a certain
logical level. The usage syntax is as follows:
The pin is the pin number you want to "set." Value can be HIGH or LOW. So, if
you need to set pin 13 to a high logic level (5V), you should write the following:
Remember that to use this function, the pin must be set to output. A classic
example of using digital I / Os is led blink; a simple firmware focused on
flashing a led. See the program below:
In the infinite loop, the digitalWrite (13, High) function is called, responsible for
assigning a high level to pin 13, that is, the led connected to pin 13 is activated.
Next is called the delay (1000) function, which pauses the loop for a thousand
milliseconds, that is, for one second.
After waiting for this time, the digitalWrite () function is called again, but this
time to assign a low logic level to pin 13, i.e. to turn off the LED connected to
pin 13. Finally, the delay function (1000) is again call to pause another second.
Analog I / Os
The analog channels are 6. These inputs are used to read analog signals, i.e.
signals whose voltage level varies continuously between 0 and VDC (usually 5
or 3.3V).
These inputs are connected to the ATmega328 A / D converter. The A / D
converter is an internal circuit to the MCU responsible for converting the analog
quantities applied to the inputs into a digital value with which the processor can
work. The Arduino UNO A / D converter has a 10-bit resolution. This means
that a signal ranging from 0 to VDC in analog terms when converted to digital
will be a value ranging from 0 to 1024. Each unit in this range from 0 to 1024
corresponds to VCC / 1024.
If the reference voltage is 5V, each unit in this range from 0 to 1024 will
correspond to 4.88 mV.
To work with analog inputs, you will use the following functions:
analogReference (type)
This function is used to set the A / D converter reference voltage. Its syntax is:
analogReference (type);
Which type defines the possible A / D channel settings. Are they:
DEFAULT: The default conversion voltage is the board supply
voltage. Usually, these values are 5V or 3.3V
INTERNAL: Internal reference of 1.1V in Atmega168 and
Atmega328, and 2.56V in ATmega8;
INTERNAL1V1: 1.1V reference, only on Arduino Mega;
INTERNAL2V56: Internal 5.6 V reference, only on Arduino
Mega;
EXTERNAL: Voltage reference applied to the AREF pin (between
0 and 5V).
To configure the A / D converter to operate with external AREF voltage, for
example, you must write the following:
analogReference (EXTERNAL);
The other function used is:
int analogRead (pin)
This function is used to read the value of one of the analog inputs. Its syntax is
as follows:
SensorValue = analogRead ( pin );
SensorValue is any variable to store the value read. The pin parameter is the
input number you want to read. For example, if you want to store the value of
analog channel 1, you would write:
SensorValue = analogRead ( 1 );
Analog Sensor Example
In the example below, we see how an analog sensor is read. This sensor could be
a thermistor to measure temperature, a potentiometer, a light sensor, and any
other whose output signal is analog.
In the void Setup () function, we set pin 13 as the digital output and the A / D
converter reference voltage for DEFAULT, i.e. the board supply voltage.
In the infinite loop, we use the analogRead () function; to read the sensor value,
which in this case is located at pin A0 (value 0 could also have been assigned).
After reading the sensor value, pin 13 is activated, and shortly after that a delay
whose wait value is the read value of the sensor is called. That is, the hold time
depends on the value read from the sensor. After the first delay, pin 1 is
deactivated, and a new delay is called.
This program only turns on and off the LED connected to pin 13, varying the
waiting time according to the sensor signal.
Serial Communication
Serial communication, known by the acronym UART, is a very interesting
feature to make a communication channel between the board and the computer
or between the microcontroller and other modules such as GSM, GPS devices,
among others.
Here are the main functions for using Arduino UNO serial channel. On the
board, you can see that there is a digital pin named RX, and another pin named
TX. These are the two pins used in serial communication.
Serial.read (): Reads the most recent byte of the read buffer.
Serial.print (): Writes a given the word in ASCII code to the serial
port.
Serial.println (): Same as above, but it adds at the end of the word
a line break character (/ n).
The Arduino IDE has a serial terminal that can be used to view receiving and
sending data to the board. To access this serial terminal, click the Serial Monitor
icon or go to Tools -> Serial Monitor menu.
PWM
The PWM technique, which stands for Pulse Width Modulation, is a technique
used to vary the average value of a periodic waveform. The basic idea of PWM
is to keep the frequency of a fixed square wave and vary the time the signal is at
a high logical level.
That is, the time the signal is activated varies. This time is called the Duty Cycle,
and it is by varying this time that the average value can be varied proportionally.
Arduino Uno has specific pins for PWM outputs. These pins are indicated by the
'~' character in front of their number. The function used to generate a PWM
signal is AnalogWrite, see its syntax below:
Pin_PWM corresponding to the pin to which the PWM will be applied. Value is
the duty cycle to be applied to the PWM signal. This value must be between 0
and 255, with 0 being a 0% duty cycle and 255 being a 100% Duty Cycle.
Programming
Let's now make an example application for you to train the knowledge gained.
This example will be a little different. We will not show any code, because
everything you will need, the functions and programming structures, have
already been shown in the previous examples.
Here in our example, we will describe the application and just present the logical
structure of the program. You are the one who will have to implement in your
Arduino by replacing the logical descriptions with the necessary functions and
codes, as you learned in this post. So, are you excited ?! To enter the Arduino
world, you have to be!
Let's start.
Challenge
Our application is as follows:
From the logical point of view, the problem does not require major
elaborations. We basically have to monitor a temperature sensor
continuously, and based on the variations that the sensor perceives,
we will adjust the Duty Cycle of a PWM applied to an LED and also
send the temperature data to the PC via a serial port.
Algorithm
Let's draw an algorithm of what this application would look like. We already
know the base structure of every Arduino program, which is the void Setup ()
and void Loop() functions. In the image below, you can see the walkthrough of
how your void Setup () function should look.
Examples:
Now the algorithm of what the Void Loop () function should look like.
Example §
void loop ()
{
// Here is our application itself
Step 2: Knowing the sensor's temperature range, convert the read value using a
factor to fit a range from 0 to 100
Step 3: Use the converted value to vary the PWM Duty Cycle applied to pin 13
led
Step 4: Convert the read value from the temperature sensor to an actual
temperature value.
Step 6: Use a delay to regulate the reading frequency of the sensor and also to
ensure that serial communication has finished sending data. Writing data on PC
and computationally slow operation
So, now it's easy, right ?! Go back to the previous topics of the text, identify
which functions to use, and write your code.
Installing Ardublock
Once Arduino is configured, go to the Ardublock website to download and
install Ardublock on the Arduino IDE:
Once you find this folder create a subfolder named: tools and inside
it another subfolder called ArduBlockTool and yet another subfolder
called tool.
Copy the downloaded file to this last folder.
Now when you open Arduino IDE, in the tools section, Ardublock
will appear in the list. (See figure below).
Phases
1. Loop Function
Any Arduino program must contain the loop function. This function is
performed indefinitely when Arduino is turned on. So that's where we want to
put our blocks.
Hit the Control section and drag the loop block to the desktop;
Push in the Pins section and drag the digital pin set block to the
desktop;
This block has 2 arguments: Pin number and desired logical state.
Push in the Pins section and drag the digital pin set block to the
desktop;
3. Lead Time
Let's use the delay milliseconds block to make a delay of 1 second. Its parameter
is the time delay in milliseconds.
Click on the Utilities section and drag the delay milliseconds block ;
4. Connection
Ardublock, like the Arduino language, is sequential so that it will perform one
function at a time. To give the instructions of instructions in Ardublock, we
connect one function below the other by simply dragging and attaching one pad
below the other.
Do this for the last 2 blocks created. Placing the delay below the
digital pin set.
Now, these 2 little blocks form one block. Since we want to turn the LED on for
a second and then turn it off for a second, we need a second block of this to do
the second operation.
Right-click on this block and hit the clone button to make a copy.
Snap the copy of the block created below the original block, and set
the second digital pin set to LOW
6. Comments
Make sure in the tools section of the Arduino window that the card
and communication port has been selected correctly.
Our goal during the preparation of this material was to pass as much information
as possible while maintaining a simple language. The idea is that anyone with
any knowledge of electronics and design can understand the material without
any major difficulties.
During the explanation, we also made several comparisons of UNO with other
versions of Arduino. This will allow you to learn more about the differences
between them, and to understand any schematic of the Arduino family better.
We hope you will enjoy it and like it.
Arduino UNO Project
Currently, Arduino UNO is the most popular and best-selling version of the
entire Arduino line, as well as serving as a base for other models such as the
Arduino MEGA 2560, for example. For this reason, we chose him to do this
section.
Designs across the official Arduino line are made using Eagle software. There is
a free version of Eagle that you can download and use to open or modify the
original Arduino designs. The original Arduino UNO project can be downloaded
directly from the Arduino website.
Installing Eagle and downloading Arduino project files are optional and are not
required to accompany this lesson.
Schematic Analysis
The complete schematic diagram of the Arduino UNO R3 can be seen in the
image below.
For ease of understanding, we have arranged it in the original layout. This was
done by just aligning the name and value of the components, and also slightly
improving the separation between them. However, no components have been
modified, removed, or added, maintaining 100% compatibility.
We also split the components into three main blocks: USB processor, main
processor and power. All of them will be explained in the following sections.
In the figure below, we identify all board components with the same names used
in the schematic. You can use it as a guide for locating components.
Now enough talk. Let's get down to business, which is the analysis and
explanation of the schematic. In the following topics, we will explain how each
of the three main blocks works:
USB processor
Main processor
Food
USB Processor
Let's take a closer look at how the ATmega16U2 USB processor is implemented.
The figure below shows the circuit in more detail:
USB processor schematic
USB Connector
On the left, we can see the USB connector named as X2. This is a Type B
female USB connector, and this is where you connect the USB cable. Other
versions of Arduino use different USB connectors. The Arduino Nano, for
example, uses the Mini USB connector, and newer versions like Arduino
Leonardo, DUE, and Zero use the Micro USB connector, which is the same as
used in most current smartphones.
The USB connector has two functions - bringing information from the PC's USB
port to the card, and also feeding Arduino when no external source is connected.
Leaving the connector, the signals and power from USB pass through the block
called "USB filter and protection." We will analyze all the components present
in it.
F1
First, all the current coming from the PC's USB port (which will power the
Arduino and other circuits) goes through the F1 component. This component is a
fuse, and has the function of protecting the PC's USB port in case of a short
circuit or accidental overload on the Arduino board. By default, each USB port
should be capable of delivering up to 500 milliamps of current, and the fuse is
there to protect it if this limit is exceeded.
In fact, this fuse is nothing more than a resistor whose resistance value increases
with increasing temperature (also known as PTC or positive temperature
coefficient). However, unlike a traditional fuse that blows when overloaded, this
component has the ability to reset itself when operating conditions return to
normal.
For current values of 500 milliamps or less, the fuse resistance value remains
low. In this way, the current flows freely through it (effectively it is as if it is not
there). However, when there is a short circuit or overload on the Arduino, the
current drained from the USB port increases. This causes more current to pass
through the fuse, causing it to heat up and increasing its resistance. Increased
resistance cuts the current flow, effectively functioning as a blown a fuse.
However, if the short circuit or overload is removed, the fuse cools, and its
resistance value lowers back to its original state.
All versions of Arduino with USB port have this fuse. It is the MF-MSMF050-2
model manufactured by Bourns
Z1 and Z2
USB communication is via the connector pins labeled D- and D +. These signals,
after exiting the connector, pass through components Z1 and Z2. They are
known as varistors, and have the function of protecting the ATmega16U2 pins
against electrostatic discharge, which could cause the processor to burn out or
malfunction.
Electrostatic discharges or ESD(electrostatic discharge) are events that occur
when approaching an object charged with electrical charges to another that is
discharged. The most common example of electrostatic discharge is when you
walk on a rug or carpet wearing a rubber-soled shoe, and then take a shock when
you try to open the metal door handle. In this case, your body is charged with
electrical charges because of the friction of the shoe with the carpet; then these
charges are quickly transferred to the door handle, causing you to receive a slight
shock. If your body is charged, and instead of the doorknob, you touch an
electronic circuit board, loads are transferred to it, which may cause circuit
damage (even with the board off).
Electrostatic discharges occur all the time, and in most cases, the current is too
low for you to feel a shock, so they end up unnoticed, but can still damage the
most sensitive components. Components and circuits with which the end-user
has direct contact (as is usually the case with USB ports) deserve special
attention about ESD protection, as they normally receive the discharges.
Like the fuse, the varistor is also a resistor, but in this case, the resistance value
decreases as the voltage on it increases. At low voltage values, such as occur
during normal USB port operation, the resistance of the varistor is quite high (in
the order of 100 mega ohms), so the signals pass through them without
deviations. However, when an electrostatic discharge event occurs, the voltage
increases rapidly (up to several kilovolts), causing the varistor resistance to drop,
and diverting excess current from the ATmega16U2 pins to the Arduino GND,
protecting the processor.
Arduino versions that use FTDI chips in place of ATmega16U2 usually do not
have ESD protection components. This is because these chips already have built-
in protection structures, which is sufficient in most cases.
L1
The component called L1 is known as ferrite. Basically, ferrites are used for
noise suppression. In this project, its function is to filter out possible noises that
may come through the USB cable mesh to Arduino, as well as to isolate the PC
from noise generated by Arduino. Not all versions of Arduino have this
component, and its presence is not required for operation.
Oscillator
The oscillator is the heart of any processor and is responsible for generating the
clock pulse. Virtually all existing processors use an oscillator, and their
implementation is often quite similar. Although it uses few components, the
operation of this circuit is relatively complex, so we will not go into detail and
focus only on the fundamental features.
In addition to the crystal, there are two 22 PF capacitors (C11 and C9), and a 1
Mega Ohm resistor (R1).
Capacitors C1 and C2 are required in this type of circuit, and in addition to their
other functions, have the role of adjusting the crystal frequency. Usually, each
crystal has the specification of which capacitor value is optimal for its operation,
and it is the designer's role to choose the value accordingly. Wrong capacitor
values may alter the resonant frequency of the crystal, or even impede its
operation.
USB Processor
This block comprises the USB processor itself, i.e. the ATmega16U2 chip. In
this project, he is responsible for receiving data from USB and turning it into
serial signals.
USB Processor Block
C7
We can see the 100 nanoparad C7 capacitors connected directly between the 5
Volt supply voltage and the GND. In this circuit, the capacitor performs the
function of the " decoupling capacitor." Capacitors with this function are very
important in the operation of digital integrated circuits. Virtually all integrated
circuit manufacturers recommend the use of capacitors attached to the power
pins, with 100 nanofarad a classical value. In addition to the value, the most
important requirement when using a decoupling capacitor is its location and
should be positioned as close as possible to the power pins of the integrated
circuit in question (if it is removed, its effect will be null).
D3
Diode D3 has the role of reinforcing the electrostatic discharge protection (ESD)
on pin 24.
But why is the diode placed only on this processor pin, not the others?
Well, the story is a little long, but we can say that processors usually already
have internal ESD protection structures, which are comprised of two diodes
connected to each pin. However, the reset pin is a special case as it is used
during software recording, and some (but not all) programming methods apply
12 Volts to this pin during the process. This fact prevents the ESD protection
structure from being fully implemented in the reset pin since the diode would
prevent the application of 12 Volts the same. In this way, the chip manufacturer
removes one of two internal protection diodes. As the Arduino production does
not use the programming methods that require the 12 Volts to be applied to the
reset pin, the omitted internal protection diode has been reinserted externally.
The use of this diode is optional and is not present in many versions of Arduino,
such as Pro, ProMini, Nano, Duemilanove, MEGA and others.
C8
The ATmega16U2 processor has an internal voltage regulator, which is required
for the operation of some of its circuits. For this regulator to work properly, the
manufacturer recommends that a capacitor with a value of 1 microfarad be
connected to pin 27 of the processor (named as UCAP).
USB LEDs
There are two LEDs, RX and TX, which are controlled by processor software
and used to indicate USB communication activity. That is, when there is
information sent from Arduino to the PC, the TX LED flashes, and when there is
information sent from the PC to Arduino, the RX LED flashes. The
implementation of this circuit is very simple and traditional; there is only one
resistor in series with each LED (RN2B and RN2C) with the value of 1 kilo
Ohms, which has the role of limiting their current.
Programming Connector
These two resistors are connected in series with the serial RX and TX signals
that go to the ATmega328 main processor, i.e. they are the link between the two
processors. The presence of these resistors in series allows you to use Arduino
shields that make use of the ATmega328 processor serial. In a way, it's as if the
serial coming from the ATmega16U2 processor is disconnected the moment you
plug into Arduino, a shield that uses the serial. This brings greater flexibility in
the use of Arduino, as it allows the use of serial with other shields, but it is as if
the USB port was disabled while there is a serial shield plugged in. Thus, to
program Arduino, or to communicate with the PC, it is necessary to unplug the
shield that uses the serial.
C5 and RN2D
The RN2D resistor is labeled "USB boot En" and is a pull-down resistor.
However, we could not get more information about its function.
JP2
JP2 Connector
It appears to be an expansion connector, but it does not come soldered to the
board, and we have no further information about its function.
Ground
Soldering Jumper
It is a soldering jumper, which is located on the bottom plate. It serves to
connect the ground from the USB cable loop (after passing through the L1
inductor) to the main ground. In electronic projects, designers typically make
this connection between the "different grounds" using a jumper, as this ensures
that they are connected only at one point, which prevents current from
circulating in unwanted areas of the board. This jumper is already factory closed.
Main Processor
Now that we understand the operation of the USB processor, it will be much
easier to understand how the main processor works, as the circuit
implementation is very similar.
As we said earlier, in Arduino UNO, the component that plays the main
processor role is ATmega328, also manufactured by Atmel Semiconductor and
named as ZU4 in the schematic.
Other Arduino models use different processors. For example, there are versions
of Arduino Nano and Duemilanove that use ATmega168, which is basically a
component identical to ATmega328 but with less memory. The Arduino MEGA
2560 uses the ATmega2560, which has more pins and more memory than
ATmega328 is the "brain" of Arduino UNO, and in short, we can say that it has
three functions:
Receives sends, and interprets serial signals coming from the
ATmega16U2 USB processor.
Runs the software that is programmed into it.
Interacts directly with shields and external elements, performing
device activation and sensor reading.
The figure below shows the main processor block:
The ceramic resonator is named Y2 in the schematic, and the model used is the
CSTCE16M0V53-R0 manufactured by Murata. Ceramic resonators are
components with crystal-like function, i.e. they are also responsible for
generating the sine wave that will serve as the basis for the processor clock
signal.
Usually, the ceramic resonator is more compact than the crystal, and they come
with the adjustment capacitors installed internally, making the circuit simpler.
However, in terms of accuracy, the ceramic resonator usually performs worse
than the crystal; we can say in general that the resonator has an accuracy of 0.5%
against 0.003% of the crystal. That is why resonators are most commonly used
in compact and space-saving applications.
Arduino versions like Duemilanove, Diecimila, and MEGA use the crystal as a
resonant element. We are not sure what drove this switch to the ceramic
resonator in Arduino UNO. It may have been a legacy of the Arduino Nano, as
he always used resonators, but it's hard to say for sure.
Anyway, the important thing is to know that the circuit, in general, is the same,
only the capacitors are omitted (since they are already inside the resonator), and
the 1 Mega Ohm resistor that assists in the start of operation (R2) continues.
Main Processor
ATmega328 Processor
This is also a block similar to the USB processor. We can see in the schematic
the 100 nano Farad components C4 and C6, which perform the function of
decoupling capacitors for pins 21 and 20, respectively. The designer could still
have placed another capacitor to uncouple pin 7, as recommended, but it was not
inserted in this scheme.
The RN1D and D2 components fulfill the pull-up and ESD protection function
for the reset pin, similar to the RN1C and D3 components on the USB processor.
We can also notice the serial signals coming from the USB processor, which are
connected to pins 2 and 3 of the ATmega328, as well as the reset signal
connected to pin 1.
Programming Connector
This connector, like the USB processor, is used for programming the first
software made at the Arduino factory (this software is called bootloader).
Reset button
The button is named as RESET in the schematic. When pressed, the button
closes the pins 1 and 2 contacts with pins 3 and 4, connecting the processor reset
pin directly to the GND. This causes a low logic level on this pin, which resets
the processor.
Shield Connectors
Note that in the schematic, all signals with the same name are interconnected,
regardless of whether there is a physical connection between them. For example,
the two branches named AD5 / SCL are electrically connected, even though
there appears to be a "loose" end on the connector (see complete block schematic
image), so do the 3.3V, RESET, GND and all others.
Try to match the connectors shown in the schematic with the connectors on the
board. Note that they are named as POWER, IOH, AD, and IOL, and the green
caption indicates the numbering or function of the pin in Arduino. Also, there is
an inscription indicating the size and model of the connector, for example, the
caption "8x1F-H8.5" indicates that it is an 8-pin connector, a female-type
speaker, and an 8.5mm.
food
Let's move on to the last block of the schematic, and see how the Arduino UNO
power supply works.
Input Jack
This connector, named X1, is where you connect the external power supply plug.
It is convenient to use an external source to power the Arduino when it cannot
always be plugged into the PC's USB port, when there is an element in the
application that needs to be powered with a voltage greater than 5 Volts, or when
the circuit requires a current than 500mA supported by the PC's USB port.
Jack for an External Source
This connector is a female type and set to 2.1 mm, which means the pin in its
center is 2.1 mm in diameter. This means that the source used must have a male
connector, also with 2.1 mm and positive center (i.e., the inside of the plug has
positive voltage compared to the outside, which is the GND).
Protection Diode
The current flowing through the input jack soon encounters the first component,
which is the protection diode D1. Its function is to protect the Arduino if an
inverted polarity source is accidentally plugged into the jack. An inverted
polarity font, in this case, would be a negative center model.
After passing through the protection diode, the voltage from the source is called
a VIN, and is also available on one of the Arduino connectors.
The diode used is the M7 model, which is the SMD version of the popular
1N4007, and the maximum current supported is 1A. However, the voltage drop
on this diode is large, reaching 1.1 Volts, which can bring undesirable effects
such as increased thermal dissipation, causing loss of efficiency. In this case, a
Schottky diode would be more appropriate because the voltage drop on it is
smaller.
Most other versions of Arduino do not specify which diode model was used.
Also, some versions like Nano do not have this polarity reversal protection.
There are still other versions like Leonardo and Arduino Micro that use other
components, or the same diode connected differently. Download the designs of
these boards and try to compare the differences in circuits.
5V regulator
The next component of the circuit that we will look at is the 5 Volt regulator
named U1. Its function is to lower the source voltage (which can have a value
between 7 and 20 Volts) and stabilize it at 5 Volts, which is the recommended
voltage for the operation of Arduino components, such as the two processors. In
addition, the regulator also acts as a filter, attenuating any noise that may be
present in the voltage generated by the power supply.
This regulator is called a linear regulator, and the means it uses to lower the
supply voltage is simply to dissipate excess power., throwing it away as heat.
For this reason, it has low efficiency and usually gets very hot in some cases. If
you power your Arduino with a 12 Volt source, for example, you will only be
using 40% of the power supplied by the source, the other 60% being thrown
away as heat. This happens with any linear regulator, regardless of manufacturer
and model. So don't be alarmed if this component starts to heat up when you use
Arduino with an external source as it is there for that. If the board is well
designed, the temperature will be within limits tolerated by the component (but
will probably be above the limit tolerated by your finger, so be careful).
The more the voltage from the external source increases, the less efficient the
operation of the linear regulator becomes. Using a 20V power source, for
example, only 25% of the energy is harnessed, with 75% being thrown away as
heat. So, whenever possible, use small power supplies such as 9 or 7.5 Volts, for
example.
In Arduino UNO, the component used for the 5 Volt regulator is the NCP1117
manufactured by ON Semiconductor, and it uses two capacitors to assist you in
this task, PC1 and PC2, both 47uF. These capacitors are important for the proper
functioning of the regulator. PC1 helps to stabilize the input voltage from the
power supply, and also provides the power to supply any power surges that
occur while using the card. The capacitor PC2 has the same stabilizing role but
in the output voltage. Also, this capacitor still plays an important role in
regulator stability and should be chosen carefully according to the
manufacturer's instructions for capacitance and series resistance (this is a
parasitic resistance that every capacitor has, it is called ESR). or "
Despite the low efficiency, virtually all versions of Arduino use a linear
regulator because they are easy to use, inexpensive and reliable. Some models
use the same NCP1117; other versions use different chips. Arduino
Duemilanove uses, for example, MC33269D-5.0, while Arduino Nano uses
UA78M05. However, the function and operation are always similar. There are
still other versions, such as Arduino Due, which does not use a linear regulator
to generate the 5 Volt voltage (download the schematic from the Arduino
website and try to find out the differences. Tip: the IC used is IC2, model
LM2734Y).
In the Arduino UNO design, the 3.3 Volt voltage is only used on component U5
(which is part of the circuit switching we will see later), on the other component
is powered by it. And why is this regulator present? Typically, the 3.3V voltage
is used by users to power other external circuits or shields that use this voltage.
Especially the most modern electronic circuits are migrating from the classic
voltage of 5 volts to 3.3 volts, is very common today in many devices. This is
why it is useful to have this feature available in Arduino.
Some Arduino versions that use the FT232 chip for the USB-serial converter
function, such as Duemilanove, Nano, and MEGA, do not have a second
regulator to generate the 3.3V voltage. In this case, it comes from an internal
regulator present on the FT232 chip itself. Although the current capacity is
reduced (50 milliamperes), it is sufficient for the vast majority of cases.
Switching Circuit
As we have seen before, Arduino can be powered either from an external power
supply or directly from the PC's USB port. In cases where Arduino is connected
to the USB port, and there is still an external source connected to it, there would
be a conflict between them as both would try to power Arduino at the same time.
This could cause damage to the power supply, the PC's USB port, and also the
Arduino.
The switching circuit has the function of resolving this conflict. It disconnects
power from the USB port whenever a power supply is connected to the Arduino.
We can then say that the external source will always have a preference to feed
the set. This process is transparent to the user, so you can connect and disconnect
the power supply even when the card is running (assuming USB has the power
to power the entire set).
The components responsible for this function are resistors RN1A, RN1B,
transistor T1 and chip U5.
Let's start by explaining how the T1 transistor works (the model is the FDN340P
manufactured by Fairchild Semiconductor). Since a complete understanding of
this component involves more complex concepts such as silicon doping and PN
junctions, let's try to abstract a little, and show it more practically.
The MOSFET remains off (cutting current between the drain and source
terminals) as long as the voltage at its control terminal is at a high logic level.
The MOSFET stays on (letting current flow between the drain and source
terminals) as long as the voltage at its control terminal is at a low logic level.
Sending the command to turn transistor T1 on and off is component U5. This
component is an operational amp (op-amp). The op-amp is one of the most
versatile components in existence, and it is widely used in analog electronic
projects, making it possible to make oscillators, filters, buffers, adders, and a
host of other applications. However, on the Arduino UNO switching circuit, the
op-amp is used as a comparator, and this is how we will analyze it.
A comparator has 2 input terminals, which are called - and +, plus an output
terminal. Its function is to compare the voltage present at the terminals - and +,
indicating through the output terminal logic level, which of these voltages is the
highest. The operation can be described as:
The voltage at the output terminal remains at a high logical level, while the
voltage at the terminal + is greater than - terminal voltage.
The voltage at the output terminal remains low logic, while the voltage at the +
terminal is less than - terminal voltage.
Let's go back to the schematic now. In it, we can see that the voltage present in
the - terminal is the 3.3V voltage itself generated on the U2 regulator. Already
the voltage present in the + terminal is the voltage VIN from the external source
after passing through the resistive divider formed by resistors RN1A and RN1B.
Since both resistors have equal values (10 kilo Ohms in this case), they form a
divisor by two, so that the voltage present at the + terminal of the comparator is
half the voltage VIN (in fact one would also have to discount the voltage drop
over diode D1, but let's ignore that because its influence is low).
When there is only a USB voltage present, VIN is zero since no external source
is connected. In this situation, the voltage at the terminal + is less than - terminal
voltage, making the comparator output remain at a low logical level. This low
logic level is sent directly to the MOSFET command terminal, causing it to turn
on and conduct current from the USB port. This allows it to power the entire
circuit (in the schematic, the current coming from USB comes from the signal
called USB VCC that originates right after passing through fuse F1, remember
that signals with the same name are always connected to each other, even if there
is no physical connection in the schematic).
Since the source voltage is always divided by two at the comparator input, the
minimum value required for it to be able to turn off the MOSFET is 6.6 Volts.
This value is below the recommended minimum limit for external source
Arduino power (which is 7 Volts), so the external source will always have a
preference.
Still, another component is present in the switching circuit, which is the Farad
100 nano C1 capacitor. In the schematic, it is connected to two "loose" pins just
above the U5A comparator, but these pins are part of the same U5 component.
LED D13
The next circuit we will look at is the Arduino D13 pin LED, which is named L
in the schematic. This is the LED that flashes when we run the Blink example.
Actually, this circuit is not part of the power circuit, but we inserted it in this
section because it shares the same U5 component of the switching circuit.
This LED has a 1 kilo Ohm RN2A resistor connected in series with it to limit its
current, and they are connected directly to the output of another amp op.
However, although there are two amp-ops in the schematic (U5A and U5B),
both are inserted into the same package, i.e. they are part of the same
component.
The op-amp was used because pin D13 does not have the exclusive function of
turning the LED on and off. It is also, for example, the SPI communication clock
pin (SCK). If the LED were turned on directly, it would drain from pin D13 an
approximate current of 3 milliamps while it was on, adding an extra charge. This
could influence and impair the use of the D13 pin in other applications.
The op-amp, in turn, has a high impedance on its input pins. This means that the
current consumed by them is very small (around 250 nanoamps). This way, it
virtually adds no extra charge to the Arduino D13 pin, eliminating the influence
of the LED. All in all, you drain from the pin a current of only 250 nanoamps to
drive a load of 3 milliamps (12000 times less).
Op-amp is not the only circuit that can be used for this purpose; it is also
possible to use buffers or transistors. Another option is to use high brightness
LEDs, which are more efficient. This increases the resistor value, reducing the
load on the pin, which makes the influence of the LED negligible.
The Arduino Nano does not use this circuit - LED goes directly on the processor
pin.
LED ON
This is the last block we need to analyze, and it is also the simplest. This is the
LED that always stays on while Arduino is on, it is named in the schematic as
ON.
The circuit has two resistors, RN4C and RN4D, both 1 kilo Ohms and connected
in parallel. Effectively they work as a single 500 Ohm resistor and have the role
of limiting the current in the LED.
Fiducials
The most attentive may say that there are still missing components to be
explained. They are the three circles that appear loose just beside the POWER
connector on the original schematic. The figure below shows where they are.
In the project published by the Arduino team, there are 3 fiducial points, and
they are located below the source input jack, reset button, and ATmega328. This
way, you can no longer see them after the components are assembled.
The monitors of the early laptops of the 1980s used the same LCD technology!
And without LED lighting.
In the early days of Digital TVs, this LCD technology was also widely used.
There are currently other technologies that reproduce images much more
faithfully.
The LCD market is always innovating, and today we have color displays: blue,
red, green, etc., that is, for all tastes. This Guide will always reference blue
LCDs. But be aware that everyone has the same principle of operation. What
changes only is the color of the LED that illuminates it.
For the use of microcontrollers such as Arduino, the most common LCDs are 16
× 2 (16 characters x 2 lines) or 20 × 4 (20 characters x 4 lines).
16 × 2 blue LCD
16 × 2 green LCD
20 × 4 blue LCD with I2C
20 × 4 green LCD
The most widely used LCD controller chip in the world today is one that was
developed by Hitachi - the HD44780, a long time ago. He is so good; he has
become a standard. If you want to deepen your study of LCDs by learning how
to use all the many features available, I recommend reading the datasheet.
Datasheet HD44780
Communication between the LCD Controller and the Microcontroller (for
example, Arduino) can be parallel (4 or 8 bits) or serial (I2C). For a limited
number of digital ports, we recommend using the I2C interface.
As a curiosity, be aware that this chip has an internal ROM where some
characters and symbols are already engraved. And for you to generate your own
symbols, there is an internal RAM. Very versatile!
Here's a part of the internally recorded Character Table - each character is made
up of a 5 x 8 dot matrix:
LCD pinout
16 × 2 LCD Datasheet
At the top of the display are 16 holes where pins or cables for communication
and power can be soldered. Caution: Incorrect connection or use of voltages
above 5V may damage the display.
NOTE: The 16 × 2 LCD pinout is identical to the 20 × 4 LCD!
If you want to consume less current, use a series resistor, for example, 220 ohms
(7.6 mA consumption).
For LCD contrast adjustment, the voltage on pin 3 (VO) must be adjusted. Use a
20K ohm potentiometer. At the ends of the POT connect + 5V and GND. Center
pin connect to LCD pin 3. On my blue 16 × 2 LCD, the VO voltage was
approximately 1.0 Volts.
When this type of LCD Display was developed, the microcontroller data buses
used 8 bits. In the Arduino era, the available digital ports are reduced. To
address this limitation, a specially dedicated I2C interface for LCDs has been
developed. The chip used in this module is the PCF8574. It is a parallel port
expander, has an I2C interface, and can control up to 8 bits either as input or
output (depending on configuration). I2C interface speed is limited to 100 kHz.
The supply voltage can be either 3.3V or 5V, which enables it for all common
microcontrollers.
This photo is the back of the LCD Display with the I2C Interface already
connected.
16 × 2 LCD with I2C Interface.
The Blue potentiometer on this interface is used for contrast adjustment. After
the display is energized and programmed, adjust it to make the image visible.
The LED jumper is used to activate the Backlight LED. If you do not want to
use the LED to save power, remove this jumper. The red LED on the board is an
indication that it is energized.
PCF8574 Addressing
The PCF8574 chip has some addresses already defined, depending on the model
(identify your module chip):
PCF8574 = 0x20H
PCF8574A = 0x38H
In addition to the basic address, through 3 address pins (A0, A1, and A2), the
addressing can be changed, as in the case of using more than one chip on the
same bus. See on the module jumpers A0, A1 and A2.
One more very important detail! For the I2C interface to function properly,
PULL UP resistors must be used on both lines (SCL and SDA). These resistors
connect these lines to the VCC. In this I2C module, these PULL-UP resistors
(4.7 K ohms) already exist. So do not add any more resistors on the interface.
In the case of a parallel bus for Arduino, only 4 data bits are used. But for
control lines, more ports are needed (RS, R / W, and ENABLE). Adding a total
of 7 doors! This type of communication should be avoided if there is no number
of ports available for the application.
This is the Fritzing circuit diagram for testing the 16 × 2 LCD Display with
Arduino Nano:
And this is the electronic diagram of the same circuit - Arduino Nano with 16 ×
2 LCD:
Note that pin 5 (R / W) is grounded (level zero). Therefore the display can only
receive data (write)
To position characters on display, there is this row and column addressing. See
that the count starts from 0 and not from 1 (Row 0, column 0)! The differences
from a 16 × 2 display to a 20 × 4 display are the number of characters and the
addressing. All commands are identical for both types of displays.
In this assembly, we will use the Liquid Crystal Library, so it must be installed
using the procedure below.
To install the new Library, click Sketch> Add Library> Manage Libraries.
After opening the Library Manager window, refine the search by entering the
library name. In the selected library, click More Info and then Install. After a
few seconds, it will be automatically installed. Remember that your computer
needs to be connected to the internet. After installing the library, you must close
and reopen the Arduino IDE program.
Using examples from the Liquid Crystal Library, I did this Sketch to test
various Display functions:
print message
flash message
cursor test
message scroll test
message direction test
To configure Display Type:
lcd.begin (16.2); // setting the LCD - 16 columns and 2 rows
lcd.begin (20,4); // setting the LCD - 20 columns and 4 rows
Another great feature of the Liquid Crystal Library: create special characters!
This library has a method that allows, by controlling the 5 × 8 matrix points of
each LCD character, the creation of any symbol or special character. Use the
Link Character Generator below to create Sketch code. To draw, click on the 5 ×
8 matrix points. Copy the generated code and insert it into Sketch.
LCD16x2_Arduino_Caracter:
I found on Youtube, this application also very interesting to use large numbers
on the 16 × 2 LCD Display.
The Liquid Crystal library is very versatile! Allows the use of various interface
types:
SPI interface
As a reference for reference, this is the link to use the SPI interface (little used):
LCD16x2 with SPI Interface – ARDUINO
Do not forget to connect the GND of the I2C interface in GND Arduino. Same
for 5V. The current draw measured by me was 27.5 mA. Make the adjustment
of the contrast using the pot I2C interface.
This is the Fritzing circuit diagram for testing the 16 × 2 LCD Display (I2C
Interface) with Arduino Nano:
This is the electronic diagram of the same circuit - 16 × 2 LCD Display (I2C
Interface) with Arduino Nano:
I2C Scanner
The first test to be done is to identify the interface I2C address. Run Sketch I2C
Scanner. In my assembly, the address found was:
I2C Address found: 63 (0x3F) - This address should be entered in Test Sketch
I2C Scanner
// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011
#include <Wire.h>
void setup ()
{
Serial.Begin (9600);
// while (! Serial)
{
}
Serial.println ();
Serial.println ("I2C scanner. Searching ...");
byte count = 0;
Wire.begin ();
for (byte i = 8; i <120; i ++)
{
Wire.beginTransmission (i);
if (Wire.endTransmission () == 0)
{
Serial.print ("I2C Address Found:");
Serial.print (i, DEC);
Serial.print ("(0x");
Serial.print (i, HEX);
Serial.println (")");
count ++;
delay (1);
}
}
Serial.print ("Found");
Serial.print (count, DEC);
Serial.println ("device (s).");
}
void loop () {}
This is the Liquid Crystal I2C Library used in this test assembly (install it using
the procedure above):
Using the Liquid Crystal I2C Library, I created the program to test the same
functions as the previous example (4-bit interface):
print message
flash message
cursor test
message scroll test
message direction test
To conclude this book, we will present 5 Arduino project ideas that you can
employ on your home premises, allowing the home automation world to invade
every room, controlling and monitoring your safety and day-to-day tasks. Do
everything, right!).
If you have your Arduino, then it's time to get it off the shelf and dust it off to
get it to work (we're all guilty of it sometimes, don't you think?). Let's add some
modules, sensors, a little of our time, and achieve extraordinary feats.
There is not much secret in the items needed for this; you will basically need 1
Arduino, 1 Ethernet Shield or 1 Wifi Module, 1 Relay Module, LEDs and
jumpers. You can also give these commands directly from your smartphone via
Bluetooth.
RFID technology uses radio waves for communication and data transfer, where a
unique numbered tag (code) is embedded in a card or key chain, for example,
and when passing the encoded object in front of the reader, it will receive
information from the cardholder, where permitted, will release the door lock
giving access to the room.
The registration of the cards or tags that will be previously allowed to pass is
configured and saved directly in Arduino, which is responsible for comparing
the information, as well as managing the reading and command procedure for
opening the door by activating a relay, which consequently will release the
electric lock.
Of course, it is not enough to connect the Arduino and RFID reader for you to be
able to carry out this project, it is necessary that the door has previously some
kind of electric lock, which will be interconnected to the programming set,
executing the received commands.
For execution, you will need 1 Arduino, 1 RC522 RFID Kit (which includes
RFID Reader and two tags, one in keychain format and one in card format), 1
relay module, 1 16 × 2 display, 1 lock or electric lock and jumpers.
This type of home automation is not limited to door use but can be applied to
gates, drawers, cabinets, and anything else you can imagine, just use creativity
and put it into practice. For more details on this project, go to the “Arduino
RFID Access Control Project.”
3 - Intelligent Security Alarm Design with Arduino
For those looking for extra protection and not wanting to afford the high
purchase and monthly payment costs of modern and sophisticated alarm
systems, the little Arduino can be a great option, delivering great results and a
relatively low cost.
The Arduino can help automate the home security, providing a compact solution
(bringing together all in one device) to control PIR motion sensors, magnetic
sensors, sirens, cameras, electric locks, signaling lights and more, and this with
activation and deactivation controlled by safe codes handled directly on numeric
keypads.
The type of residence, the number of rooms and the security profile you are
looking for will define which sensors and modules to use, where you can employ
PIR motion sensors to detect movements based on the variation of infrared light
emitted by human body radiation, firing a siren if so, for example.
If you are using a large number of sensors, you may need to use an Arduino
Mega, which has many more ports to connect than Arduino Uno, which may
provide greater possibilities, emphasizing that in both cases, the operation will
be the same mode.
4 - Arduino Irrigation Project - Autonomous Greenhouse
Now the excuse is gone: "Puts, I forgot." Anyone who has a garden or
greenhouse knows that they should water regularly. You may love flowers or
have salads and vegetables in the greenhouse that you are eager to eat, but
watering can be a challenge, especially if you are traveling or going out at night
(this is because you should avoid watering during the day because water in
conjunction with the scorching sun can burn the leaves).
So what now? Shouldn't I plant anything else? Calmly, the solution is Arduino
home automation, where once again, it saves the day, allowing your garden to
keep itself watered with the help of specially developed sensors.
Using specialized soil temperature and humidity sensors, Arduino can detect
when plants need to be watered and trigger a solenoid valve or water pump, for
example by meeting the need for plants housed in that particular location,
because it will be able to Set when the land is dry and when it is wet (Real-
time!), presented better results than those in which a person manages.
And what will I need? Some similar items already used so far and some specials,
requiring 1 Arduino, 1 water pump or solenoid valve, 1 relay module, 1 Soil
Moisture Sensor and Jumpers, and of course, that specific location type
programming you want to automate, allowing you to stay alone. So now, this
daily watering commitment is no longer yours. For more details, go to the
“Arduino Automatic Irrigation Project.”
Excessive food is not good for the animal, the measure must be right and ruled
with defined intervals between meals, i.e. leaving the bowl overflowing with
food in the morning and forgetting for the rest of the day is not a good solution.
Nothing better than home automation with Arduino to break this deadlock and
proportionate a healthy habit that will influence your pet's health. You are
providing food at the right amount and at the right times.
I liked it, but how does it work? With a standalone feeder connected to the
Internet, you can send commands to Arduino to feed your dog or cat at the right
time or at scheduled times if using an RTC (Real Time Clock Module)
connected to the microcontroller system.
Efficient and simple, the feeder is fixed in a place already stocked with ration,
where a type of shovel stuck in an engine is responsible for dosing the amount of
food, which motor is driven by Arduino as previously scheduled, to serve more
or less, with a buzzer system to let the pet know it's time to eat.
For this automation, you will need 1 Arduino, 1 Relay Module, 1 Ethernet Shield
(if you want to connect to the internet) or 1 RTC (if you want to work at pre-
programmed times), 1 Motor, 1 Motor Driver, 1 Buzzer and Jumpers. Since here
everything is possible, you can replace any component with another, being mere
suggestions that may or may not be followed will depend on the will and
possibilities of who will do the installation and programming.
Finally, these 5 project ideas are just a few possibilities for starting home
automation with Arduino in your home and can be broadly extended due to a
large number of sensors and electronics modules currently in existence. Check
out every Arduino product line available on the website.
So which one are you going to do? Time to take Arduino off and put it to work.
More than ever, the electronic revolution is approaching; perhaps one day, we
may have a fully automated home, as intelligent as Iron Man's. While this day is
not enough, let's kick-start, because this decade will be the machines!
ARDUINO
The Shield
Where the peripherals available are not enough for our projects, we can purchase
one of the numerous “shields " through which the potential of the basic
electronic board extends, for example, adding the ethernet connection, Wi-Fi,
GPRS, a reader microSD and so on. It is no coincidence that there are numerous
add-ons or completely new projects defined as "Arduino-compatible" on the net,
precisely to express the concept of compatibility with this family both from a
hardware (connector/pin correspondence) and software (possibility firmware
execution); not least is the agreement reached with Intel that released the Galileo
board, pin-to-pin compatible with all Arduino shields and able to run any
program already written for the latter.
During this guide on programming with Arduino, we will refer to the first board
born in the family or the "Arduino Uno" which has all the credentials for the
realization of any project that comes to mind; given the absence of the native
Ethernet connection, it will subsequently be necessary to use the known "
Arduino Ethernet Shield. "
For those approaching for the first time the world of development on
"embedded" systems, it should be anticipated that very often we will have to
deal with extremely small orders of magnitude in terms of RAM and storage; we
will not talk about hundreds of MegaBytes (MB) or GigaBytes (GB)
respectively but much more likely than KiloBytes (KB). During this process, we
will see how many things can be done with such extremely reduced resources,
especially trying to taste the pleasure of interacting with the outside world.
Arduino Uno
The "Arduino Uno" is a board based on an Atmel microcontroller, ATmega328,
which has all the memory and storage necessary for our programs on board
(which as we will see are called “sketches "); in particular, we have available:
The main pins of the microcontroller are made available to the "maker" through
two connectors located on the edges of the board, through which it is trivial to
connect any other external device that can be driven through our program. In
particular, there are 14 digital pins and six analog pins, as the Atmega328 is also
equipped with a 6-channel AD converter (Analog to Digital) with 10-bit
resolution.
Each of the digital pins can be driven independently by software, setting the
level 1 (high) or 0 (low), and used as a GPIO (General Purpose Input Output)
pin; however, some of these pins have additional features if properly configured
and in particular:
In addition, the board provides two 3.3V and 5V output power signals that can
be useful for powering one or more external devices with which to
communicate, a RESET signal, and above all, an on-board LED that we will use
for our first application "Hello World."
The only direct connectivity with the outside world is characterized by a USB
connector that we can use to connect to our development PC. As we will see, the
PC will have a serial port to communicate with the "Arduino Uno," thanks to the
appropriate drivers to be installed and the "USB-to-serial" converter with which
the board is equipped (in practice the microcontroller is not has a native USB
interface but always uses serial communication).
The interesting thing is that being open-source hardware, and all the wiring
diagrams are available online on the official Arduino website, so the board is
absolutely "replicable" at home; in fact, there are many unofficial "Arduino-like"
boards.
It should be noted that the examples used in this guide are compatible with all
Arduino boards and with the Intel Galileo.
With this first part of the introduction, we introduced the Arduino project and the
first-born board in the large family of boards. In the "embedded" development,
before being able to write some code, it is necessary to have a good knowledge
of the hardware that will be used in order not to incur unpleasant
inconveniences. From the next part, we will start with the study of the IDE,
which will be our travel companion in the creation of the so-called Arduino
sketches throughout the entire book!
Firstly, it must be emphasized that the programming language used for Arduino
is C/C ++; we can talk about both languages, as it is possible to use the support
for the classes that C ++ makes available or not. Furthermore, the compiler used
is obviously dedicated to the Atmel AVR microcontrollers and is part of a well-
defined GCC toolchain.
With a compiler and a simple text editor, it is always possible to write and
compile a program but, to increase productivity and reduce development times,
we always prefer to use a dedicated IDE (if available); luckily with Arduino, we
have this possibility!
Download and Install the IDE
The Download section is available on the official Arduino website, from which
we can download the IDE for the operating system we use (Windows, Linux,
and Mac OS X are supported). In addition to the “Arduino 1.0.5” version that
interests us (current version at the time of publication of the guide), a Beta
version is available for the "Arduino Yun" board, a dedicated version for the
Intel "Galileo" and even the sources of the environment, given the open-source
nature of the project.
In the case of Windows, which we will use during this guide, we have the option
of downloading an installer or a simple ZIP file containing everything you need.
To avoid an unnecessary installation process, the second solution is absolutely
the best; in this way, we will simply delete the folder in case we need to update
the IDE or not want to use it anymore.
Once the content of the ZIP file has been downloaded and extracted, we click on
the executable file arduino.exe located in the main folder, and after a few
seconds, we will find ourselves before our eyes the only simple but essential IDE
window completely developed in Java.
The first operation is to select which board of the Arduino family will be used
(in our case, the "Arduino Uno") through the menu Tools "Type of Arduino."
Before connecting our board to the PC through the USB cable, let's take a look at
the IDE to see the features it makes available to us.
On the board, there are examples of pin management, on the use of the
analog/digital converter, on all types of connection from serial to Ethernet, and
so on. Furthermore, through the menu Sketch > Import Library, we can add to
our program one or more of the many libraries that the Arduino project makes
available to us (to access the EEPROM, the Ethernet controller, the SD, etc.).
The import operation of a library does nothing but add all the directives
(#include) necessary for the use of the classes and functions that the library itself
makes available to us in our source file. It will be the IDE to take charge at the
time of compilation to include in the generated firmware, not only our code but
also that of the libraries used.
Compilation
Also, in the Sketch menu, there is a Check option that allows us to verify the
correctness of the code (obviously from a syntactic point of view and the
references to the functions used) and then fill it in but without immediately
loading it onto the board.
Shortcuts
Finally, in the menu, Modification finds a series of functions strictly linked to
the editor to simply perform the operations of commenting on the code,
searching, copying/pasting, and indenting.
Some of the most common operations are accessible through a series of buttons
located immediately below the menu bar and which respectively indicate:
Inside the driver's archive folder that we downloaded, you can find the two
executable files (dpinst-x86.exee dpinst-amd64.exe), which allow the installation
of the card on a 32 and 64-bit operating system respectively.
Once the installation is complete, the serial ports already available on the PC
with the one just installed and relative to the Arduino board will be visible in the
menu Tools > Serial Port; we obviously have to select the right port to which the
card is connected. To verify which is the right serial port, we can identify all the
ports installed in the system inside the control panel, where we find an Arduino
Uno (COMx) type port, which is nothing more than a virtual serial port
associated with the USB converter - serial on board.
Debugging at Runtime
A very useful IDE feature is the serial port monitor available in the menu item
Tools > Serial Monitor. As we will see, this tool will prove to be very important
for debugging our runtime programs.
Using the serial management library, we will have the possibility to send
messages on it and then view them through the monitor; only in this way could
we "debug" and know at runtime where in the program we are or what one or
more variables assume the value to be. Although it may appear a little
rudimentary, it represents the only solution in this case.
We have acquired all the necessary knowledge, from the board to the IDE, to
start developing an application for Arduino.
Enough said, now let's delve deep into the wonderful world of Arduino with
some exciting projects integrated into the chapters of this book.
Chapter One
Controlling the LED
In this chapter, you will learn how to operate the LED and how to connect to the
Arduino. You will also learn and consolidate the basic concepts of programming
(script, program, algorithm, control, condition, loop). These perform the task of
building an electronic system using the Arduino, the contact plate, LEDs, and
resistors. The task consists of pointing the learners of the new chosen pin,
assigning it in using the command pinMode (no pin, OUTPUT), and make the
LED flash (i.e., lights up for 2 seconds, go out for 1 second and repeat the
cycle).
Warning! This part of the scenario should pursue all classes (and those carried
out by the following scenarios of II. "Create your own robot") to the extent that
is needed until the basic material will be fixed.
Arduino Connection
Arduino is programmed using a computer. So first, we have to connect the
Arduino to your computer using a USB cable. In the language and development
environment, Arduino IDE created programs which then uploads (forward by
cable) to Arduino. When the program is uploaded (it takes a few seconds), it will
be executed without a break (in the loop).
Once connected, you run the Arduino IDE. We check if any computer has
correctly detected the port that is connected to the Arduino (you need to click on
the top menu "Tools" and then "Port"). Sensitization as learners that sometimes
you may experience problems with the detection of Arduino on your computer
and should then check whether the port is active.
Then we run the Arduino IDE. On the Windows platform, you should search for
the program on the Start menu. Ubuntu Linux platform should find a program in
the Ubuntu menu in the upper left corner of the screen.
After the program, we should see a window with white text, graphic elements,
and blue-green thick black stripe at the bottom of the window. At the top of the
window, we see the following menu:
File: here, you can create new projects (New), save it (Save, Save As), open
(Open, Open Recent), and view examples of ready-made programs (Examples).
Edit: edit menu, allowing you to copy and paste text, and other methods modify
it.
Sketch (Draft): menu, allowing you to compile your code, or to translate it into a
language understandable to the computer and upload it to the Arduino.
Tools: menu of tools, among others, we can choose the type of Arduino board
that we have, and a USB port to which the plate is connected to your computer.
Help: Help menu.
First: Verify (Verify) allows you to verify the correctness of the code. The
Arduino check if the code that we wrote is correct, that is, whether it can be
compiled (translated into computer language).
If you select the menu command: File> Examples> 01.Basic> Blink (File>
Examples> 01.Basics> Blink) and you click this button, the black box at the
bottom of the window should display various information written in white font.
This shows that the program can be compiled and sent to the Arduino board.
Second: Upload (Upload) works similarly to the Verify, with the difference that
after the successful compilation immediately sends the code to the Arduino
board when it is properly connected to your computer.
Sixth: located at the end on the right side opens the Serial Monitor (Serial Port
Monitor). This is the window in which we can see what information signals and
sends the Arduino board to your computer and allows us to send signals and
information to the plate. To be able to send and receive signals, we need to plate
in the first program.
Below is the window of our program. Arduino programs are called "sketches."
On the left side is our only tab. In this case, it is a sketch loaded earlier,
Examples, from the menu called Blink (blinking LED module built into the
Arduino).
On the right side is a drop-down icon that allows you to navigate through the
tabs.
Below is the code - the text of our sketch and, below, the window in which the
program Arduino communicates with us, showing errors at compile-time, or
indicate success.
This scenario includes instructions on how to write a program for the Arduino.
We create a new project. From the File menu, choose New command, or click on
the New button in the program interface. See if a new window with the
following:
void setup () {
// put your setup code here, to run once:
} Void loop () {
// put your main code here, to run repeatedly:
}
This is the basic structure of the program, the Arduino. Part of the "setup" is
done only once, at the start of the program, and is made part of the "loop" around
the clock, in the so-called loop. If you have already studied the earlier books of
this series, then you should be familiar with the term "loop". The text that
follows the characters // are comments - here you can enter what you want.
Typically, comments are written as information for the programmer, which
carries a part of the program. Comments must be in the same line as the
characters //.
We write a program that will show us the information in the Serial Monitor.
Then click the Upload button. If errors occur, they should be corrected - the
program should be prescribed very carefully and without errors. Then click the
Serial Monitor button or select the Tools menu> Serial Monitor (Tools> Serial
Port Monitor).
Much more convenient to start with is to use the example programs included
with the Arduino (File> Examples) (File> Examples). The programming
language is learned in much the same way as a foreign language - we learn the
words, syntax, grammar, spelling, etc.
And so "Serial" is a feature. It has its sub-functions, which can perform various
operations, for example. "Println" print line, and "begin" starts communication
with the computer. These sub-functions have their own parameters that type in
parentheses. "Println" must know what exactly is to be printed ( "hello world").
"Begin" must know how often to talk to the computer (in this case - 9600 signals
per second).
The loop program works very fast. For example, the processor plate Arduino
Mega operating frequency is 16 MHz. Hz, or Hertz, is a unit of frequency -
defines one cycle (i.e., one event) per second. MHz is megahertz - that is, one
million hertz. So for the example module, Arduino Mega can operate at a speed
of 16 million events per second.
Warning! The section on getting started with Arduino is present in all classes.
We recommend to repeat it (as necessary) for each class, to the point where you
will be able to perform basic tasks independently.
Getting to Know LED (using diodes, resistors and the contact plate)
We will start with questions referring to the introduction and the previous books
of this series, e.g.:
What is Arduino?
The answer here should fall, that one of the light sources can be used, for
example, LEDs, in TV remote controls, flashlights, etc. At this point, the LEDs
show the Arduino kits available; in addition, you can use flat batteries 3V (e.g.,
CR2032) and place them between the leg diodes, which will make the LED light
up.
It is at this point, ask yourself the question: whether the light will shine in the
same way, if we apply the opposite leg?
Then we explain how the LED works and where we use it. It is worth noting that
LED has legs of different lengths: the longer one is the anode, and the cathode is
shorter. Plus, always attach the resistor to the anode (longer leg); otherwise, the
LED will not light.
In this part of the project, we will use the contact plate (prototype) and install a
simple system, which will be controlled by the Arduino. But at the very
beginning, we demonstrate to you how it works and how to contact plates
connected to the various elements (e.g., Diode, resistors and connecting cables).
NOTE: Learners often have a problem with connecting wires and small
electronic components. It is worth paying special attention and help yourself if
you are in difficulty with it. Most often, the contact plate systems do not work
because their components are connected incorrectly.
We explained that the additional element in our system is a resistor. But we have
not yet explained its role. It connects the system and checks if it works.
Everywhere should be lit up with LED.
At this point, it is possible to divide the lesson into two parts (the next part of the
project will be executed in the next chapter).
Then load both the Arduino already known Blink sample program, which can be
found in the File tab> Examples> 01.Basics> Blink. We observe what is
happening, and you can ask yourself (the LED should blink, as well as the LED
built into the Arduino pin 13).
We explain that using an Arduino controls the digital outputs, in this case, the
LED, but can also control any other electronic device.
Arduino and disconnect the cable hooked to a pin 13 changing to any other
digital pin (you can choose themselves). Let's assume that it will be to pin 6.
Then modify the program in the appropriate places (replace all the places where
it is used to pin 13 6) or to load on the Arduino and see if it works. In this way,
we show you how to assign different pins on the Arduino IDE (you do not have
anything connected to pin 13).
NOTE: Before every change of the contact plate, changing wires, adding new
electronic components disconnect the power from the Arduino (remove the USB
cable AB). Thanks to avoiding accidental short circuits, which can destroy our
Arduino.
Chapter Two
Alarm Siren & Signal Light
In the first part of this chapter, you will build a simple model siren, using the
buzzer (buzzer) and outputs Arduino marked PWM (Pulse Width Modulation,
called. "Pulse Width Modulation"). To know and/or consolidate the basic
concepts of programming (script, program, algorithm, control, condition, loop).
Using the properties of the loop and the PWM regulate the brightness of the
LEDs and buzzer volume. They perform the task: build a siren with the Arduino,
which is an arrangement in which the buzzer to smoothly increase the volume of
the published sound - from silence to a maximum value.
And in the second part, you will learn to build a simple model of traffic lights
using RGB LED that can glow in any color. To know and/or consolidate the
basic concepts of programming (script, program, algorithm, control, condition,
loop). They learn to control LED RGB using the Arduino. They perform the
task: to construct a "system" traffic light with the use of RGB LEDs
programmed by Arduino.
Arduino UNO board and USB cable AB (for each participant or pair
of participants) contact plate,
220-ohm resistors,
connecting cables
Connecting Arduino IDE to run the program and guide to the basic
information
Warning! For information on how to connect the Arduino, run the Arduino IDE
and Scratch for Arduino, as well as basic information needed to get started with
Arduino, contain scenarios 1 and 2. This part of the book should be repeated
every time the extent that is needed until basic material is fixed.
We are starting with a discussion of analog and digital devices; we can ask
questions such as:
Then we explain the difference between digital devices (e.g., computer, mobile
phone) and analog devices (mechanical watch, old radio). We also explain that
by using the digitalWrite () function in Arduino, we can give the pins two states:
high (marked with the number 1 - then the current flows) or low (marked with
the number 0 - the current does not flow).
It is worth paying attention to the markings pins. In the Arduino pins operating
in PWM mode, they are marked with ~.
Now, we can assemble the system shown in the scheme below.
The system is very similar to that used in the scenario of LED, but it is worth
noting that here is the output pin to pin 9 (of course, you can freely select one of
the six PWM pins).
The LED has two legs of different lengths. The longer is the anode, and the
resistor attaches to it.
We compile and load both sketch programs for the Arduino. We ask you how
the LED behaves. Is this the behavior of a digital or analog? (The correct answer
is analog because the LED brightens smoothly on and off). We explain to you
the LED action in this case, and we can refer to the example scenario of LED,
where he steered digitally.
We discuss, in turn, all the elements of the code. We pay attention to the loop
"for" and analogWrite function () contained within this loop. We explain how to
operate loops - here, and we introduce the concept of the "for" loop. It is worth
noting that in the main loop Arduino, there are two loops "for" succession: the
first is responsible for brighter LEDs, and the way her darker. For more
information about the "for" loop can be found in the supplementary materials.
Loop "for" works in this way that the operations contained within the loop, the
program performs a specific number of times for us. In this case, we have three
parameters. The first parameter is a variable fadeValue, which is initialized to 0,
as we begin to clear LED 0. The second parameter is the condition that
determines when the loop will work. In this case, we break the loop when we
reach the maximum value of 255.
The third parameter is the number by which raise or lower the value of the
variable fadeValue with subsequent cycles "for" loop. Here it is expressed with +
=, which represents an increase of 5 each time through the loop (i. Successively:
0, 5, 10, 15, 20, etc.). Symbol - = (second "for" loop) represents a decrease of 5
(ie. The following order: 255, 250, 245, 240, etc.).
Then we give you a task: you need to modify two parameters "for" loop and see
how it affects the behavior of the LEDs. Here is a hint, which parameters can be
changed and what is affected by:
Once again, load a program from the previous point and check how the buzzer
behaves. Ask yourself the question, do you see a difference in the behavior of
the buzzer and LEDs. Or maybe there is no such difference? The buzzer should
behave the same way, or - alternately - quieter and louder sound.
Warning! For information on how to connect the Arduino, run the Arduino IDE
and Scratch for Arduino, as well as basic information needed to get started with
Arduino, contain scenarios 1 and 2. This part of the book should be repeated
every time you need it until the basic material is fixed.
hence comes the name "RGB" - from the names of colors. The LED has four
legs, three of which are responsible for the individual colors, and the fourth is a
common anode or cathode. RGB LEDs are in the two versions, but in this case,
we will discuss RGB LEDs common cathode.
Using the PWM connectors and analogWrite function (), we can control the
brightness of each channel. By setting different voltages on all three channels
can be freely mixed color components, thus obtaining a full RGB color palette.
You know what types of displays and/or screens? Where are they
used? In what devices?
How does the display?
What is a pixel?
What happens when you mix different colors, for example. Poster
paints?
In this section together to connect RGB LED Arduino according to the following
scheme:
Note: for each leg, a diode corresponding to a given color of a resistor connected
in series (maybe 330 ohms). As previously mentioned, LED RGB is constructed
from three smaller diodes and each of which controls independently. However,
this LED RGB is a common cathode and thus needs only one connected to the
wire in our Arduino minus (GND pin). It should help you with pinning because
there may be problems with the distribution of feet RGB LEDs and plugging the
holes in the contact plate.
After checking all the connections on the Arduino or to load the following
program (https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-an-
rgb-led-89bcae)
void setup() {
pinMode(PIN_LED_R, OUTPUT);
pinMode(PIN_LED_G, OUTPUT);
pinMode(PIN_LED_B, OUTPUT);
displayColor(COLOR_BLACK);
void loop() {
displayColor(COLOR_RED);
delay(1000);
displayColor(COLOR_GREEN);
delay(1000);
displayColor(COLOR_BLUE);
delay(1000);
displayColor(COLOR_MAGENTA);
delay(1000);
displayColor(COLOR_CYAN);
delay(1000);
displayColor(COLOR_YELLOW);
delay(1000);
displayColor(COLOR_WHITE);
delay(1000);
displayColor(COLOR_BLACK);
delay(1000);
Now we need to enter the code manually or prepare it in advance and distribute
it on our computers. After downloading the program, we observe how light
behaves. Then, we analyze the program code. We explain that each pin is
responsible for a different color. We show, at which point, where to turn on and
turn off the individual channels (where it is excessively high or low). We give
you the task to decode and place the code that is responsible for a particular
color displayed by the RGB LED. This makes it much easier to understand the
operation code and the entire system.
Now we need to write a new program that allows simple adjust the brightness of
each channel. It is worth noting that the command digitalWrite () to change the
analogWrite ()because otherwise, we will not be able to assign analog values in
the range 0-255. Below is a sample program:
(https://www.programmingelectronics.com/tutorial-10-fade-an-led-with-pulse-
width-modulation-using-analogwrite/)
/*
Fade
*/
void setup() {
pinMode(led, OUTPUT);
void loop() {
fadeAmount = -fadeAmount ;
delay(30);
Now briefly review the program code and try to see where you can
independently change the parameters and the same color mix.
Try to create a simple traffic light simulator. RGB LED light should be the same
as the beam in the following sequence: light green, yellow, red, red, yellow,
green.
- 2 s
All in including the main loop and thus obtain a continuous operating traffic
light. RGB LED built into the system should be lit in different colors in the
following sequence: light green, yellow, red, red, yellow, green.
Chapter Three
MDF Robotic Arm Kit & Recording of Micro
SD Card with Arduino
In the first part of this chapter, we are going to talk about the MDF Robotic Arm
Kit. This kit consists of all the parts necessary to assemble a genuine robotic
arm, with two control axes and a claw. All movements are controlled by four
servo motors, which are not included in the kit. Servants are responsible for
controlling the movements of the arm on its different axes and the claw.
It is the ideal product for makers, electronics lovers, and anyone who wants to
assemble and have their own robotic arm. All pieces are laser cut, based on MDF
boards. It was thought to be used in projects with Arduino, Pic, ESP, and other
microcontrollers. We will show you how to program the Arduino to control the
arm satisfactorily.
The parts are all laser cut, and the screws, nuts, and other assembly components
(except the servos) are all included in the kit. Anyone can assemble it. Just
follow the instruction manual carefully from the manufacturer.
The Figure above shows the robotic arm assembled with the four servos to
control its joints. The figure just below shows the set of parts that make up the
kit. The parts must be carefully assembled for the arm to work properly.
It is common for projects where servomotors are used that they are connected
directly to the Arduino. In this case, there are four servos, so it is necessary to
have an external power supply, as the Arduino is not able to supply all the power
for the set of 4 motors. We will use a protoboard source in our project, as will be
explained later.
Applications
The applications of this robotic arm in MDF are mainly:
Project Description
In this project, we will assemble the Robotic Arm kit in MDF and program an
Arduino UNO with a Sensor Shield V5.0 to control the four-arm servos. As the
Arduino on the USB does not supply power to all servos, we will use an external
9V source to power the servo drives. With Arduino, we will use the application
developed here on the book as a base software to control a robotic claw. The
robotic claw of this other project is different from that used in the robotic arm.
Made of acrylic and sold only as a claw (without larger components like the
mechanical arm), the claw is applied to hold and release objects and can be
affixed to different surfaces.
This base software uses a potentiometer to read the signal commanded by the
user, and in proportion to that signal modulates the PWM output applied to the
servomotor. In our project with the mechanical arm, as there are four servos, we
will expand this project to read four potentiometers, each one to activate one of
the servos of the mechanical arm.
Hardware Needed
For our assembly, we will need the following components:
1 Arduino Uno R3 + USB Cable
1 Shield V5 sensor for Arduino;
1 9V/1A source to power the Arduino;
4 9g Tower Pro Micro Servos;
4 10k potentiometers;
1 Robotic arm kit in MDF for Arduino;
1 Protoboard 400 points
Jumpers - Male/Female
With the manual available in the introductory part, there is not much secret of
assembling the project, just follow the instructions in the assembly manual
carefully. With the arm ready to be connected, we have to mount the Arduino to
control the servos. See the figure below:
Software
Our software must read four potentiometers, each one to control a servomotor.
Thus, in our firmware, we must use four analog channels to read and four PWM
channels, each for a different servo motor. Since there are many control signals
connected to the same circuit, the servos may be unstable due to noise.
Especially if the whole assembly is done on a protoboard instead of the sensor
shield. Make sure that Sensor Shield is powering the protoboard by 5V and
GND, as well as the VCC and GND of power for each pot.
In the code below, we have the definition of the reading pins, each for a
potentiometer, and the declaration of four Servo type objects. To declare objects
of the Servo class, it is necessary to include the Servo.h library.
(https://www.arduino.cc/en/reference/servo)
#define potpin1 2
#define potpin2 3
#define potpin3 4
#define potpin4 5
#include < Servant .h>
MyservoBase Servant; // Servo object to control the base
Servo myservoGarra; // Servo object to control the claw
Servo myservoAltura; // Servo object to control arm height
Servo myservoPr Depth; // Servo object for depth at arm's height
int val; // variable to read the value from the analog pin
void setup ()
{
// Associates each object with a myswebase
pwm pin . attach (3);
myservoClaw. attach (5);
myservoHeight. attach (9);
myservo Depth. attach (11);
}
void loop ()
{
val = map ( analogRead (potpin1), 0, 1023, 0, 180);
myservoBase. write (val);
val = map ( analogRead (potpin2), 0, 1023, 0, 180);
myservoClaw. write (val);
val = map ( analogRead (potpin3), 0, 1023, 0, 180);
myservoHeight. write (val);
val = map ( analogRead (potpin4), 0, 1023, 0, 180);
myservo Depth. write (val);
delay (100);
}
In the void loop function, we will always update the values read from the
potentiometers and use them as a reference to set the position of each servo.
Thus, any control mode on the knob of one of the four potentiometers will be
converted into a change of position on one of the four servos. In this way, we
can separately control the base of the arm, as well as the joints (height and depth
of the arm) and the opening and closing of the claw.
Notice how we read each analog pin directly into the map () function, passing
the result of the reading as an argument to the map () function.
With the MDF Robotic Arm kit and four TowerPro SG90 micro servos, you can
implement a robotic arm of your own. A practical aspect of the assembly is the
noise that the assembly on the protoboard and possible badly attached contacts
can cause. Leave all connections firmly and check that all components are well
referenced to the GND.
A practical tip when assembling the arm following the manufacturer's manual:
None of the screws should be tightened too much. As it is a set of moving parts,
you must use the screws only to join the parts, applying the minimum amount of
force necessary. The same goes for the screws used to secure the servo motor
“horns.” When these screws are too tight, it can happen that the servo's rotation
may even stop. Therefore, on all screws, use as little force as possible, just
enough to keep the parts fixed.
In this second and final part of the chapter, we are going to learn how to write
data and read information using a Micro SD card with Arduino. Several SD card
shields are available on the market to connect these handy memory cards to the
Arduino. In this section, we will use the Micro SD Card Adapter connected to an
Arduino Uno.
The micro SD card with Arduino allows the development of data loggers.
Devices that store data collected from sensors and other information for analysis
and graphing.
The figure below shows the SD card adapter that we are going to use in our
project. There are also specific datalogger shields integrated with RTC (Real
Time Clock) for telemetry and sensor monitoring applications.
The module is efficient and compact. In addition to being practical to use and
integrate with hardware and control systems, it was developed to optimize the
work of designers, students, and hobbyists in the construction of data logger and
data storage systems.
Basically, the module has an entry for Micro SD cards with all six interface pins
available for communication with Arduino. Through the SPI pins
(communication protocol used to read and write data in the card's Flash
memory), we can turn on the Arduino and send information to be stored. It is
also possible to perform reading procedures to present the data recorded on
displays as displays or on the serial interface.
The SPI interface that allows you to read and write data to Flash memory is
based on six channels:
Applications
The applications of dataloggers are diverse. Any system in which it is necessary
to store data for future analysis are candidates to have received the integration of
a datalogger. Among the applications, we can mention:
Telemetry and monitoring of drones;
Telemetry and monitoring of vehicle prototypes;
Monitoring of sensors and machines for predictive and preventive
maintenance;
Monitoring of energy consumption;
Any other system that requires a data logger;
Project Description
For this project, we will develop the following:
Hardware Aspects
From a hardware point of view, we will need the following materials:
Protoboard;
Ultrasonic Sensor HC-SR04 ;
Arduino UNO;
PIR motion and presence sensor ;
3 3K3 resistors;
3 2k2 resistors;
Jumpers for connection;
The important point is that although 5V powers the adapter module, the MISO,
MOSI, and SCK signals are 3.3V. In other words, it is necessary to use a CI to
convert the logic levels or use three voltage dividers to lower the Arduino's 5V
signals to 3.3V on the SD card side. The solution with voltage dividers, as it is
simpler and more practical, will be the one adopted in our project.
Having said that and having all the components, we can assemble the circuit as
shown in the figure below:
If you still do not know the operation and implementation of projects with
ultrasonic sensors, visit this exclusive post and learn all about the HC-SR04
sensor and how to do projects with it.
Software Aspects
Let's understand the software developed that makes the recording on the card.
See the code below:
SPI.h
SD.h
STDLIB.h
The first two are to record the SD card. The last one is so that we can use the
dtostr () function, which converts a float to a string. To record the card, we
declare an array of characters and an object of type FILE, which we call
myArchive.
The other variables are related to the ultrasonic sensor and the IO settings. To
know the functions and how the part of the software related to the ultrasonic
sensor works, access this article. (https://lastminuteengineers.com/arduino-sr04-
ultrasonic-sensor-tutorial/)
In the void Setup () function, we initialize the serial port and the SD card using
the SD.begin (CS) function, where CS is the pin on which the ChipSelect signal
of the card is connected.
Putting it to Work!
See how the final result should look like:
Complete Assembly 2
Complete Assembly 1:
Log.txt file:
Serial output:
In this example, we made a simple data logger to monitor the signals from an
ultrasonic sensor. All sensor readings, which were taken at a rate of 2 seconds,
are recorded on the micro SD card using the SPI protocol. The adapter can be
easily integrated into any electronic system. The micro SD card can be easily
removed and taken anywhere else so that the data can be used to plot graphs and
build tables.
Chapter Four
Home Automation: Presence Sensor &
Automation of Irrigation System with
Arduino
In the first section of this chapter, we will assemble a typical home automation
system. We will use a PIR presence sensor to turn a lamp on and off. The sensor
is connected to an Arduino and triggers a signal indicating the presence of
someone within a certain radius. Reading the signal from the sensor, we will
know if someone is nearby and turn on a lamp by activating a relay module.
The operation of the sensor is extremely simple. If an object enters the detection
range, an output is activated at a high level, and if there is no movement detected
within the range, the output is at a low level. In the summer, the detection range
may be slightly less due to the higher temperatures. The datasheet provides this
and some other additional information. We strongly recommend that you know
the component's datasheet.
The pyroelectric sensor captures infrared radiation through a fresnel lens, which
divides the sensitive area of the sensor into sectors with lenses of different
characteristics. The PIR sensors are stimulated only by some energy sources,
such as human and animal heat, for example. A passive sensor is said because it
does not emit any signal; it only receives the radiation and is stimulated by it.
Dyp-me003 Specifications
The elecfreak model dyp-me003 is simple and small. It is very easy to use and
very flexible for prototyping projects and residential assemblies. The sensor
module has a small yellow potentiometer to adjust the waiting time for
stabilization and also to adjust its sensitivity. Stabilization can vary between 5 to
200 seconds.
Applications
The PIR sensor is ideal for home, commercial, and security automation projects.
It is widely used in:
Security products;
Devices with presence detection;
Automatic lighting;
Automatic activation of buzzers, lamps, and home and commercial
automation circuits;
Automation and industrial control;
Project Description
In our project, we are going to use the ElecFreak PIR sensor to drive a lamp
through a relay module. To learn more about the relay module, you can access
all other resources of the references in this book. The project consists of the
following:
Hardware Aspects
To assemble this project, we will need the following components:
Sensor DYP-ME003;
Protoboard;
Arduino Uno;
The assembly below shows how the circuit should be made. The relay module
does not require the use of transistors to amplify the Arduino signal to activate
the lamp. The relay module must be connected with the common pin on one of
the socket terminals, and the NA pin on one of the lamp terminals. The other
terminal of the lamp must be connected to the other terminal of the socket.
Software Aspects
The software consists of constant monitoring of the PIR sensor to find out if the
sensor has identified any infrared variation (movement of people or animations).
We declare the variables to determine the reading pins (PIR sensor output) and
output pins (activates the Relay module), and in the void loop () function we
read the PIR sensor output signal, which is digital, that is is, or is it high level or
low level.
#define Relaymodule 7
#define ThesensorPIR 8
int ReadingSensor;
void setup ()
{
pinMode ( trigger it , OUTPUT );
pinMode (LesensorPIR, INPUT );
Serial . begin (9600);
}
void loop ()
{
//
Read the presence sensor ReadingSensor = digitalRead
(LesensorPIR);
// No
if motion detection (ReadingSensor == LOW )
{
digitalWrite (trigger, LOW );
}
// There is movement detected - turn on lamp
else
{
digitalWrite (trigger it, HIGH );
}
delay (2000);
}
We use a delay in the loop function and depending on the setting time you use it
will be necessary to change this time
Putting it to Work!
Let's see how the assembly is ready! The figure below shows the entire circuit
connected and assembled to light the lamp.
With this section, you now know how PIR presence sensors work and how to
integrate them into any home automation project or any other application you
want. The sensor is simple to use and is sold in the United States.
Now in this second and final section of this chapter, we are going to talk about a
subject that interests a lot of people: Irrigation systems. From small gardens to
larger sites and areas, knowing how to automate your own irrigation system
gives you flexibility and allows you to make customized solutions for your
needs. For these systems, it is necessary to measure mainly soil moisture and
temperature. As an actuator to release water to the pivots, a valve is required.
And, of course, a microprocessor system to read the sensors and control the
valve according to the soil moisture and temperature levels
The soil sensor is a probe that measures the humidity level of the earth. With it,
you can know when it is necessary to turn on irrigation to regulate soil moisture.
The solenoid valve is the actuator component of the system. We use a 12V
signal to open and close the valve, allowing water to flow or blocking it.
The working principle is simple. The module has two rods with two long
contacts. It is a sensor whose electrical resistance varies according to the
humidity of the soil. Thus, the wetter the soil, the lower the resistance of the
sensor. The drier, the greater the resistance of the sensor.
With the digital output (D0), the basic operation is as follows: When the
humidity is low (dry soil), the output is at a high level. Otherwise (wet soil), the
outlet is at a low level. A small potentiometer embedded in the sensor is used to
adjust the reference limits. The comparator circuit can be seen in the image
below:
Ground Sensor Module Specifications
The humidity sensor specifications are:
Comparator LM393;
Pinout:
GND;
VCC;
Solenoid Valve
The Solenoid valve is used to control the flow of water. When powered with
12V DC, it opens and allows water to flow. When de-energized, it closes and
cuts off the flow. Its operation is based on a coil (solenoid), which, when
energized, generates an electromagnetic field responsible for moving the valve
plunger.
Specifications:
The valve is small and simple, ideal for use in gardens and small irrigation
systems. Together with the soil sensor module, it is a piece of ideal equipment
for hobbyists and makers.
Applications
The humidity sensor and valve applications are mainly for water flow control
systems, such as:
Hardware Aspects
For our assembly, we will need the following components:
Solenoid Valve;
Arduino Uno;
External 12 V DC source;
5V Relay Module;
The relay module is used to activate the solenoid valve because, in addition to
the Arduino operating at 5V, it does not have enough power to supply the valve.
If you still don't know how to use the relay module, access this post on relay
modules and lamp drives with Arduino. The assembly is shown below:
Software Aspects
Let's see how the software works to monitor the sensor and activate the solenoid
valve.
We define the pins that we will use for reading and activate the relay with three
directives at the beginning of the code. In the void setup function, we only
initialize the serial port so that we can communicate and configure the inputs and
outputs. The main part is in the void loop () function. Here we are going to read
the two outputs from the humidity sensor. The analog output is read with the
analogRead function (Analog pin), and the digital output of the sensor is read
with the digitalRead function (Digital pin).
We present the reading data on the screen and then make the comparison to see
if we should close or open the valve. If the humidity sensor is at a high level, it
means that the soil is dry, so we have to activate the relay to open the valve. The
relay is then activated by sending a GND signal. If the sensor output signal is
low, it means that the soil is moist enough, and we don't need to open the valve
anymore. So, we send a high-level signal to the relay to turn the relay off and de-
energize the valve.
#define pinDigital 13
#define pinAnalog 0
#define pinRelay 7
float AnalogOutput = 0;
float voltage = 0;
int ReadingSensor = 0;
// the setup routine runs once when you press reset:
void setup () {
pinMode (pinDigital, INPUT );
pinMode (pinRelay, OUTPUT );
Serial . begin (9600);
}
// the loop routine runs over and over again forever:
void loop () {
AnalogOutput = analogRead (pinAnalog);
ReadingSensor = digitalRead (pinDigital);
float voltage = AnalogOutput * (5.0/1023.0);
Serial . println ( "Sainda analog" );
Serial . println (voltage);
Serial . println ( "Digital Sainda" );
Serial . println (ReadingSensor);
if (ReadingSensor == HIGH )
digitalWrite (pinRelay, LOW );
else
digitalWrite (pinRelay, HIGH );
delay (2000);
}
Note that we connect the relay to the valve using the COMMON and NA pins,
that is, we use the normally open contacts. If you use normally closed contacts,
your logic will be slightly different. To rectify how to use the relay module,
check our post where we explain this component better.
Putting it to Work!
Complete Assembly:
The output on the serial interface presents the following information:
Note that at the output of the serial interface above, we are reading a value of 5
mV, which means that the soil is dry, with virtually no moisture. Because of this,
the digital output is at a high level, as shown on the same interface.
With this simple assembly, you can assemble an automated irrigation system
with your own hands. You can adapt the wire sizes to make a better system for
your plants or gardens. You can also use more than one soil sensor to be able to
take readings from various points, obtaining a more accurate map of humidity
over a larger area.
Chapter Five
Flammable Gas Sensor & RFID Kit with
Arduino
In this first part, we will learn how to use a sensor to assemble a system to
identify fire spots and flammable gases. For this, we will use an MQ 2 sensor,
which identifies gases such as methane, natural gas, hydrogen, smoke, among
others. We can use this sensor to validate air monitoring systems, as well as
prototype systems for checking air quality and the presence of hazardous gases.
The module also has an analog output (A0), which allows measuring the
variation in the concentration of gases in the air more accurately. To use the
analog output, you need an AD converter, like the one Arduino makes available
on its analog channels.
Despite being easy and practical to use, the sensor is not suitable for use in real
fire safety systems. The manufacturer recommends it for experimental purposes
and product validation. The author and the publisher are not responsible for any
damage caused by their use. If you want to develop a real security system
against fire or dangerous gases, we recommend researching and using industrial
and more robust sensors.
Specifications
The sensor specifications are as follows:
Detection of flammable gases: LPG, Methane, Propane, Butane,
Hydrogen, Alcohol, Natural Gas and others;
Smoke detection;
Concentration levels for detection: 300-10,000 ppm;
Operating voltage: 5V;
Comparator LM393;
Led indicator for voltage;
Led indicator for digital output;
The module has four pins. There are two for power supply (VCC and GND) and
two output signals, one digital and one analog:
VDC: 5V;
GND: Land/Reference;
Applications
According to the datasheet, the MQ 2 sensor can be used in the following
applications:
Validation of domestic gas leak identification systems;
Development and validation of flammable gas detectors;
Development and validation of portable flammable gas detectors;
Prototyping of fire protection systems;
Project Description
In this project, we will see the following:
An interesting point is the following. There are several sensors in the MQ series.
For example, MQ-3, which detects alcohol, MQ-7, which detects carbon
monoxide, MQ-4, which detects methane gas, and several other models for
specific types of gases. All of them have similar pinouts (VCC, GND, Analog
Output, and Digital Output). Thus, the circuit you know here is extensive for all
these other sensors. Just be careful to confirm the pinout.
Hardware Aspects
Let's start with the list of components we are going to use. Are they:
Arduino UNO + USB cable;
Gas sensor MQ-2;
5V active buzzer;
16 × 2 LCD;
10k potentiometer;
Jumpers for connection in protoboard;
Protoboard;
With these components, we can assemble the circuit below. Note that we used
the MQ-3 to assemble the circuit, which does not change the design because, as
we said, it applies to the entire series of sensors.
Software Aspects
With the assembly ready, we can load the software below. If you follow the
work here on with the books of this series, then nothing in the program will be
new to you. The LCD we present and talk about its technology in this post. The
MQ-2 sensor follows a scheme very similar to several other sensors used with
Arduino, such as the humidity sensor and the various other models of the MQ
family.
Basically, the firmware does the following: It declares the directives are
associating strings to the pins that will be used. Configures I/Os, LCD, and serial
port. In the void loop () function, the two outputs of the MQ-2 sensor are
constantly read to assess whether any gas has been detected.
Putting it to Work!
Most of the wires used for the connection are for the LCD. The interface with
the sensor and the Buzzer take only a few wires. See how the system looks!
We hope that you will now be able to incorporate not only the MQ-2 but any
other sensor in the MQ family. These sensors can detect a wide variety of gases
and are easy and practical to be introduced in projects with Arduino and small
microprocessor systems.
Now, in this final and second part of this chapter, we will see how to build an
access control system using an RFID Kit with Arduino!
RFID cards are used in many applications in everyday life, from credit cards to
automatic identification cards for access control.
These cards have a magnetic stripe that stores digital data and can be read and
written using radio waves.
AIDC methods automatically identify objects and people, collect data about
them, and enter that data directly into the software with little or no human
intervention.
In this section, I will teach you how to build an access control system using an
RFID Kit with Arduino. So, Check out next!
It is a chip with extremely low consumption and small dimensions. Its main
application is the reading of cards that use the Mifare standard.
With the kit, it is possible to develop and validate designs of access control
systems, security systems, and other variations.
RFID tags can be used to read various information about the cardholder,
allowing their automatic identification to validate or not access.
MFRC522 Specifications
Working current: 13-26mA/DC 3.3V;
Peak current: <30mA;
Operating frequency: 13.56MHz;
Supported card types: Mifare1 S50, S70 Mifare1, Mifare UltraLight,
Mifare Pro, Mifare Desfire;
SPI Interface Parameter;
Transfer rate: 10 Mbit/s;
RFID reader: The reader converts the radio waves transmitted by the
tag's antenna to a format that can be used internally on the
computer;
RFID kits, like the one used in this assembly, come with all of these
components. The RFID tag and antenna are integrated into the card or in a
keychain type tag.
The reader module is also part of the kit, and it is through it that data is
written/read. In our case, the reader is based on CI MFRC522.
When the card approaches the reader module, the antenna transmits the data at
the operating frequency (13.56MHz) to the reader, which receives the data and
converts it to a format that can be processed by the IC and manipulated by an
external MCU (Arduino, Raspberry or any other system).
Access control;
Make software with Arduino to identify the card tag and present a
message on an LCD of "Access Released" for the saved tag, or
"Access Denied," for any other tag.
A buzzer will also be inserted in the circuit to warn and will emit
beeps for each situation.
Hardware Aspects
We will need the following materials to assemble the circuit:
RFID KIT;
16 × 2 LCD;
10KΩ potentiometer;
Active buzzer;
Protoboard;
Protoboard jumpers;
SDA -> 9
MOSI -> 11
SCK -> 13
RST -> 8
MISO -> 12
Remember to connect the RFID-RC522 Vcc to the 3.3V! The RFID circuit
works with the 3.3V voltage, not the Arduino traditional 5V.
Hence the need to use the bidirectional level shifter between one and the other.
Some channels are unidirectional, but since you are already going to use a level
shifter circuit, we recommend that you buy a fully bidirectional one, as indicated
in the component list.
The LCD connections are well explained in the code below. Each pin on the
LCD is associated with a macro through which we define the connection pin
with the Arduino.
Software Aspects
The software to load on the Arduino is as the below one:
LCD;
Serial port;
mfrc522;
Input and output pins;
In addition, we have already called the StandardMessage () function to display a
standard message on the LCD.
In the Void Loop () function, we have two if's that are present in all examples of
programs in the MFRC522 .h library.
(https://www.arduinolibraries.info/libraries/mfrc522)
In these two if's, specific library functions are called to search for a card in the
vicinity of the reader, and select/read that card if present.
After this first step, we call the getUID () function, in which we separate the
identification bytes of the card reader into a string named UID. In addition, we
present this UID on the serial port.
If you still do not know the UID of your card, the first time you run the program,
whenever you bring the card close to the reader, the access denied message will
appear, because the UID that is in the program (22 C9 0A 10) is from the card
we used to prepare the post.
Just open the serial terminal and bring the card closer to the reader, so the UID
of your card will be displayed on the serial terminal, and you can replace the flag
CardReleased in the program with your UID.
After loading the program with the updated flag, the message displayed for your
card will be “Access Cleared.”
With the UID of the card read, we do an if-else to find out if this UID is the
same as the one saved in the program (in the flag CardReleased).
If it is the same, the program displays the message “Access cleared” and triggers
two beeps with the buzzer. If it is any other card, the message “Access Denied”
is shown, and we trigger four beeps with the Buzzer.
Auxiliary Functions
We have three auxiliary functions, they are;
StandardMessage ();
getUID ();
The assembly may be a little fuller than normal, due to the wires to connect the
RF522 to the level shifters and theirs to the Arduino.
We hope you will see something like the one shown below:
Before closing this chapter, we recommend reading the examples available in the
MFRC522 .h library.
When you download the file and extract it to your computer, a folder called
“examples” can be accessed. In it are several examples of programs with RFID
applications with Arduino.
Using the sample codes, you can create your own applications and learn much
more about this technology.
Chapter Six
Current + Energy Meter & Audio Module
WTV020-SD with Arduino
In the first section of this chapter, we will assemble an AC power meter
(alternating current) using the Arduino UNO. Energy meters are part of the daily
life of any residence, building, or business. Several models of traditional
companies such as Clamper and EDMI are available on the market with varying
price ranges.
The key components of the meter are the current and voltage sensors, and the
technology/measurement specifications will dictate the final project price; we
will use a 100A non-invasive AC sensor SCT-013.
If the electrical power is constant, just multiply the power by the consumption
time. Thus, a 100W lamp on for 2 hours will consume 200 Wh (watt-hour). If a
function gives the electrical power, say p (t), the energy is calculated by making
the integral of p (t) in the measurement period.
In the case we are going to see, we will measure the instantaneous power from
the current sensor. The energy will be calculated using a summation (which in
practice is what an integral does). So, let's consider a 1-second integration step.
For each step, we will measure the electrical power and find the energy
corresponding to that interval and add all these values into a variable, which will
be shown on the LCD.
We will present in an LCD the values of current and energy calculated from the
moment the Arduino is powered.
Always remembering that when we talk about current, we are talking about the
RMS values, that is, the peak current measured by the sensor is higher, around
142 A, which corresponds to the RMS value multiplied by 1.4142 (square root
of two). Consult your AC circuit book to review these concepts, if necessary.
The sensor has an opening through which the wire with the current to be
measured must be passed (in a house, it would be either the phase or the neutral).
This wire acts as the primary of the transformer, generating a proportional
current in the secondary, according to the transformation rate of the circuit.
An important difference is that this sensor has a current output signal and not a
voltage signal. Thus, an additional circuit is needed at the output to convert the
output current into a voltage that can be read by the Arduino (we'll talk more
about that below).
Specifications
Input current: 0-100A;
Applications
Energy meters are used in any project where it is necessary to monitor the
energy consumption of installation or circuit. The current sensor 100A SCT-013
can be used, for example:
Lighting systems;
Project Description
This project consists of the following:
Use a current sensor and present on the computer screen the values of current
and energy consumed since the measurement circuit was switched on until that
moment.
Hardware Aspects
An additional circuit that we will use to convert the current to a voltage value
that can be read by the Arduino is explained in this reference. Basically, first, we
need to know what is the relationship between the input and the output. For this,
we only divide the input current by the transformation ratio. In our case,
100/0.05 = 2000. Thus, we know that the measured current is the output current
multiplied by 2000.
To be able to read the output signal, we have to convert the output current to a
voltage within the measurement range of the Arduino. For this, we will use a
load resistor in conjunction with a circuit. Here is a detail, the current is
alternating; that is, it has positive and negative cycles. Since the Arduino does
not read negative voltages, we must also ensure that the voltage is always
positive.
We must also know the peak current to which the load resistor will be subjected.
Knowing that the maximum RMS output current is 0.05A, the peak current is
0.0707 A. Thus, the load resistor we are going to use is:
The closest commercial value is 33Ω. This will be our load resistor.
At peak values, the instantaneous power dissipated by the resistor will be 2.5 *
0.0707 = 0.177 W. Knowing this value is important to purchase a resistor that is
capable of withstanding the power that will be dissipated. With these values, the
voltage in the resistor will vary from 2.33V at the positive peak (33 * 0.0707)
and -2.33V at the negative peak (33 * -0.05). And the voltage on the Arduino pin
will vary from 2.5-2.33 = 0.17V to 2.5 + 2.33 = 4.83V. That is, we guarantee
that the alternating sinusoidal current is converted into a sinusoidal voltage that
varies in the measurement range of the Arduino.
All of these values are suggested by an open energy monitor, which has
developed a library that calculates the measured current value from this voltage
signal that we just built.
Where 2000 is the transformation ratio (from 100 A to 50mA, the current is
divided by 2000), and 33 is the value of our load resistor, calculated just above.
So, we are ready to use the function in our program.
Note that this is a “huge sensor,” capable of measuring up to 100A. The output
current is very small, 50 mA. This means smaller currents, like 1 A, for example,
resulted in extremely small voltage variations at the Arduino port. If we have a
current of 1A for example, the current on the secondary of the CT will be 50mA
divided by 100, that is, 0.5mA. In the load resistor, this current generates a
voltage drop of 16.5mV, very difficult to measure, and extremely vulnerable to
circuit and external noise. Thus, the SCT-103 100A is particularly suitable for
larger loads.
If you want to validate a bench design or a small power load, for example, we
recommend using an SCT with a different transformation ratio. For example,
SCT-013-020, which transforms currents up to 20A into voltages of 1V.
Important Tips:
The SCT-030 100A sensors come with the built-in Burden resistor. I
measured the value of 38 ohms. Measure the value of your sensor as
well. If you already have the Burden resistor, it is not necessary to
insert the 33-ohm resistor into the circuit. But in this way, the
calibration factor (I_calibration) must be changed to the value of 30.
List of Components
The necessary components for the project are:
Arduino Uno;
Current sensor 100A SCT-013;
33R resistor and at least 1/4 W;
2 100K resistors;
1 capacitor of 10uF;
Circuit
An additional component that could be added to the circuit is a voltage amplifier
between the voltage divider and the load resistor. When using high-value
resistors, the load effect decreases, but ideally, to decouple the two circuits
(voltage divider and load resistor), it is recommended to use an op-amp in the
voltage follower configuration or an additional optocoupler.
Software Aspects
Putting it to Work!
Note: The wire that must be inserted in the sensor is only one and in no way
should we pass the two wires of the load supply through the sensor, because with
the current circulating in opposite directions in each wire, the magnetic fields
associated with each wire are canceled and not provide adequate excitation of
the magnetic core of the CT.
Final assembly:
Now in this second and final part of the chapter, we will learn how to use the
WTV020-SD audio module. With it, you can incorporate audio elements in your
projects with Arduino, such as voice messages, music, customized alarms, and
many others. With this brief introduction, you will be able to use the WTV020-
SD module easily and practically in your projects.
With the module, it is possible to use files in WAV and AD4 (compressed audio)
formats that are in accordance with FAT formatting. WAV format files can have
a sample rate of 6KHz to 16Hz. The files in the AD4 format have a sampling
frequency of 6KHz to 36KHz. For more information on the AD4 format, visit
this article. (https://www.filedesc.com/en/file/ad4)
In Audio Mode, push-buttons are used to activate the module's pins and perform
the same music playback functions mentioned above. The other two modes are
the least used, as they relate to less common situations.
Applications
The WTV020-SD Module can be used in several applications, such as:
Car alarms;
Voice messages;
Music player;
Parking Sensor;
Smart home and medical instruments.
Any project where the incorporation of audio elements is important is a strong
candidate for the WTV020-SD module.
Project Description
The example project consists of the following:
Prepare and save two files on the SD card of the WTV020-SD module, one in
WAV format, and the other in Ad4 display a menu on the serial interface to
choose which file to play and for how long.
Hardware Aspects
The list of components for this project is as follows:
WTV020-SD module;
Arduino UNO;
Protoboard;
Speaker for Arduino;
A very lean list with components available on the market.
The pinout of the WTV020-SD module can be seen in the table below, taken
from the original datasheet. For this project, we will use the power pins (3.3V
and GND) and four other communication pins.
Software Aspects
To control the module, we will use the WTV020sd library. The library was made
available in the Arduino Community. Before recording the program and running
its audio files, it is necessary to format the SD card with the FAT file system and
also save a file in the AD4 format and one in the Wav format.
/*
Example: Control a WTV020-SD-16P module to play voices from an
Arduino board.
Created by XYZ, August 16th, 2019.
Released into the public domain.
*/
#include <Wtv020sd16p.h>
int resetPin = 2; // The pin number of the reset pin.
int clockPin = 3; // The pin number of the clock pin.
int dataPin = 4; // The pin number of the data pin.
int busyPin = 5; // The pin number of the busy pin.
/*
Create an instance of the Wtv020sd16p class.
1st parameter: Reset pin number.
2nd parameter: Clock pin number.
3rd parameter: Data pin number.
4th parameter: Busy pin number.
*/
Wtv020sd16p wtv020sd16p(resetPin,clockPin,dataPin,busyPin);
void setup() {
//Initializes the module.
wtv020sd16p.reset();
}
void loop() {
//Plays synchronously an audio file. Busy pin is used for this method.
wtv020sd16p.playVoice(0);
//Plays asynchronously an audio file.
wtv020sd16p.asyncPlayVoice(1);
//Plays audio file number 1 during 2 seconds.
delay(5000);
//Pauses audio file number 1 during 2 seconds.
wtv020sd16p.pauseVoice();
delay(5000);
//Resumes audio file number 1 during 2 seconds.
wtv020sd16p.pauseVoice();
delay(5000);
//Stops current audio file playing.
wtv020sd16p.stopVoice();
//Plays synchronously an audio file. Busy pin is used for this method.
wtv020sd16p.asyncPlayVoice(2);
delay(2000);
//Mutes audio file number 2 during 2 seconds.
wtv020sd16p.mute();
delay(2000);
//Unmutes audio file number 2 during 2 seconds.
wtv020sd16p.unmute();
delay(2000);
//Stops current audio file playing.
wtv020sd16p.stopVoice();
}
Basically, we have a loop in which we give the option for the user to choose one
of the two ad4 files to play. We created the TocaAudio function that executes the
commands to play the selected audio for 5 seconds. Two important observations
we have are as follows:
Finally, a small hardware detail. The module has three solder points,
located at the top and with two markings, one written 5V, and the
other 3.3V. Some modules already come with these soldered points,
but you may have to solder them, connecting the middle point to the
3.3V point, as in the figure below:
We will close the chapter with the saying that we believe strongly now you are
ready to use the WTV020-SD in your electronic projects.
Chapter Seven
KY039 Heart Rate Meter & Audio Recording
and Playback with Arduino
In this first section, we will learn how to use the heart rate sensor and set up a
circuit with a datalogger to store historical heart rate series. The datalogger was
the subject of this post, and in the following text, we will focus on the sensor and
heart rate measurement.
The KY-039 sensor is not the most accurate and stable on the market. It can be
challenging to mount a meter with it that is reliable. In this section, we show
how it works and an example of how to interface it with Arduino and a
datalogger. Other sensors can be used in place of the KY-039 to save data to the
datalogger with minor changes to the code.
Attention: This project is for teaching purposes only. For real applications, an
approved and certified meter must be used. This post aims to explain the
operation and show an example of how this type of sensor can be interfaced with
the Arduino, but this is not a project for real applications.
Applications
Basically, the frequency meter is used to build small devices for measuring heart
rate. Depending on how you implement it, it can be equipped to use during
walks/runs, for example, or any other type of variation.
Project Description
In this project, we will pursue the following objective:
Develop and assemble a heart rate meter that saves your heart rate history to a
log on the SD card.
Hardware Aspects
As stated at the beginning, our circuit consists of two parts: the circuit for the
datalogger and the circuit for the heart rate sensor itself. In the diagram below,
we show the datalogger integrated with the heart rate sensor:
We draw your attention to the three voltage dividers that are needed to connect
the SD card pins with the Arduino (a logic level converter can also be used).
The Ky039 sensor connections are very simple. The power pins can be
connected to the Arduino 5V and GND. Pin S must be connected to A0, which
will be used in our program to take readings.
SD card;
3 3K3 resistors;
3 2k2 resistors ;
An important tip. For effective operation, the infrared beam must be well aligned
with the receiver, as shown in the figure below:
Software Aspects
This simple assembly and firmware identify the variations of the sensor and
saves the data in the SD, but to achieve stable and more accurate measurements,
improvements are necessary. In general, other projects on the internet also
feature measurements with many variations. If you really decide to use this
sensor, some possibilities are:
Some other interesting projects are (the second link is great to see how variations
in ambient lighting conditions alter the behavior of the sensor):
We hope the project helped to teach new content. Although KY-039 is not very
accurate and there are no examples of really functional designs with it, it is a
very didactic sensor in terms of its operation and also very simple in relation to
its circuit.
We recommend reading the other references and projects that we recommend to
find out the difficulties and solutions that other developers have encountered.
Now we will learn how to use the ISD 1820 audio recording and playback
module. The module can be used alone, using its push buttons, or with an
interface MCU (control via GPIO).
Know a little more about the module and learn how to incorporate it into your
applications.
In this part, we will use Arduino, as it offers flexibility and the possibility of
integrating audio recording and playback in an automation project, for example.
The heart of the module is the CI ISD 1820. It is responsible for the process of
acquiring voice and reproducing the data recorded in memory. In addition to the
CI, a quick inspection of the module allows the identification of an electret
microphone, the power terminal, the control buttons, with the REC, PLAYE and
PLAYL functions, and also the outputs for the speaker, which is the white
connector at the end of the module.
See the figure below for the location of the microphone, the power terminals,
and the ISD 1820 IC:
To select the recording time, it is necessary to adjust/change an external resistor.
The sampling frequency is also changed using this resistor. The recording time is
8 to 20 seconds, and the sampling frequency is 4 to 12kHz. The default resistor
is 100k. As you can see in the table below, this means that, by default, the
module plays 10 seconds of audio and has a sampling frequency of 6.4kHz.
VCC: 3.3V;
SP + and SP-: These are the outputs for the speaker. Can be
connected to speakers with impedances of up to 8 ohms;
It is worth mentioning the module's supply voltage, which is 3.3V, not 5V.
Therefore, be careful not to supply the module with a voltage greater than 3.3V,
at risk of damaging it.
1. Press/Activate the REC button (note the LED that will light up) and
keep it at a high level until the end of the recording;
Project Description
Now here we are going to implement an example to control the module through
the Arduino. The project will be as follows:
Thus, our test consists of two steps: Press the REC button via Arduino to record
the desired voice command, and then enter an object identification mode, in
which whenever the sensor identifies the presence of an object, the ISD module
1820 will play the recording.
Hardware Aspects
In the module, you will see a pin bar with 12 pins, six on the right and six on the
left. The default setting is to leave the two jumpers interconnecting all four
middle pins on the inside. The meaning of each pin and configuration is shown
in the image below:
When the jumpers are connected as in A (PE configuration), the recording is
played continuously. When a jumper is connected to B, there are no changes as
the two pins in the middle have no functions. When a jumper is connecting the
two pins in C, FT mode is enabled.
The circuit, together with the TCRT5000, is shown below. For module
connections, for convenience, we show only the pins used by the software.
Software Aspects
The software used is as follows:
#define exidaSensor 5
#define led 13
#define activatePlayL 3
#define activateREC 4
#define Reproductiontime 10000
int readingSensor = 0;
void setup ()
{
pinMode (outputSensor, INPUT);
pinMode (activePlayL, OUTPUT);
pinMode (activeREC, OUTPUT);
pinMode (led, OUTPUT); // Pin to activate the
pinMode led (sensor output, INPUT); // Pin to read the signal on the
collector of the
Serial phototransistor. begin (9600); // initializes the serial port with a
baud rate of 9600
MainMenu ();
}
void loop ()
{
readingSensor = digitalRead (outputSensor);
if (lSensor == 0)
{
digitalWrite (led, HIGH);
digitalWrite (activePlayL, HIGH);
delay (playtime);
digitalWrite (activePlayL, LOW);
}
else
digitalWrite (led, LOW);
delay (10);
}
void MainMenu ()
{
int controlLoop = true;
char byteRead;
Serial. println ("Type a to record or b to run the playback");
while (controlLoop)
{
if (Serial. available ()) // checks if data is available for reading
{
byteRead = Serial. read (); // readbyte latest in the serial buffer
Serial. write (byteRead); // send the received data to the computer
}
if (byteRead == 'a')
{
Serial. println ("Recording starts at 3");
counter (3);
digitalWrite (activeREC, HIGH);
Serial. println ("Recording for 10 seconds!");
counter (10);
digitalWrite (activeREC, LOW);
Serial. print ("Done!");
Serial. println ("Type b to start playback");
byteRead = '';
}
if (byteRead == 'b')
{
controlLoop = false;
byteRead = '';
}
}
}
void counter (int how many times)
{
for (int i = 0; i <how many times; i ++)
{
Serial. print (i + 1);
Serial. println ("...");
delay (1000);
}
}
In the program, two auxiliary functions were created:
MainMenu (): This function is a quick menu so that the user can
make recordings before the system enters the void loop () function;
When energizing the Arduino and with the serial terminal open, you will see
messages asking you to record new audio or proceed to playback. If you choose
to record, you can record new audio for 10 seconds (standard time). If you
choose to proceed with the reproductions, the firmware will go to the void Loop
() function. In this function, the TCRT5000 sensor is read constantly. Whenever
an object enters the reading range, the sensor output changes state, and the
PLAYL pin of the ISD 1820 module is activated for 10 seconds.
Depending on your application, you can make small adjustments to the code to
play the audio for a shorter time or use other features of the ISD 1820 module.
Chapter Eight
Digital Scale with Arduino and Strain Gauge
Cell
In this chapter, we are going to talk about a very useful and practical sensor to be
integrated with applications with Arduino. Load cells based on Strain Gauges are
the sensor elements used in digital scales of various types. The model cell that
we are going to use is capable of measuring up to 50Kg. For scales with greater
capacity, a larger number of sensors can be used. Here we will also explain what
Strain Gauges sensors are, and we will use a load cell to measure the weight of
objects up to 50Kg and present the result on an LCD.
The load sensor we are going to use is a strain gauge, one of several types of
sensors that can be used to measure weight. Multiple load sensors can be used
simultaneously to increase capacity. Our load cell is a half-bridge sensor, that is,
it uses a Wheatstone half-bridge with a reference resistance and a sensor element
whose resistance varies according to the pressure applied. See the image below.
In general, at least two load cells are used, one to measure compression and the
other to measure tension (forces applied in different directions). With two load
cells, you have a complete Wheatstone bridge. To use only one load cell, it is
necessary to complete the bridge with two other resistors.
How a Strain Gauge Sensor Works
The principle of operation of a Strain Gauge is the change in the electrical
resistance of the sensor proportional to a certain pressure or force applied to it
(hence the name “Strain”). The most common Strain Gauge sensor is made with
very small wires organized in a certain pattern (usually in the form of a
resistance bridge) so that when a force is applied in a certain direction, causing
deformation in the disposition of the wires, the resistance varies proportionately.
The sensitivity of each sensor and model is quite different and is usually
expressed by the so-called Gauge Factor (GF). This is defined as the ratio of a
change in electrical resistance to a change in length (physical dimensions)
caused by an external force.
The great difficulty with these sensors is that the deformations caused by the
application of an external force or pressure are very small, causing variations in
the scale of tenths of ohms. Due to these very small order variations, it is
necessary to use a second component, which is a signal amplifier. There are
specific business models for working with Strain Gauges. For this project, we
will use the HX711 amplifier (more information in the next section).
In addition to sensors based on strain Gauges, there are also pneumatic and
hydraulic load sensors. To work with Arduino and small electronic projects, the
Strain Gauge sensor, which is based on the variation of electrical resistance, is
the most suitable. For a quick video introduction, visit this link.
(https://www.youtube.com/watch?v=fPzUtzFJFus&feature=youtu.be)
The load cell we are going to use has the following specifications:
Dimensions (mm): 28 * 28 * 8;
It is an active sensor, that is, it is fed with an external excitation signal. The
sensor output is in Volts. As you can imagine, due to the small variation in the
resistance of the sensor element, the variation in the output voltage is also very
small. This output voltage signal is what we are going to connect to the HX711
amplifier.
HX711 Converter
The HX711 24-bit converter and amplifier module is used to amplify the signal
from devices such as load cells, making the interconnection between these cells
and the microcontroller. We recommend reading the datasheet.
(https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf)
Specifications:
SPI interface;
Dimensions: 29 x 17 x 4mm (without pins)
Applications
Load cells are used in commercial and industrial applications for weight/load
measurement in general.
Digital scales;
Weighing of objects;
Project Description
Our example project will be as follows:
Use two load cells to weigh objects and show them on the serial port.
Hardware Aspects
It is important to highlight the color pattern used in this cell. As shown in the
image, the red wire, which is usually used for VCC, is actually the output signal
(connected to pin A- of the HX711). And the wire to which the VCC must be
connected is the white wire. We recommend that you measure the resistance
between the cell wires to know which is which. The wires that give a reading of
2K are the ones that must be connected to E + and E- (generally, the white (E +)
and black (E-) wire). The wire on which you get 1K readings is the one to be
connected to A + (usually the red wire). Thus, pin A + d HX711 will be
connected to the common point between the two 1K resistors.
Load cells are generally used in groups of four, where each cell is placed on the
part of the scale. They can be used in groups of two as well, where each cell is
one of the “arms” of the Wheatstone bridge (this is the case in question). There
are also examples where one of the cells is replaced by two 1k resistors (in this
case, it has to be precision resistors). Another option for making measurements
with just one load cell is to complete the Wheatstone bridge with a 1K resistor
plus a trimpot. The resistors must be as close as possible, so traditional resistors
with a 5% tolerance are not a good idea. Using a multi-turn trimpot or 1%
tolerance metafilm resistors is more appropriate.
In the references at the end of the book, we leave some of these assemblies as an
indication.
In the image above, we see a complete resistance bridge. On each side, we will
use a load cell. Each cell has active resistance (sensor element). It is worth
noting that, for practical purposes, it is enough to connect the black wire of one
cell to the white wire of the other, and each red wire remains the signals A + and
A-.
To facilitate mounting on the Protoboard, pins can be welded to the ends of the
load cell wires. Note that the point of support of the scale surface must be on the
black arrow (upper part of the cell). The bottom of the cell must be on a flat
base as well.
The bottom of the cell must be suspended; otherwise, the pins that hold the
transducer will prevent the sensor from flexing. In this case, we used cut-out
Velcro adhesive to attach to the bottom.
The connection with the HX711 and the Arduino is shown below:
Software Aspects
For our Sketches, we will use the library HX711.h, which can be downloaded for
free from Github.
The first step is the calibration of the load cells. Using the assembly with the two
50 kg cells, run the calibration program below. In my assembly, the calibration
factor was 42130 (for weighing in kilograms). Therefore, this value was inserted
into the program. After calibration, make a note of the calibration factor to be
inserted in your Balance programs with the HX711.
Calibration Steps:
Remove the weight again, and zero the Scale (type t + ENTER to
zero),
Put the weight back on and repeat steps 3 through 6 to redo the
calibration.
Each load cell may have a different value for the calibration factor. If any
measured weight is giving a negative value, reverse the wires of pins A + and
A-.
If your scale allows the use of two cells at the same time, perform the calibration
procedure with the two cells mounted under the base of the scale.
When the balance is adequately accurate, stop the procedure and note the value
of the Calibration Factor. Repeat the calibration process with other known
weights, if necessary.
* /
#include "HX711.h" // HX711 Library
#define DOUT A0 // HX711 DATA OUT = Arduino pin A0
#define CLK A1 // HX711 SCK IN = pin Arduino A1
HX711 scale; // define HX711 scale instance
float calibration_factor = 42130; // calibration factor for initial test
void setup ()
{
Serial.begin (9600); // 9600 Bps serial monitor
balance.begin (DOUT, CLK); // initializes the scale
Serial.println (); // skips a line
Serial.println ("HX711 - Balance Calibration"); // prints on the serial
monitor
Serial.println ("Remove the weight from the scale");
Serial.println ("After the readings begin, place a known weight on the
Scale");
Serial.println ("Press a, s, d, f to increase the Calibration Factor by
10,100,1000,10000 respectively");
Serial.println ("Press z, x, c, v to decrease the Calibration Factor by
10,100,1000,10000 respectively");
Serial.println ("After reading the weight correctly, press t for TARA
(reset)");
balance.set_scale (); // sets the scale of the scale
zeroBalance (); // zero the Scale
}
void zeroBalance ()
{
Serial.println (); // skips a line
balance.tare (); // zero the Scale
Serial.println ("Zero Balance");
}
void loop ()
{
balance.set_scale (calibration_factor); // adjust calibration factor
Serial.print ("Weight:"); // prints on the serial monitor
Serial.print (balance.get_units (), 3); // prints scale weight to 3 decimal
places
Serial.print ("kg");
Serial.print ("Calibration Factor:"); // prints on the serial monitor
Serial.println (calibration_factor); // prints calibration factor
delay (500); // 0.5 second delay
if (Serial.available ()) // recognizes letter for adjusting the calibration
factor
{
char temp = Serial.read ();
if (temp == '+' || temp == 'a') // a = increase by 10
calibration_factor + = 10;
else if (temp == '-' || temp == 'z') // z = decreases 10
calibration_factor - = 10;
else if (temp == 's') // s = increases by 100
calibration_factor + = 100;
else if (temp == 'x') // x = decreases 100
calibration_factor - = 100;
else if (temp == 'd') // d = increase by 1000
calibration_factor + = 1000;
else if (temp == 'c') // c = decrease by 1000
calibration_factor - = 1000;
else if (temp == 'f') // f = increases by 10000
calibration_factor + = 10000;
else if (temp == 'v') // v = decrease by 10000
calibration_factor - = 10000;
else if (temp == 't') zeroBalance (); // t = zero the Scale
}
}
Arduino IDE serial monitor window, with the calibration procedure:
After calibrating the load cells, you can now run the Scale program.
Change the value of the Calibration Factor in the Arduino Program HX711
Balance (enter the value found in the Calibration procedure).
Remove any weight on the load cells, and press T to reset the Scale.
Insert the weight into the Scale and check the weight.
* /
#include "HX711.h" // HX711 Library
#define DOUT A0 // HX711 DATA OUT = Arduino pin A0
#define CLK A1 // HX711 SCK IN = pin Arduino A1
HX711 scale; // define HX711 scale instance
float calibration_factor = 42130; // calibration factor measured in
Calibration
void setup ()
{
Serial.begin (9600);
balance.begin (DOUT, CLK); // initializes the scale
Serial.println ("Scale with HX711 - 50 Kg load cell");
Serial.println ("Press t for Tare"); // prints on the serial monitor
balance.set_scale (calibration_factor); // adjust calibration factor
balance.tare (); // zero the Scale
}
void loop ()
{
Serial.print ("Weight:"); // prints on the serial monitor
Serial.print (balance.get_units (), 3); // prints weight on the scale to 3
decimal places
Serial.println ("kg"); // prints on the serial monitor
delay (500); // 0.5 second delay
if (Serial.available ()) // if the serial is available
{
char temp = Serial.read (); // le character of the serial
if (temp == 't' || temp == 'T') // if you press t or T
{
balance.tare (); // zero the scale
Serial.println ("Balance reset"); // prints on the serial monitor
}
}
}
Arduino IDE serial monitor window, with the HX711 Scale program (weight =
1,250 Kg) will look like:
Due to noise in connections with a protoboard and load cell, some readings may
vary outside the curve. However, measurements tend to remain around a
reference value. An important point for the quality of the measurements is how
the load cells are mounted on the scale.
The ideal is to use a flat surface on the load cells to apply the entire weight to the
cells. The mechanical structure you use to accommodate the weights can cause
the readings to vary slightly. Pay attention to this point.
With the circuit assembled, just run on the PC. Do not make wires too large to
connect the load cells to reduce interference.
Our final recommendation is that you use at least two load cells and complete
the Wheatstone bridge. Many examples found using only one load cell have had
many difficulties until getting readings that make sense.
Chapter Nine
IoT with Esp8266 WiFi Module & Updating
ESP-01 Firmware
In this first part of the chapter, we will explore the ESP8266 ESP-01 WiFi
module. It is a component that has become popular in recent years because it
makes the integration of WiFi networks and TCP/IP connections in electronic
projects easy and practical. We will cover the basic aspects of operation and
programming. In the next part of the chapter, an advanced application is
developed to control residential cargo over the internet.
Thus, in general, the Arduino interface is used only in the programming step.
But in real operation, ESP does not need to be connected to the Arduino or any
other control board. You can also use Arduino to expand your project's
capabilities and have more flexibility.
The ESP8266 is designed by Espressif Systems, a fabless company (without its
own factory) of wireless products in Shanghai. AI-Thinker does the
manufacturing itself. The small size and reduced price meant that the module
quickly attracted the attention of designers. With it, you can connect to a WiFi
network and create TCP/IP connections simply and practically.
Several versions of the module are produced, each with different technical
specifications. Projects using ESP8266 are not lacking. The internet has an
already quite respectable collection, and at the end of the section, in the
references section, there are some very interesting examples to go a little deeper.
The version in figure 1 (introduction) is one of the simplest, with eight pins
available in the module. A more robust version is the ESP8266 NodeMcu ESP-
12, which has 30 pins on the board and reaches a little more than the simpler
models (see the figure below).
For this introductory section, we are going to use ESP-01. This module talks to
the microcontroller via the serial interface. It also has 2 GPIO pins that allow the
module to be programmed directly. The figure below shows the module and its
pinout:
The pins are as follows:
The processing capabilities of the board are also good, considering its small size,
which allows it to integrate sensors and other equipment directly with the
module (with the necessary interfaces and conditioning whenever necessary).
Before we talk about the hardware aspects, we warn you that, like many other
components, the ESP8266 operates with 3.3V. If you have a 5V circuit, it is
necessary to use a logic converter and provide a 3.3V supply.
Hardware Aspects
Hardware assembly is very simple. Follow the connections in the image below:
For convenience, we use voltage dividers to adjust the logic levels, but you can
also use a specific converter. Notice that the GPIO and RST pins are
disconnected.
Another thing is that in this assembly, the Arduino is used only as a serial
interface with the computer. See that we connect the ESP to the Arduino serial
port. You can also use your own USB to RS232 converter module, such as
FTDI.
Software Aspects
As the goal is just to send AT commands manually so that we can understand
how the ESP-01 talks to the microcontroller, it is not necessary to write a
specific code. With the connections we use, let's just power up the Arduino and
use the IDE's serial terminal.
Since the TX and RX pins we are using are the ones that the Arduino uses to
communicate with its own microcontroller, we were able to send the commands
directly.
If you use other pins to make the serial connection, then it is necessary to write a
small program to receive the characters and send them to the module, and also
display the response strings on the serial terminal.
So, if you did the right assembly, just open the IDE, open the serial terminal and
proceed according to the next steps. To make sure that any previously recorded
application is not using the serial port pins, we suggest that you download the
“BareMinimum” example, which can be accessed in the IDE under the File ->
Examples -> Basics -> BareMinimum tab.
One point to note is that the ESP-01 may not have the correct firmware for use
with AT commands. If you have any problems with the steps in the next section,
after checking the connections, the next step is to save the most current SDK for
using AT commands.
The process for writing new firmware to ESP is explained in this other post. It is
worth checking because the process of updating AT firmware is not so well
explained on the internet (many references use tools other than those
recommended by the manufacturer and do not explain how to identify the binary
files and the respective memory addresses to be used).
AT
As an answer, you should receive an "Ok." This means that ESP-01 understood
the command and that it is all right to continue to command it. The module has
three basic operating modes:
In AP mode, ESP acts as an access point, allowing other devices to connect to it.
But that does not mean that you can, for example, access your personal website
via ESP-01 in AP mode. In this operating mode, it simply establishes a
communication channel with another device using the WiFi protocol.
In STA mode, ESP can connect to an AP, such as your home's internet modem.
This allows your device to communicate with any other equipment that is also
part of the local network.
In the third mode of operation, the module works as both AP and STA.
To set the module to operate in one of these three modes, use the command:
AT + CWMODE = X
AT + CWMODE = 1
To check which mode of operation the module is configured in, the command is:
AT + CWMODE?
See in the image below how your serial terminal should look:
How to Connect to a Network with the ESP-01
To connect to a network, there are two steps. First check if any connection is
already active with the command:
AT + CIFSR
If an IP address was displayed, it is because the module is connected to that
station. In fact, this is the module's IP address. If there is no IP (all reset), you
can connect to a network with the command:
Simply enter the network name and password in the indicated fields of the
command. Double quotes are part of the command. If all goes well, you will
receive an ok answer.
AT + CIPSTATUS
It shows the status of the connection. In the image below, the answer to this
command was 5, which means that it is not connected, as we expected.
In the image below, we connect to the “Example” network, which in this case
has no password (open network, without WPS security)
Configure ESP-01 as a Server
So far, we left the module in STA mode and connected to a local network. Now,
to configure it as a server, we first have to enable it to allow multiple
connections. The command below does this:
AT + CIPMUX = X
Where X is 0 for only one connection, and 1 for multiple connections. Then, we
configure the port with the following command:
AT + CIPSERVER = 1.80
The number 1 means that we want the module as Open Server Mode. If it were
0, we would be setting it to Close Server Mode. The number 80 is the default
number of the HTTP protocol port. If you open a browser and enter the IP
address of your ESP module, a screen similar to the one shown below will
appear on the serial terminal:
Sending Data to the Browser
With the settings made, we can send commands and display data in the browser.
For this, the command is used:
AT + CIPSEND = 0.9
The 0 indicates the channel that will be used to send the data. 5 is the number of
characters that will be sent. In our case, we will send the message “Hello
World.” After sending the command, a “>” symbol will appear. This means that
you can enter the characters you want to send.
If you receive the message “SEND OK,” the transmission was successful. For
the message to be displayed, the communication channel must first be closed.
Use the command:
AT + CIPCLOSE = 0
When sending this command, the message “Hello world” will be displayed in
the browser.
Click Ok after filling in the data and then open the menu tab (three dots in the
upper right corner) and select “Connect.” The screen below will be shown, and
you can now send information that appeared on the Serial monitor to which the
ESP is connected.
On the serial screen, you will receive all the messages sent.
Nice, right! It is highly recommended that you read the AT Examples from
Espressif Systems.
(https://www.espressif.com/en/support/download/documents)
In the next part of this chapter, we will make an application in home automation.
We will use the ESP-01 to control cargo over the internet. Now that you know
the module and know how the main AT commands work, everything will be
easier. For some advanced applications, there are already some developed
libraries, and we will also use them to increase the projects.
Now we will show you how to update the ESP-01 firmware. There will be two
approaches. The first will be to show how to restore the default firmware for
module AT commands. The second will be to present how to record new
firmware written by you or ready-made examples from the Arduino IDE.
There are several examples and posts on the internet, but an impressive number
of them run into a very complicated problem from the didactic point of view:
They explain the step by step very well but do not explain what is behind each
step. This happened mainly to record the original firmware for use with AT
commands. Most guides assume that the reader knows exactly how to configure
Espressif Systems tools and how to identify the memory addresses associated
with each binary file that must be written.
Despite being a basic aspect of all research in the electronics area, users do not
always remember to read the readme files or to seek instructions from the
manufacturers of the models and sensors themselves, preferring to go straight to
tutorials that, in theory, would better explain how to put an application to run.
In the case of recording the original firmware to use the ESP-01 with AT
commands, the main recommendations to be taken into account are:
Go to the bin folder, inside which will be the binaries for you to
record and two other folders: std and stdio. These two folders are the
readme file (one file for each folder). When opening each file, you
should find content more or less like the image below:
These files indicate the corresponding address for each binary file, for each type
of ESP-01 (which varies the size of the flash memory). This file is often omitted
in tutorials, but it is the main source for knowing how to use the manufacturer's
binary files correctly.
Knowing the addresses is essential as the ESP-01's official firmware update tool
saves more than one binary file at the same time, making it necessary to specify
exactly which memory address from which each file should be saved.
Hardware Aspects
In view of what was said in the introduction, we will use the following assembly
to load the software (both the original for AT commands and other firmware you
want to record).
The assembly was done using the FTDI232 serial converter. It is a very useful
board on many projects, and it is recommended to have one when needed. The
most important points of the assembly are the following:
The FTDI232 card works with 5V or 3.3V. In this case, since the
ESP-01 works with 3.3V, you must use an external 3.3V source to
power the protoboard and select the FTDI232 jumper to the 3.3V
position. See the highlighted jumper in the image below, and it is
essential to put it in the correct position.
Two buttons are used, one connected to the ESP reset pin and the
other to the GPIO0 pin. These two keys are used to put the module
into recording mode.
As the entire circuit is powered by 3.3V and the FTDI232 has the
jumper selected for 3.3V, it is not necessary to convert the logic
levels between the two boards. But it is common in projects with
ESP that you have to use a logic level converter or voltage dividers.
In the next section, we will do the firmware update in two procedures.
Software Aspects
First, let's load the firmware to use AT commands. It is often necessary to load
this firmware to be able to work with AT commands and make tests with your
module.
Recording tool ;
Binary files ;
The recording tool has the face below. Note that there are several fields to fill
with a memory address and load different binary files. As we mentioned at the
beginning of the post, you should check the readme file, which comes with the
binaries you downloaded, which is the memory address associated with each
binary.
To find out the size of your module's memory, you can do a simple test. When
running the ESP Flash Download Tool, two windows are opened: the main
screen of the program and a black screen used for logging.
Select the COM port assigned to your module.
Select the baud rate. The most common value is 115200, but
depending on the version of your module and firmware, it can be
different. Try 115200 first.
Now, with your circuit properly energized and with the FTDI232
connected to the computer, press and hold the button connected to
the ESP GPIO_0 pin, and then press and release the other button
(Reset). You will see the blue ESP led blink once.
Just upload the corresponding files and fill in the address on the right, as shown
below. Then check the SPIautoSet option above the DETECTED INFO box.
Also, select the size of your module's Flash memory. Once everything is
checked, select and START and wait for the download to finish.
In the end, your module will be loaded with the firmware for AT commands. To
test if everything went well, open a serial terminal, and do a test by typing AT. If
you get an "OK," then everything went well!
If something goes wrong, check if there have been any changes in the official
repository.
See the image below for the preferences screen to load the additional URL.
After adding the URL, you can install the ESP package as per step 2, as shown
below:
After doing all the steps and with your ESP module already selected for the IDE,
you can now do the firmware update. With the circuit assembled and properly
tested, go to the Arduino IDE and download the ESP8266 Blink example. With
the example open and the circuit energized, keep the button connected to GPIO0
pressed and press the reset button. You will see the blue LED flash, which
means that the module is in recording mode.
Now, in the IDE, just upload the firmware and wait for the recording to finish. In
the end, the Blink program will be loaded on your ESP. The same procedure can
be repeated for other modules.
Now that you know how to load and update the ESP-01 firmware, you can start
making your applications and writing your own programs.
Chapter Ten
RTC - Real Time Clock DS1302, 1307 And
3231
This is the last chapter of this book, and here we will talk about real-time clocks,
or as they are known, RTCs - Real-Time Clocks. We will explain the three main
models used in applications with Arduino: RTC DS1302, RTC DS1307, and
RTC3231. A project will be implemented, in which we will use the RTC
DS1307 to send date and time information to an LCD, that is, we will make a
digital clock.
RTCs are small electronic devices used to incorporate date and time data into
electronic devices. RTCs use quartz crystals and assisted circuits integrated into
a chip to measure time. Virtually all devices that require precise time control
have some type of RTC.
RTC DS3231
The DS3231 is a high-precision, low-power RTC. The module has a factory
temperature sensor and also an oscillator to further improve its accuracy.
It works in both 12-hour and 24-hour format, and information for months less
than 30/31 days and leap years are automatically corrected by the module.
A battery is included with the module to prevent data loss if the circuit is de-
energized. An important aspect that sets it apart from other models is the
communication protocol used. In the case of DS3231, the I2C protocol is used.
Thus, there are two communication channels (pins): SCL (Clock) and SDA
(data).
Dimensions: 38 x 22 x 14mm.
Weight: 8g.
RTC 1302
The RTC 1302 is the simplest of the three. It communicates via a serial protocol,
with a pin called CE and another SCL. It is able to provide information on
second, minute, day, date, month, and year. Months with less than 31 days and
leap years are automatically handled by the module, and it operates in 12 and 24-
hour formats.
Chip: DS1302.
The datasheet, directly from the manufacturer's website, can be accessed here.
(https://datasheets.maximintegrated.com/en/ds/DS1302.pdf)
RTC 1307
This Real Time Clock (RTC) is a real-time clock with a complete calendar and
more than 56 bytes of SRAM non-volatile memory. Like the other RTCs, it
provides information for seconds, minutes, days, dates, months, and years. On its
board, there is a circuit that detects power failures and activates the built-in
battery to avoid data loss.
It uses I2C protocol and automatically handles cases of months with less than 31
days and leap years.
Specifications:
Chip: DS1307.
56 bytes of SRAM.
The big difference is that the I2C signals the start and end of the data
transmission using changes in the logical state on the SCL and SDA pins.
Basically, if SCL is at a high level, and there is a transition from high to low in
the SDA, the DS1307/3231 recognizes it as the START of communication.
Now, if SCL is at a high level and there is a low to high transition in the SDA,
the DS1307/3231 recognizes it as the END of communication.
In the DS1302, the role played by these logic combinations is played by the CE
pin. If it is at a high level, communication starts, if it is at a low level, the data
transfer ends. That is, whenever a reading or writing procedure is performed
with the DS1302, the CE pin must be placed at a high level.
The supply voltages are also important differences, with the DS1302 operating at
a minimum of 2V, while the DS1307 operates at a minimum of 4.5V.
Hardware Aspects
To illustrate how to use RTC in your projects, let's do the following assembly:
Notice that the RTC DS1307 was connected directly to the Arduino. This is
possible because both works with the same voltage levels. In addition to the
RTC, we also connect an LCD to show the date and time data. If you have any
questions regarding the LCD, read this post, and learn more details.
From a hardware point of view, assembly is simple. If the other RTCs were
used, the assembly would be basically the same.
Software Aspects
From a software standpoint, we will use the RTClib.h library, which can be
found on GitHub.
#include <Wire.h>
#include "RTClib.h"
#include <LiquidCrystal.h>
#define InterfaceLCD 1
RTC_DS1307 rtc;
char daysOfTheWeek [7] [12] = {"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"};
LiquidCrystal lcd (9, 8, 4, 5, 6, 7); // RS E D4 D5 D6 D7
void setup ()
{
Serial.begin (57600);
if (! rtc.begin ())
{
Serial.println ("Couldn't find RTC");
while (1);
}
if (! rtc.isrunning ())
{
Serial.println ("RTC is NOT running!");
// set for compilation date and time
rtc.adjust (DateTime (F (__ DATE__), F (__ TIME__)));
// Set to a date you set
//rtc.adjust(DateTime(2017, 12, 27, 11, 14, 0));
}
lcd.begin (16, 2);
delay (2000);
}
void loop ()
{
if (InterfaceLCD == 1)
showLCD ();
else
showSerial ();
Serial.println ();
delay (3000);
}
void showLCD ()
{
DateTime now = rtc.now ();
// year = now.year ();
lcd.clear ();
// shows the date
lcd.print (now.year ());
lcd.write ('/');
lcd.print (now.month ());
lcd.write ('/');
lcd.print (now.day ());
// Shows the time
lcd.setCursor (1, 2);
lcd.print (now.hour ());
lcd.write ('/');
lcd.print (now.minute ());
lcd.write ('/');
lcd.print (now.second ());
}
void showSerial ()
{
DateTime now = rtc.now ();
Serial.print (now.year (), DEC);
Serial.print ('/');
Serial.print (now.month (), DEC);
Serial.print ('/');
Serial.print (now.day (), DEC);
Serial.print ("(");
Serial.print (daysOfTheWeek [now.dayOfTheWeek ()]);
Serial.print (")");
Serial.print (now.hour (), DEC);
Serial.print (':');
Serial.print (now.minute (), DEC);
Serial.print (':');
Serial.print (now.second (), DEC);
Serial.println ();
}
Note that in the software, we use two functions to display the date and time data.
The showLCD function shows the data on the LCD, and the showSerial function
shows it on the serial interface. To select which one to use, just change the
InterfaceLCD flag.
The rtc.adjust function (DateTime (2017, 12, 27, 11, 14, 0)) adjusts
the RTC time to the user-defined date and time. In this case,
December 27, 2017, 11 hours and 14 minutes.
After the rtc.adjust function is called, the RTC will start from that
date, and you no longer need to adjust it (unless you want to). The
RTC will continue to count until the day the module's battery runs
out, usually after a few years.
To read the date and time data, the new object of the Datetime class
is created (DateTime now = rtc.now ()). This object reads the
various time information, as shown in the showLCD and showSerial
functions.
Load the software into your assembly and test it. Using the serial interface, you
will have something like the image below in your output:
The first time the software runs, the message RTC is not running! will be
displayed. After that, the function rtc.adjust () will be called, and the RTC will
start counting the time normally.
With everything set up, you should receive messages like the ones shown on the
screen above. Detail: To change the display, such as changing from
“Wednesday” to “Wednesday” or showing the time first, just adjust the order of
the Serial.println and lcd.print functions within the showSerial and ShowLCD
functions. This adjustment is for homework, so you can train.
To use the LCD, just do the assembly, as shown in the "Hardware Aspects"
section. If you have any questions about the LCD or want to know more
information about it, read this specific post about that component. Remember to
adjust the contrast by the potentiometer until the letters can be seen clearly.
What's more, you can now incorporate date and time information into your
projects; the same library used in this project also has support for the RTC
DS3231. For the RTC DS1302, good library options and examples can be found
in the references at the end of this book.
Conclusion
Arduino is an open-source platform for electronics prototyping based on flexible
and easy to use hardware and software. It is targeted at artists, designers,
amateurs, and anyone interested in creating interactive objects or environments.
Arduino is capable of detecting environmental conditions by receiving signals
from sensors and interacting with the environment, controlling lights, motors and
other actuators. The PCB microcontroller is programmed using the Arduino
cable-based programming language and the Arduino environment based on the
processing environment. Projects developed using the Arduino can be self-
contained or can interact with a computer to complete a task using special
software (e.g., Flash, Processing, MaxMSP).
The technology created in 2005 by the Italian Massimo Banzi, along with other
collaborators, was born to be a facilitator in the teaching of electronics for
students of design and artists.
The platform was born to be low cost because students needed to be able to
develop their prototypes while spending as little as possible. You know how it is,
right?
Another interesting point of the project was the proposal to create an open-
source platform available to the community, which helped a lot in its
development.
Its applications are the most diverse, from fun to art, home automation, and even
helping other people. For example, the Arduino has already been used to create a
beer cooler controlled by an iPad where it was possible to follow the flow of the
drink and obtain information about the different types of beer. In addition, the
plate also served to inform the temperature and find out who drank more.
Another team created a touch-sensitive glove that helps blind people to “see”
obstacles along the way. In the same vein, another user created a jacket using the
LilyPad version (designed to build wearable designs) of the Arduino that
informs when a cyclist will change lanes through LEDs placed on the back of the
jacket.
In this book, we listed some incredible projects that used Arduino, proving that
this is a tool that helps a lot of those who have creativity.
You can make LED cubes that generate three-dimensional images, secret knock
detectors, after all, security is never too much, sneakers that tie the shoelace for
you, like “Back to the future 2”, in fact, the prototype rolled so well that it
became a product and it was opened for commercialization ...
A lot of people know that the creators of Pebble - that watch that hit 10 million
dollars in their crowdfunding campaign - did not get a 2nd round of financing, so
they turned to the community (Kickstarter) to get investment. What few know is
that they used Arduino to make their prototype.
Reference and Resources
https://create.arduino.cc/projecthub/MisterBotBreak/how-to-use-an-rgb-led-
89bcae
https://www.programmingelectronics.com/tutorial-10-fade-an-led-with-pulse-
width-modulation-using-analogwrite/
https://www.arduino.cc/en/reference/servo
https://forum.arduino.cc/index.php?topic=478360.0
https://www.arduino.cc/en/Guide/ArduinoEsploraExamples
https://www.pololu.com/file/download/MQ2.pdf?file_id=0J309
https://en.wikipedia.org/wiki/MIFARE
https://www.arduinolibraries.info/libraries/mfrc522
https://github.com/RuiSantosdotme/Random-Nerd-Tutorials/blob/master/
Projects/MFRC522_RFID_Reader_with_Arduino.ino
https://stackoverflow.com/questions/58863735/ trying-to-stop-multiple-activations
https://create.arduino.cc/projecthub/Elaf07
https://stackoverflow.com/questions/59362306/ i-keep-getting-a-compilation-
error-on-arduino-ide-using-mfrc522-rfid-saying-that
https://learn.openenergymonitor.org/
https://github.com/openenergymonitor/EmonLib
https://www.filedesc.com/en/file/ad4
https://www.robotshop.com/community/forum/c/letsmakerobots
https://forum.arduino.cc/index.php?topic=117009.0
https://gist.github.com/buildcircuit/5132328
https://www.buildcircuit.com/how-to-convert-mp3-and-wav-files-to-ad4-format-
wtv020sd-tutorial/
https://www.instructables.com/id/How-to-use-WTV020SD-16P-with-Arduino/
https://www.buildcircuit.com/example-1-using-wtv020sd-16p-music-module-
with-arduino/
https://forum.arduino.cc/index.php?topic=117009.0
http://www.electronoobs.com/eng_arduino_tut8.php
https://makezine.com/projects/ir-pulse-sensor/
https://www.instructables.com/id/Heart-Rate-Monitor-1/
https://microcontrollerslab.com/heart-beat-sensor-arduino/
https://tkkrlab.nl/wiki/Arduino_KY-039_Detect_the_heartbeat_module
http://www.utteducation.com/past-projects/ky-039-finger-measuring-heartbeat-
sensor-module/
https://forum.arduino.cc/index.php?topic=368013.0
https://www.instructables.com/id/HOW-TO-USE-ISD1820-VOICE-
RECORDER-AND-PLAYER/
https://www.allelectronics.com/mas_assets/media/allelectronics2018/spec/ME-
63.pdf
https://www.elecfreaks.com/store/blog/voice-record-module-isd1820.html/
https://learn.sparkfun.com/tutorials/getting-started-with-load-cells
https://cdn.sparkfun.com/datasheets/Sensors/ForceFlex/hx711_english.pdf
https://github.com/bogde/HX711
https://www.hackster.io/MOHAN_CHANDALURU/hx711-load-cell-amplifier-
interface-with-arduino-fa47f3
https://electronics.stackexchange.com/questions/199487/connect-hx711-to-a-
three-wire-load-cell
https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-
guide
https://electronics.stackexchange.com/questions/102164/3-wire-load-cells-and-
wheatstone-bridges-from-a-bathroom-scale
https://www.geekstips.com/esp8266-arduino-tutorial-iot-code-example/
https://maker.pro/esp8266/tutorial
https://www.instructables.com/id/ESP8266-Wi-fi-module-explain-and-
connection/
https://maker.pro/esp8266/tutorial/how-to-program-esp8266s-onboard-gpio-pins
https://datasheets.maximintegrated.com/en/ds/DS3231.pdf
https://datasheets.maximintegrated.com/en/ds/DS1302.pdf
https://datasheets.maximintegrated.com/en/ds/DS1307.pdf
https://github.com/adafruit/RTClib
https://github.com/msparks/arduino-ds1302
https://github.com/iot-
playground/Arduino/tree/master/external_libraries/DS1302RTC
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/overview
https://www.instructables.com/id/Arduino-Real-Time-Clock-DS1307/
https://www.arduino.cc/en/Reference/RTC