Arduino Programming 3 in 1
Arduino Programming 3 in 1
This document is geared towards providing exact and reliable information in regards to the topic and
issue covered. The publication is sold with the idea that the publisher is not required to render
accounting, officially permitted or otherwise qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
- From a Declaration of Principles which was accepted and approved equally by a Committee of the
American Bar Association and a Committee of Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic
means or printed format. Recording of this publication is strictly prohibited, and any storage of this
document is not allowed unless with written permission from the publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability, in terms of
inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained
within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any
legal responsibility or blame be held against the publisher for any reparation, damages, or monetary
loss due to the information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely and is universal as so. The
presentation of the information is without a contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark is without
permission or backing by the trademark owner. All trademarks and brands within this book are for
clarifying purposes only and are owned by the owners themselves, not affiliated with this document.
Table of Contents
ARDUINO PROGRAMMING
A Comprehensive Beginner's Guide
to learn the Realms of Arduino from A-Z
Introduction
Where Do I Find a Microcontroller?
Arduino
Know the Hardware
Chapter 1: Basic Concepts of Arduino
Physical Computing
Open Source Hardware
Free Software
Arduino
Processing
Fritzing
Chapter 2: Electronics
Concept of Electronics
Voltage
Electric Current
Direct Current
Alternate Current
Resistance
Ohm's Law
Electronic Systems
Summary of Electronic Systems
Electronic Signals
Voltage Divider
Analog to Digital Converter
PWM Pulse Width Modulation
Serial Communication
Chapter 3: Electronic Components
Microcontroller
Protoboard
Resistor
Thermistor
Diode
Transistor
Capacitor
LED
RGB LED
LCD
Button
Reed Switch
Potentiometer
Photocell
Piezoelectric Transducer
DC Motor
Relay
Chapter 4: Arduino Programming
The Arduino Project
Arduino IDE for Windows
Arduino IDE for Linux
Programming
Programming Language
Algorithm
Arduino Software
Sketches
Serial Monitor
Arduino Library
Programming Arduino
Digital Functions
Analog Functions
Chapter 5: Starter Kit with Arduino Uno R3
Lessons
Button
Serial Reading of a Digital Input
Serial Reading of an Analog Input
Command with Serial Communication
Fade
Loop
LDR Sensor
Thermistor
DC Motor
LCD
Typing into the LCD
Piezo as Analog Output
Scroll Bar with Processing
Arduino - Thermostat
Chapter 6: If Statement with Arduino, Control the Execution of your
Code
If with Arduino - Necessary Material
Syntax of the if Statement with Arduino
Comparison Operators in if Statements with Arduino
Example if Statement with Arduino
Boolean Operators if with Arduino
if-else with Arduino
Example if-else statement with Arduino
else if with Arduino
Example else if statement with Arduino
Chapter 7: Battery and Battery Charge Meter with Arduino
The Objective of the Battery and Battery Charge Meter with the Arduino
Board
Arduino Components that We Will Use
Riding the Circuit with Arduino
Programming the Battery and Battery Charge Meter with Arduino
Arduino Native Code
Chapter 8: ADS1115 ADC Digital-Analog Converter for Arduino and
ESP8266
What is a Digital-Analog Converter?
What is an ADS1115?
Install Library for ADS1115
Single-End Mode Programming
Differential Mode
Differential Mode Programming
Comparator Mode
Chapter 9: Arduino Interruptions
Practical Example: Controlling the Speed of Fantastic Car Lights
Conclusion
References
ARDUINO PROGRAMMING
Tip and Tricks to Learn Arduino Programming Efficiently
Introduction
What is Arduino?
Advantages of Arduino
Arduino - Choosing a Hardware Platform
Equipment Arduino UNO R3
Clones, or Arduino (un) Original
Materials you need to program Arduino
Arduino IDE Installation
What happens when you install the wrong IDE?
If you already have Arduino
Chapter 1: Basic Concepts of Programming
Conversions
Decimal <-> Binary
Binary <-> Hexadecimal
Decimal <-> Hexadecimal
QUICK Method
The Software
Installation
Downloading
Windows
Mac Os
Under Linux
Software Interface Software Launch
Correspondence
Approach and Use of the Software
The File Menu
Buttons
Equipment
Presentation of the Card
Constitution of the Card
Materials
Visualization
Connectivity
Installation
Windows
Test your Equipment
The Arduino Language (1/2)
Language syntax
The Minimum Code
Function
The Instructions
The Braces
Comments
Accents
The Variables
What is a Variable?
A Variable is a Number
The Name of a Variable
Define a Variable
Code: C
The Arduino Language (2/2)
What is a Loop?
The do... while loop
Concatenation
The Functions
What is a Function?
Make a Function
But what is "Void"?
Empty Functions
The "Typed" Functions
Functions with Parameters
What is going on?
The Tables
What's the Point?
The Maximum Score
Average Calculation
Chapter 2: Input / Output Management
Our First Program
But how do you calculate this resistance?
Where do we start?
Create A New Project
What does "HIGH Value or LOW Value" Mean?
Use the Command
The Program
Millis () Function
Limits of the Delay () Function
Chapter 3: Programming With Arduino
The Basic Structure of a Sketch
1. Variables to Name
2. Setup (essential in the program)
3. Loop (essential in the program)
Instructions
A Flashing LED
Circuit
The Change Indicators
Sketch:
An LED Pulsing Leave
Sketch:
Simultaneous Lighting and Sound
Sketch:
Activate a LED Touch of a Button
Sketch:
An RGB LED Drive
Sketch 1:
Sketch 2:
The Motion
Sketch:
Read Brightness Sensor
Read Voltages
The "Serial Monitor"
Sketch:
Knobs
Sketch:
Measure Temperatures
Sketch:
Measure Distance
Code:
Enhancements: Reversing Warning
Infrared Remote Control for Controlling Arduino Microcontrollers
Code:
Servo Drive
Code:
LCD Display
Code:
Relay Card
Code:
Stepper Motor
Cabling
Code
Code:
Drop Sensor
Code:
RFID Kit
Read an RFID tag with Arduino and Process the Data
Preparation - the first sketch with the RFID READER
RFID Sketch 2
Sketch 3
Chapter 4: Accessories for Arduino
Keypad Shield
Code:
Instructions for LCD Display with I2C Port
Program
Sketch:
Example of use:
Two I²C Displays
Arduino RTC
Cabling:
Extension:
Keypad
The Sketch:
Keypad - Castle
Color Sensor
Cabling:
Generate Tones
Code:
Create Melodies
Arduino Tilt Sensor SW-520D
The Sketch:
Temperature Measured with the LM35
Expansion of the Program:
Code:
Measure the Voltage
Cabling:
We now come to the code:
Four-Digit 7-Segment Display
Programming
Code:
Conclusion
References
ARDUINO PROGRAMMING
Advanced Methods and Strategies
to Learn Arduino Programming
Introduction
Chapter 1: Setting Up the Tools
The Arduino Software
Arduino Hardware
Setting Up The Arduino IDE
Working with Arduino
Chapter 2: The Basics of Arduino Programming
Curly Bracket
Semicolons
Comments
Variables
Datatype
Boolean
Byte
Integer
Long
Double and Float
Character
Arrays
Character Arrays
Constants
Arithmetic Functions
Comparison Operators
Logical Operators
Casting
Decision Making
Looping
Functions
Chapter 3: The Advanced Concepts of Arduino Programming
Setting Digital Pin Mode
Digital Write
Digital Read
Analog Read
Structures
Unions
Adding Tabs
Working with Tabs
Object-Oriented Programming
String Library
Arduino Motion Sensor Project
Arduino LCD Display Project
Chapter 4: Structuring and Arduino Programming
Structuring and Arduino Program
Using Standard Variable Types
Floating- Point Numbers
Working with Groups of Values
Using Strings in Arduino
Using Strings of C Programming Language
Splitting Comma- Separated Text into Groups
Converting a Number to a String
Converting a String to a Number
Transforming the Lines of Code into Blocks
Returning More Than One Value from a Function
STUART NICHOLAS
Introduction
Arduino
A few years ago, a free project, called Arduino, appeared, which facilitated
access to this class of devices for students since it is an open hardware-based
board (its design is free and can be reproduced by anyone).
Initially, the board was connected through a USB port to program it (it
usually is done based on its IDE that can be found here). Arduino
programming was not done at a low level with assembler like many
microcontrollers (from now on we will call them PICs), but it is done with a
language more understandable by most of us, C / C ++ (the basic reference to
the language we found here and examples on this route).
With these elements, a programmer who does not know about PICs would be
able to program the Arduino in a short time.
The UNO version board consisted of 14 digital I / O pins, of which 2 had a
serial connection. These pins are useful for most basic sensors, or for relays,
actuators, etc., which only have two states, on or off (or with the Arduino
constants HIGH and LOW). It also has six analog pins, capable of reading up
to 1024 voltage levels, called analog port resolution. These are used to read
sensors that give us different voltage ranges depending on their state, such as
heat resistance, variable resistance, etc.
Basically, with the structure of the Arduino UNO, anyone can enter the world
of PIC programming. But, for larger projects, more power is needed, with
which the Arduino boys were creating plates and improved versions of the
Arduino UNO. I expose a few:
Arduino Leonardo
It is the first evolution of the Arduino Mega, in fact, it has the same ports, but
the PIC is different, with greater capacity and higher working frequency.
Another difference is the USB port, which at the same time of being used to
upload the program, can use the USB as a host; that is, we can use it as a
keyboard, etc ... Another inclusion is the SDA and SCL ports, used for
devices that communicate through the I2C protocol.
Arduino Mega 2560
For those who fall short, the Leonardo designed the Arduino Mega 2560,
with much more speed in the microcontroller and many more digital (54 pins)
and analog (16 pins) ports. We have the pins for I2C like Leonardo (although
they change position).
This design is also the Arduino Mega ADK, which is a modified board of the
Mega 2560, but a USB host port is added. Google has designed several
projects with this board and its flagship, Android, an example you have on
this page.
Another evolution is the Arduino DUE, with the same design as the Mega
2560 but with a 32-bit microprocessor. It is much faster than the Mega 2560.
Arduino YUN
Basically, this board has the same pin and processor characteristics as the
Arduino Leonardo, but a microcomputer has been incorporated where a small
Unix resides, which allows us to mount fundamental web servers. This board
is mostly used for projects in which the sensors have to report through an
Ethernet network quickly and easily.
More developments will come in the future, merging the power of Arduino
boards with computer motherboards and offering us the possibility of
creating a multitude of projects, with unlimited power and scalability.
Breadboards
Hello World with Integrated LED
After installing the Arduino IDE (https://Arduino.CC/en/Main/Software) and
connecting it via the USB cable, you need to configure it. We start by
choosing the serial port where it is connected (usually there will only be one).
Next, you must choose the Arduino model.
In some cases (such as Arduino Mega), it is also necessary to choose the
version.
The Arduino IDE comes with some examples. Let's start by using the Blink
example for flashing the integrated LED on board (L), which is connected to
pin 13.
The example shows two functions:
Setup()
In this function, we initialize the hardware we are using. This function runs
once when Arduino is powered.
Loop()
In this function, we put the program that performs the desired function. At the
end of this function, it is called again (repeats indefinitely).
After creating the program, we must validate it. For this, we use the first
toolbar button (√).
To send the program to Arduino, we use the second button (→). During
upload, we will see several messages at the bottom of the IDE as well as the
flashing RX and TX LEDs on the board. Once the upload is complete, the
program starts automatically. In this case, the LED L on the board will flash.
You can adjust the delay()to change the duration of each state (on or off) of
the LED. The delay()uses milliseconds. We start by implementing the
following scheme, with a button and a high resistance (e.g., 10 kΩ).
This scheme, which, while the button is not pressed, is sending 0V to the
input, is called a pull-down. There is also a pull-up, but by default, the input
gets + 5V (or + 3.3V, depending on the type of card).
Then we load the Button example. After upload, the button will work to
activate the LED. Using the scheme from the previous lab, we will send the
status of the button over the USB / serial connection to the computer. Let's
open the DigitalReadSerial example.
After sending the program to Arduino, let's see what is sent to the USB /
serial port using Serial Monitor.
Note: Before turning on the Serial Monitor, in some, the serial output buffer
fills up quickly, then the LED starts flashing randomly, and the program
hangs on the Serial.println().
We can also send custom to debug text. For example, we add the line (always
respect case).
[...] Serial. println ( buttonState );
if ( buttonState ) Serial . println ( "ON" ); else Serial . println ( "OFF" );
delay ( 1 ); // delay in between reads for stability [...]
Building on the scheme of previous labs, let's add a relay (which acts as a
switch that can control external equipment).
We add to the end of the function setup():
pinMode ( 13 , OUTPUT );
pinMode ( 12 , OUTPUT );
We add to the end of the function loop():
digitalWrite ( 13 , buttonState );
digitalWrite ( 12 , ! buttonState );
Why is the pin 12 (relay) value reversed? The relays we are going to use will
be active if their signal pin receives 0V, and they are inactive if they receive
5V (or not turned on). Not all relays are like this, so try testing before using
it.
Using the scheme of previous labs, we will add an analog temperature or
light sensor to pin A0.
Next, we load the example AnalogReadSerial.
We open the Serial Monitor again to see the sensor values. Analog pin
reading (A0, A1, etc.) returns values between 0 and 1023 (i.e., linearly
between 0V and 5V). However, likely, the sensor chosen will only show
values in part of this range. Record the minimum and maximum sensor
values for use in the following laboratory.
Using the scheme of previous laboratories, we will define rules for activating
the relay. For example, if we use a light sensor, when we no longer have
light, we want to enable the relay to turn on a lamp.
We add to the end of the function setup():
pinMode ( 13 , OUTPUT );
pinMode ( 12 , OUTPUT );
pinMode ( 2 , INPUT );
We add to the end of the function loop():
if ( sensorValue > 500 || digitalRead ( 2 )) { // Relay on
digitalWrite ( 13 , HIGH );
digitalWrite ( 12 , LOW ); } else { // Rele off
digitalWrite ( 13 , LOW );
digitalWrite ( 12 , HIGH ); }
The exact value (here 500) and the operator ( >or <) may vary by sensor. Use
the values obtained in the previous laboratory to calibrate.
Chapter 1
Physical Computing
Physical computing means building interactive physical systems through the
use of software and hardware that integrate, can feel and respond to the
analog world. Although this definition is broad, in a more general sense,
physical computing is a creative framework for understanding the
relationship between humans and the digital world. In practice, this term
often describes design drawings DIY or objects using sensors and
microcontrollers for translate analog inputs to software-based systems or
control electromechanical devices such as motors, servos, lighting, or other
hardware.
Other physical computing implementations work with voice recognition,
which captures and interpret sound waves through microphones or other
devices, audio wave detection devices, also computer vision, which applies
algorithms to videos detected by some type of camera. Tactile interfaces are
also an example of physical computing.
Prototyping (creating quick assemblies with the help of a protoboard and
basic electronics components) plays an important role in physical computing.
Tools such as Arduino and Fritzing are useful for designers, artists, students,
and hobbyists because they help to make prototypes quickly.
Free Software
Free software is software that is distributed along with its source code and is
released under terms that guarantee users the freedom to study, adapt/modify,
and distribute the software. Free software is often developed in collaboration
between volunteer programmers as part of an open-source software
development project.
The Free Software Foundation considers software as free when it meets the
four types of freedom for users:
Freedom 0: The freedom to run the program, for any purpose;
Freedom 1: The freedom to study the software;
Freedom 2: The freedom to redistribute copies of the program so
that you can help your neighbor;
Freedom 3: Freedom to modify the program and distribute these
modifications so that the entire community benefits.
The users of this type of software are free because they do not need to ask
permission and are not bound by restrictive proprietary licenses. The Open
Source Initiative (OSI) is an organization dedicated to promoting open-source
or free software. It was created to encourage a rapprochement of commercial
entities with free software. Its main performance is to certify which licenses
fit as free software licenses, software, and its technological and economic
advantages.
Free software, although this name is also sometimes confused with "free"
because of the ambiguity of the term "free," so "free software" and "logical
free" are also used) It is the name of the software that respects the freedom of
the users on their acquired product and, therefore, once obtained, it can be
used, copied, studied, modified, and redistributed freely. According to the
Free Software Foundation, free software refers to the freedom of users to
execute, copy, distribute, study, modify the software, and distribute it
modified.
OSI, like many community members, believes that software is first and
foremost a tool and that the merit of this tool should be judged based on
technical criteria. For them, free software, in the long run, is economically
more efficient and of better quality and should, therefore, be encouraged. In
addition, the participation of companies in the free software ecosystem is
considered fundamental because they are the companies that enable the
increase in the development, implementation, and use of free software.
Arduino
Arduino is an open electronics platform for prototyping based on free,
flexible, and easy-to-use software and hardware. It was developed for artists,
designers, hobbyists, and anyone interested in creating objects or interactive
environments. The Arduino can acquire environmental information through
its input pins, for which a complete range of sensors can be used. On the
other hand, Arduino can act in the environment by controlling lights, motors,
or other actuators.
The fields of action for the control of systems are immense, being able to
have applications in the area of 3D printing, robotics, transport engineering,
agronomic engineering, musical engineering, fashion, and many others. The
microcontroller of the Arduino board is programmed using the Arduino
programming language, based on Wiring, and the development environment
(IDE) is based on Processing.
The projects developed with Arduino can be run even without the need to be
connected to a computer, although they can also be done by communicating
with different types of software (such as Flash, Processing, or MaxMSP).
Plates can be handmade or purchased assembled from the factory.
You can download the software that can be done for free, and the board
designs are available under an open license, so you are also free to adapt it to
your needs.
Processing
Processing is an open-source programming language, and integrated
development environment (IDE) built for the electronic arts and communities
of visual projects to teach basic notions of computer programming in a visual
context. The project was initiated in 2001 by Casey Reas and Ben Fry, both
former members of the MIT Media Lab Computing Group. One of the
objectives of Processing is to act as a tool for nonprogrammers initiated with
programming, through immediate satisfaction with visual feedback.
Fritzing
Fritzing is an open-source electronic design automation program designed to
help designers and artists move from prototypes (using, for example, test
boards) to final products. Fritzing was created under the principles of
Processing and Arduino and allows designers, artists, researchers, and
amateurs to document your Arduino-based prototype and create printed
circuit diagrams for later manufacturing. Besides.., it has a complementary
website that helps share and discuss projects, experiences, and reduce
manufacturing costs.
Chapter 2
Electronics
From the beginning of this chapter, you will find out about the technical
terms that electronics have and that at the end of this one, you will most
likely manage expertly.
Concept of Electronics
In a broader definition, we can say that electronics is the branch of science
that studies the use of circuits formed by electrical and electronic
components, with the main objective of representing, storing, transmitting, or
processing information beyond the control of processes and
servomechanisms.
From this point of view, it can also be said that the internal circuits of the
computers, telecommunications systems, the various types of sensors and
transducers are all within the area of interest of electronics. It is divided into
analog and digital because its work coordinates choose to obey.
These two forms of presentation of the electrical signals to be treated. It is
also considered to be a branch of electricity, which, in turn, is a branch of
physics where the phenomena of the charges are studied - elementary
electrical power, the properties, and the behavior of the electron, photons,
elementary particles, electromagnetic waves, etc.
It studies and uses systems whose operation is based on the conduction and
control of the flow of electrons or other electrically charged particles. The
design and large construction of electronic circuits to solve practical
problems are part of electronics and the fields of electronic,
electromechanical, and computer engineering in the design of software for
their control.
Electronics currently develops a wide variety of tasks. The main uses of
electronic circuits are control, processing, distribution of information,
conversion, and distribution of electrical energy. These two uses involve the
creation or detection of electromagnetic fields and electric currents. Look
around the radio, TV, PC, mobile phone, washing machine, all of them have
electronics.
Voltage
Electric voltage, also known as the potential difference (DDP) or voltage, is
the difference in electrical potential between two points or the difference in
potential electrical energy per electric charge unit between two points. Its unit
of measure is the volt or joules by coulomb. The potential difference is equal
to the work that must be done per unit of load against an electric field to
move any load.
It is a physical quantity that drives electrons along a conductor (for example,
a cable) in a closed electrical circuit, causing the flow of an electric current.
Its unit is Volt (V). The instrument used to measure the voltage is known as a
voltmeter.
A voltmeter can be used to measure the potential difference between two
points in a system, and usually, a common reference point is earth. Fields can
cause electrical voltage by an electric current under the action of a magnetic
field by a variant magnetic field or a combination of the three.
Electric Current
Electric current is the orderly flow of electrically charged particles, or also
the displacement of loads within a conductor when there is an electrical
potential difference between the ends. The standard unit in the International
System of Units for measuring current intensity is ampere. To measure the
current, you can use an ammeter. An electric current, since it is electric, this
is a phenomenon that can be used as an electromagnet, being this the
principle of operation of a motor.
The instrument used to measure the intensity of the electric current is the
galvanometer, which, calibrated in amps, is called an ammeter placed in
series with the conductor whose intensity you want to measure.
Direct Current
Direct current, direct current, galvanic current, or direct current (DC) is the
orderly flow of electrons in one direction at a time. This type of current is
generated by car or motorcycle batteries (6, 12 or 24V), small batteries
(usually 9V), batteries (1.2V and 1.5V), dynamos, solar cells and power
supplies of various technologies, which rectify the alternating current to
produce direct current.
It is the continuous flow of electrons through a conductor between two points
of different potential. In the direct current, the electric charges always
circulate in the same direction. It is continuing the current still maintains the
same polarity. In the systematic American standard, the color black
corresponds to the negative and the red to the positive or is symbolized for
the positive with VCC, +, VSS, and for the negative with 0V, -, GND.
It has usually used for powering electronic devices (between 1.2 V and 24V)
and digital circuits of computer equipment (computers, modems, hubs, etc.).
This type of circuit has a negative pole and a positive pole (is polarized),
whose intensity is maintained. More correctly, the intensity increases at the
beginning to a maximum point, remaining continuous, that is, without
changing. When turned off, it decreases to zero and extinguishes.
Many devices need direct current to operate on all those that carry electronics
(audiovisual equipment, computers, etc.). For this purpose, power supplies
are used. You can find it in the batteries, batteries, output of the computer
chargers.
Alternate Current
Alternating current (AC) is an electrical current whose direction varies in
time, as opposed to the following of the direct current whose direction
remains constant over time. The usual waveform in an AC power is
sinusoidal for to be the most efficient form of energy transmission. However,
in specific applications, different waveforms are used, such as triangular or
square waves. While the direct current source consists of the positive and
negative poles of an alternating current is composed of phases (and often
neutral wire).
It is the electric current in which the magnitude and direction vary cyclically.
The most commonly used alternating current waveform is that of a sine wave.
The AC voltage is what reaches the electrical outlets of homes and
businesses, and it is very common to find it in the sockets where our
appliances are connected. However, audio and radio signals transmitted by
electric cables are also examples of alternating current. In these uses, the
most important purpose is usually the transmission and retrieval of the
information encoded (or modulated) on the AC signal.
Resistance
Electrical resistance is the capacity of a body to oppose the passage of
electric current even when there is a difference of applied potential. It is
measured in ohms (Ω).
Resistors are components whose purpose is to offer opposition to the passage
of electric current through its material. We call this opposition electrical
resistance. They cause a voltage drop in the power supply to a power supply
unit may be limited to some part of an electrical circuit, but it will never
cause an electric current drop, even though the current is limited.
This means that the electrical current entering one resistor terminal will be
exactly the same as that of leaving the other terminal, but there is a voltage
drop. Using this, it is possible to use the resistors to control the voltage on the
desired components. You can find resistance in electric heaters, electronic
cards, stoves are very useful to limit the passage of current.
Ohm's Law
Ohm's Law states that the current (I) circulating through a given circuit is
directly proportional to the applied voltage (V) and inversely proportional to
its resistance (R).
The pyramid on the side is very useful to know this formula. For example,
cover with one finger the letter V (voltage), then the voltage will be equal to
the current (I) times the resistance (R). Or, to calculate the resistance, divide
the voltage (V) by the current (I).
Electronic Systems
An electronic system is a set of circuits that interact with each other to obtain
a result. One way of understanding electronic systems is to divide them into
inputs, outputs, and signal processing.
Inputs
Inputs are electronic or mechanical sensors that take signals (in the form of
temperature, pressure, humidity, contact, light, motion, pH, etc.) from the
physical world and convert them into current or voltage signals. Examples of
inputs are gas sensors, temperature sensors, pulsators, photocells,
potentiometers, motion sensors, and many more.
Outputs
Outputs are actuators or other devices that convert current or voltage signals
into physically useful signals such as motion, light, sound, force, or rotation,
among others. Examples of outputs are motors, LEDs, or light systems that
switch on automatically when darkens or a buzzer that generates several
tones.
Signal Processing
Signal processing is carried out using circuits known as microcontrollers.
These are integrated circuits built to manipulate, interpret, and transform
voltage and current signals coming from sensors (inputs) and to activate
certain actions in the outputs.
Electronic Signals
The inputs and outputs of an electronic system will be considered as variable
signals. In electronics, we work with variables that are taken in the form of
voltage or current, which can simply be called signals. The signals can be of
two types: digital or analog.
Digital Variable
Also called discrete variables are characterized by having two different states
and, therefore, can also be called binary (in logic would be True (V) and
False (F) values, or could be 1 or 0 respectively). An example of a digital
signal is the bell switch of your house because it has only two states, pulsed
and pulseless.
Analog Variable
They are those that can take an infinite number of values comprised between
two limits. Most real-life phenomena are signals of this type (sound,
temperature, brightness, etc.).
An example of an analog electronic system is that of a speaker, who is
concerned with amplifying the sound of his voice so that a large audience can
hear it. The sound waves that are analog in their origin are captured by a
microphone and converted into a small analog voltage variation, called an
audio signal.
Voltage Divider
In electronics, the voltage divider rule is a design technique used to create a
voltage (Volt) that is proportional to the other (Vin). In this way, the voltage
of a source is distributed among one or more resistors connected in series. On
a circuit like this, two resistors are connected in series as in the following
diagram:
The output voltage, Volt, is given by the formula:
This way, we can obtain any fraction between 0 and 1 of the Vin voltage.
Electronic Components
Microcontroller
A microcontroller is a programmable integrated circuit capable of to execute
the orders recorded in his memory. A microcontroller has inside it three main
functional units: central processing unit, memory, input, and output
peripherals.
The microcontrollers are different from the processors because, besides the
logical components and usual arithmetic of a general-purpose
microprocessor, the microcontroller integrates additional elements into its
internal structure, such as memory read and write for data storage, read-only
memory for storage of programs, EEPROMs for permanent data storage,
peripheral devices such as analog / digital converters (ADC), digital-to-
analog (DAC) converters in some cases; and, data input and output interfaces.
They are generally used in automation and control of products and
peripherals, such as automotive engine control systems, remote controls,
office and residential machines, toys, supervisory systems, etc. By reducing
the size, cost, and energy consumption, and when compared to the way of the
use of conventional microprocessors, allied to the ease of application design,
along with its low price, the microcontrollers are an efficient alternative for
controlling many processes and applications.
Protoboard
It is a reusable board used to build prototypes of seamless electronic circuits.
A protoboard is made of perforated plastic blocks and several thin sheets of
copper, tin, and phosphorus alloy.
Resistor
It is a component formed by carbon and other resistant elements used to limit
the electric current in a circuit. It opposes the passage of the current. The
maximum current in a resistor is conditioned by the maximum power that can
dissipate your body. This power can be visually identified from the diameter
without another indication being necessary. The most common values are
0.25 W, 0.5 W, and 1 W.
Due to their very small size, it is not possible to print their respective resistors
on the resistors. The color-coding was then chosen, which consists of colored
stripes on the resistor body indicated as a, b, c, and % tolerance. The first
three ranges are used to indicate the nominal value of its resistance and the
last range, the percentage by which the resistance can vary its nominal value,
according to the following equation:
R = (10a + b) x 10c ± % of tolerance
The value of the electrical resistance is obtained by reading the figures as a
one, two, or three-digit number; it is multiplied by the multiplier, and the
result is obtained in Ohms (Ω).
Thermistor
The NTC (Negative Temperature Coefficient) thermistor is a temperature-
sensitive semiconductor electronic component used for control, measurement,
or polarization of electronic circuits. It has a coefficient of resistance
variation that varies negatively as the temperature increases, i.e., its electrical
resistance decreases with increasing temperature.
Diode
It is the simplest type of semiconductor electronic component. It is a
component that allows the chain to cross only in one direction.
Transistor
It is mainly used as an amplifier, an electrical signal switch, and an electric
rectifier in a circuit. The term comes from the English transfer resistor
(resistor/ transfer resistance), as its inventors knew it.
The process of resistance transfer in the case of an analog circuit, it means
that the characteristic impedance of the component varies upwards or
downwards from the pre-assigned polarization.
Thanks to this function, the electrical current passing between collector (C),
base (B), and emitter (E) of the transistor varies within specific pre-set
parameters and processes the signal amplification.
The term "amplify" means the procedure for making a weaker electrical
signal on a stronger one. A low-intensity electrical signal, such as the signal
generated by a microphone, is injected into an electronic circuit
(transistorized, for example), whose main function is to transform this weak
signal generated by the microphone into electrical signals with them.
This whole process is called signal gain. Nowadays, transistors are found in
all appliances for household and everyday use: radios, televisions, recorders,
stereos, microwaves, washing machines, cars, calculators, printers, mobile
phones, etc.
Capacitor
The capacitor is an electrical device capable of storing electrical charges. In
electronic circuits, some components require DC power, while the power
supply is connected to AC power. Solving this problem is one example of the
usefulness of a capacitor.
This element is capable of storing electrical potential energy during a time
interval and is constructed using a uniform electrical field. A capacitor
consists of two conductive parts, called armatures and insulating material
with specific properties called the dielectric.
LED
The LED (Light Emitting Diode) is a diode that emits light when energized.
LEDs have many advantages over incandescent light sources such as lower
energy consumption, longer lifetime, smaller size, exceptional durability, and
reliability. The LED has a polarity, an order of connection. Connecting it
upside down will not work correctly. Check the drawings for a match
between the negative and the positive.
They are mainly used in microelectronic products, such as a warning signal.
It is also widely used in panels, curtains, and led tracks. They can be found in
larger sizes, such as some models of traffic lights or displays.
RGB LED
An RGB LED is an LED that incorporates in a single package three LEDs,
one red, one green, and one red, blue. In this way, it is possible to form
thousands of colors by adjusting each color individually. The three LED's are
joined by a negative or cathode.
LCD
A liquid crystal display, or LCD (liquid crystal display), is a thin panel used
to display information by electronic means, such as text, images, and videos.
An LCD consists of an electrically controlled light polarizing liquid that is
compressed into cells between two transparent polarizing blades. Its main
features are lightness and portability. Its low power consumption allows it to
be used in portable equipment, powered by electronic battery.
An LCD can vary the number of lines and characters per line, the color of the
characters, and the background color, as well as having or not backlighting.
The models with backlight have better visualization.
Button
A button, or push button, is used to activate some function. The buttons are
usually activated by pressing them. A button on an electronic device often
functions as an electrical switch. There are two contacts inside, and if it is a
normally closed or normally open device, pressing the button will activate the
opposite function to the one currently being performed.
Reed Switch
It is an electrical switch activated by a magnetic field, for example, with a
magnet. When the contacts are open, they close in the presence of a magnetic
field. When they're closed, they open.
It is commonly used in the door and window sensors for anti-theft alarms.
The magnet is attached to the door and the reed switch to the stop.
Potentiometer
A potentiometer is a resistance whose value is variable. In this way,
indirectly, you can control the current intensity that flows through a circuit if
it is connected in parallel, or control the voltage by connecting it in series.
They are suitable for use as a control element in electronic devices. You can
activate it to vary the normal operating parameters. An example is the volume
button of a radio.
Photocell
The LDR (Light Dependent Resistor) is a resistance whose value in ohms
varies according to the incident light. A photocell has a low resistance value
in the presence of light and a high value in its absence.
It can be found in various consumer goods, such as cameras, light meters,
radio clocks, security alarms, or public lighting systems.
Piezoelectric Transducer
A piezoelectric transducer is efficient for detecting vibrations or blows. It can
be used as a sensor by reading the output voltage. This electroacoustic
transducer can also be used as a small buzzer to produce a continuous or
intermittent sound or buzz.
DC Motor
The direct current (DC) motor is a machine that converts electrical energy
into mechanical energy, causing a rotary motion. This direct current machine
is one of the most versatile. Its easy control of position, pause, and speed
makes it one of the best options in process control and automation
applications. For example, you can find yourself in the traction of battery-
powered toy cars or on the wheels of a robot.
Relay
It is an electromechanical switch used to turn devices on or off. When a
current circulates through the internal coil, it creates a magnetic field that
attracts one or a series of contacts by the closing or opening circuits. When
the coil current ceases, the magnetic field also ceases, causing the
connections to return to their original position.
Chapter 4
Arduino Programming
Arduino Family
Over the years, the Arduino line has been growing more and more and
bringing solutions to the most diverse projects.
Shields for Arduino
A shield is a board that allows you to expand the original features of Arduino.
Some examples:
Arduino IDE for Windows
Arduino board and a USB AB cable
This lesson will help you install Arduino Uno, Arduino Duemilanove, Nano,
Arduino Mega 2560, or Diecimila boards. For other boards of the Arduino
line, you should look for the corresponding lesson. You will also need a USB
AB cable.
Download Arduino Software
Download the latest version of the Arduino software. When finished, unzip
the file and maintain the folder and subfolder structure. If you want to save
this folder in the C: drive of your computer. Inside this folder, there is a file
called arduino.exe, which is the entry point of the Arduino program, the IDE
(Integrated Development Environment).
Connecting Arduino
The isolated Arduino Uno uses power from the computer via the USB
connection; no external power is required. Connect the Arduino card to the
computer using the USB AB cable. The green power LED (PWR) should
light up.
Installing drivers
Drivers for Arduino Uno or Arduino Mega 2560 with Windows 7, Vista or
XP:
Connect the card to the computer and wait for Windows to start
the driver installation process. After a few moments, the process
will fail. Click finish and dismiss the wizard's help.
Click on the Main Menu and open the Control Panel.
Within the Control Panel, navigate to System and Security. Then
click System, select Hardware, and then click Device Manager.
Search for Ports (COM & LPT), where you should see an
Arduino UNO option (COMxx).
Right-click on Arduino UNO (COMxx) and choose the Update
Driver option.
Then choose the Install option from a specific list or location
(Advanced) and click move forward.
Finally, browse and choose the Arduino.inf driver located in the
Drivers folder of the Arduino software you downloaded.
Windows will finish installing the driver from this point.
Programming
Programming is a great resource that allows us to create several sequences of
logical steps to meet our needs and those of our systems. Programming is an
art that requires excellent logical skill and concentration on the part of the
programmer.
Programming Concept
It is the process of designing, writing, proving, debugging, and maintaining
the source code of computer programs. The source code is written in a
programming language. The purpose of programming is to create programs
that perform the desired behavior.
The process of writing code often requires knowledge in several different
areas, in addition to the domain of the language to be used, specialized
algorithms, and formal logic. Scheduling encompasses areas such as
application analysis and design.
To create a program that the computer interprets and executes the written
instructions, a programming language must be used. In the beginning,
computers interpreted only instructions in a specific language, a low-level
programming language known as machine code, which was too complicated
to program. It consists exclusively of number strings 1 and 0 (binary system).
To facilitate the programming work, the first scientists who worked in the
area decided to replace the instructions, sequences of one and zero, by
English words or letters, encoding and creating a higher level language
known as Assembly. For example, to add up, you use the English letter A
add. Actually, writing in assembly language is basically the same as with
machine language, but letters and words are easier to remember and
understand than sequences of binary numbers.
As the complexity of the tasks performed by computers increased, it was
necessary to develop a simpler method of programming. Then the high-level
languages were created. While a task as simple as multiplying two numbers
requires a set of assembly language instructions, in a high-level language, one
is sufficient.
Programming Language
A programming language is an artificial language developed to express
operations that can be performed by machines such as computers. They can
be used to create programs that control the physical and logical behavior of a
device, to express algorithms accurately, or as a mode of communication
between people.
It consists of a set of symbols and syntactic and semantic rules that define its
structure and the meaning of its elements and expressions.
The process by which the source code of a computer program is written,
tested, debugged, compiled, and maintained is called programming.
Machine Language
A code system directly interpretable by a micro programmable circuit, such
as a computer microprocessor or a microcontroller. A machine code program
consists of a sequence of numbers that mean a sequence of instructions to be
executed.
The machine language works with two voltage levels. Such levels, by
abstraction, are symbolized by zero (0) and one (1), so the machine language
only uses these signs.
Computer programs are rarely created in machine language but must be
translated (by compilers) to be run directly by the computer.
There is currently a fashionable option of not running them directly, but using
an interpreter, this one running directly on machine code and previously
compiled.
Assembly Language
It is a low-level programming language for computers, microcontrollers, and
other programmable integrated circuits. Machine language, which is a mere
bit pattern, becomes readable by replacing the raw values with symbols called
mnemonics. These symbols are generally defined by the hardware
manufacturer and are based on codes that symbolize the processing steps (the
instructions).
An assembly language is therefore specific to each computer architecture and
can only be used by a specific microprocessor. This contrasts with most high-
level programming languages that are ideally portable, which means that a
program can run on a variety of computers.
High-Level Language
The high-level programming language is what is called, in Computer Science
of programming languages, a language with a relatively high level of
abstraction.
Far from the machine code and closer to human language, high-level
languages are not directly related to computer architecture.
The programmer of a high-level language does not need to know processor
features such as instructions and registers. These characteristics are abstracted
in a high-level language.
For these languages, a certain amount of programming knowledge is required
to perform sequences of logical instructions. High-level languages were
created so that the average user could solve a data processing problem more
easily and quickly.
Algorithm
An algorithm is a finite sequence of well-defined and unambiguous
instructions, each of which can be performed mechanically over a finite
period and with a finite amount of effort.
The concept of algorithm is often illustrated by the example of a cooking
recipe, although many algorithms are more complex. They may repeat steps
(making iterations) or need decisions (such as comparisons or logic) until the
task is completed. An algorithm does not necessarily represent a computer
program, but the steps necessary to perform a task. Its implementation can be
done by a computer, by another type of automaton, or even by a human
being.
Arduino Software
To run the program, we enter the Arduino folder stored on the computer and
look for the icon. Double-click to open the program.
The Arduino program is also known as the Arduino IDE (Integrated
Development Environment) because besides the programming environment,
it also consists of a code editor, a compiler, and a debugger.
Sketches
Software written using Arduino is called Sketches. These Sketches are
written in the text editor of the Arduino IDE and are saved with the .ino file
extension. This editor has cut/paste and fetch/replace text features. The
message area gives feedback when saving and exporting files and also
displays error information when compiling Sketches. The lower right corner
of the window displays the current card and the serial port. The toolbar
buttons let you check, load, create, open, and save Sketches or open the serial
monitor.
Note: In IDE versions before 1.0 Sketches are saved with the .pde extension.
It is possible to open these files with version 1.0, but you will be asked to
save Sketch with the .ino extension.
Serial Monitor
Displays serial data being sent from the Arduino card to the computer. To
send data to the card, enter the text and click the "send" button or press enter.
Communication between the Arduino board and your computer can take
place at several predefined standard speeds. For this to happen, it is important
to set the same speed in both Sketch and Serial Monitor.
In Sketch, this choice is made through the Serial. Begin function. And in the
Serial Monitor via the drop-down menu in the lower right corner.
Note that on Mac or Linux, the Arduino card will reset (re-run your Sketch
from the beginning) when you open the serial monitor.
Serial communication with the Arduino board can also be done through other
programming languages such as Processing, Flash, Python, MaxMSP, and
many others.
Arduino Library
The Arduino environment can be extended through the use of libraries, as can
most programming platforms. Libraries provide extra functionality for use in
sketches. For example, to work with hardware or data manipulation.
Some libraries are already installed with the Arduino IDE, but you can also
download or create your own.
To use a library in a sketch, select in your Arduino IDE: Sketch>Import
Library.
Included in the programming is the functionality of an existing library from
the command:
#include < LiquidCrystal.h>
Programming Arduino
Arduino is programmed in a high-level language similar to C/C++ and
usually has the following components to elaborate the algorithm:
Structures
Variables
Boolean, comparison and arithmetic operators
Control Structure
Digital and analog functions
For more details, visit the see the extended reference to more advanced
features of the Arduino language and the libraries page for interaction with
specific types of hardware on the official Arduino website.
Structures
These are two main functions that every program in Arduino must-have.
The setup() function is called when a program starts running. Use this
function to initialize your variables, pin modes, declare the use of bookstores,
etc. This function will be performed once after the Arduino board is turned
on or reset.
setup(){
}
After creating a setup() function that declares the initial values, the loop()
function does exactly what its name suggests, goes into looping (it always
executes the same block of code), allowing your program to make changes
and respond. Use this function to control the Arduino board actively.
loop(){
}
Variables
Variables are expressions that you can use in programs to store values such as
reading from a sensor on an analog pin. Here we highlight some:
Boolean Variables
A data type that occupies 1 byte of memory and stores the value of an
ASCII character. Literal characters are written in quotation marks.
char myChar = 'A';
Boolean Operators
These operators can be used within the condition in an if sentence.
&& ("and" logical)
True only if the two operands are true, that is, the first condition and
the second condition are true. Example
if (digitalRead(2) == 1&& digitalRead(3) == 1) { // read two
switches
// ...
}
is only true if both switches are closed.
|| ("or" logical)
- (subtraction)
* (multiplication)
/ (business area)
% (rest of the division)
Control Structures
These are instructions that allow you to decide and perform several
repetitions according to certain parameters. Among the most important we
can highlight:
Switch/Case
Like if sentences, switch/case-control the flow of programs. Switch/case
allows the programmer to construct a list of "cases" within a key-delimited
block. The program checks each case with the test variable and executes the
code if it finds an identical value.
switch (var) { case 1:
//do something when var == 1 case 2:
//do something when var == 2 default:
// if no value is identical, make the default
// default is optional
}
While
While it will cause the code block between keys to repeat continuously and
indefinitely until the expression between parentheses () becomes false.
Something has to cause a change in the value of the variable being checked,
or the code will always be turning around inside the while. This could be the
increment of a variable or an external condition, such as testing a sensor.
var = 0;
while(var < 200){
// some code that repeats 200 times var++;
}
For
The sentence is used to repeat a key-delimited code block. An increment
counter is normally used to control and finalize the loop. The for sentence is
useful for any repetitive operation, and is often used with arrays to operate on
data sets or pins.
// Increase the brightness of an LED using an int PWM pin PWMpin =
13; // an LED on pin 13
void setup()
{
// no setup required
}
void loop()
{
for (int i=0; i <= 255; i++){ analogWrite(PWMpin, i); delay(10);
}
}
Digital Functions
Oriented to review the status and configuration of digital inputs and outputs.
pinMode()
Sets the specified pin to behave either as an input or output.
Syntax:
pinMode(pin, mode)
pinMode(9, OUTPUT); // determines digital pin 9 as an output.
digitalRead()
Reads the value of a specified digital pin, HIGH or LOW. Syntax:
digitalRead(pin)
buttonState = digitalRead(9); // Reading the status of a button on pin
9.
digitalWrite()
Write a HIGH or LOW value on a digital pin. Syntax:
digitalWrite(pin, value)
digitalWrite(9, HIGH); // Puts pin 9 into HIGH state.
Analog Functions
Ideal for reading or writing analog values.
analogRead()
It reads the value of a specified analog pin. The Arduino board contains a 10-
bit analog-to-digital converter with 6 channels. With this, it can map input
voltages between 0 and 5 volts to integer values between 0 and 1023. This
allows a resolution between readings of 5 volts / 1024 units or 0.0049 volts
(4.9 mV) per unit.
Syntax:
analogRead(pin)
int a = analogRead (A0); // Reads the value of analog pin A0 and stores
//this value in variable "a".
analogWrite()
Write an analog value (PWM wave) on a pin. It can be used to light an LED
by varying the brightness or rotate a variable speed motor.
Syntax:
analogWrite(pin, value)
analogWrite (9.134); // Sends the analog value 134 to pin 9.
Chapter 5
In this beginner Kit with Arduino Uno R3, you will explore lots of lessons. It
has everything you need to perform all the lessons in this chapter and to start
developing your own projects with the Arduino platform, without the need
for welding.
Lessons
Lessons developed as an example to use all the components of your Beginner
Kit with Arduino Uno R3. In each lesson, you identify the materials needed
for its execution, the previous knowledge needed, and what you will learn,
the assembly diagram, the programming code, tips, and extra exercises.
Hello World - Blinking
This example shows the most uncomplicated experience you can do with an
Arduino to check a physical output: blink an LED.
When you're learning how to program, in most programming languages, the
first code you write says "Hello World" on your computer screen. Since the
Arduino board does not have a display, we will replace this function by
flashing an LED.
Previous Knowledge
Digital Signal
DigitalWrite() function
The polarity of an LED (page 39)
Connecting the Arduino board to the computer
Required Materials
1 Arduino Uno1 LED
1 AB USB cable
This code already comes with the Arduino IDE. You can access in: Archive >
Examples > 01. Basics > Blink
We only reproduce here with explanations and comments.
In the following program, the first command is to initialize pin 13 as an
output through the line.
pinMode(13, OUTPUT);
In the main loop of the code, you turn on the LED with this command line:
digitalWrite(13, HIGH);
This command directs 5 volts to pin 13 and lights it up. You switch off the
LED with the following command:
digitalWrite(13, LOW);
This command removes the 5 volts from pin 13, returning to 0 and turning off
the LED. Between power off and on you need enough time for one person to
see the difference, so the delay() command tells Arduino not to do anything
for 1000 milliseconds, or one second. When you use the delay() command,
nothing else happens in this period. Once you have understood the basic
examples.
Source Code
/*
Blinking
Illuminates an LED for one second, and then goes out for the same time
repeatedly.
*/
// Sets a name for pin 13: int led = 13;
// It is executed each time Arduino starts: void setup () {
// Initializes the digital pin as output. pinMode (led, OUTPUT);
}
// The loop () function continues to perform while Arduino is powered,
// or until the reset button is pressed.
void loop () {
digitalWrite (led, HIGH); // Lights up the LED
delay (1000); // Wait one second (1s = 1000ms) digitalWrite (led,
LOW); // Turn off the LED
delay (1000); // Wait one second (1s = 1000ms)
}
Tips
1. In the Arduino // language it is used to add comments to the line of code,
being very useful to explain a syntax or leave a reminder. An example of its
use:
digitalWrite(13,LOW); //Deletes the LED
2. Digital signals (ON and OFF) are present in many sensors. Meet some of
them:
Infrared motion sensor
Sharp GP2Y0A41SK0F distance sensor - 4 to 30cm
Exercise 1
From the source code presented in this lesson, make the necessary
modifications to make the LED stay:
3 seconds on and 3 seconds off
200 milliseconds on and 500 milliseconds off
Exercise 2
From the same source code, make a new assembly of this lesson and make
the necessary modifications to the source code so that the LED is placed on
Pin 5 and is on for 2 seconds and off for 1 second.
Note that for any pin other than 13, it is necessary to place a resistor in series
with O LED, In this case, a resistor from 330Ω is sufficient.
Button
The button is a component that connects two points of the circuit when it is
pressed. In this example, when the button is pressed, the LED lights up.
What Will I Learn?
Wiring a circuit
Conditional if/else
Status of a button
Read a digital input and write a digital output
Previous Knowledge
Digital Signal
DigitalWrite() and digitalRead() function
Voltage divider
Conditional, Boolean and comparison operators
Required Materials
1 Arduino Uno
1 Button
1 LED
1 Resistor 10kΩ
1 AB USB cable Jumpers
1 Protoboard
Source Code
/*
Button
Turns on and off an LED connected to digital pin 13 when a button
connected to pin 2 is pressed.
The Circuit:
* LED connected to pin 13 and ground
* button connected to pin 2 from 5V
* 10K resistor connected to pin 2 from ground
*/
// constants are not changed.
// These are used here to define the pin numbers: const int buttonPin = 2;
// the pin number of the const int ledPin button = 13; // the pin number of
the LED pin
// variables that must change:
int buttonState = 0; // variable to read the state of the button
void setup () {
// initializes the LED pin as output: pinMode (ledPin, OUTPUT);
// initializes the button pin as input: pinMode (buttonPin, INPUT);
}
void loop () {
// reads the button value: buttonState = digitalRead (buttonPin);
// check if the button is pressed.
// if yes, buttonState and HIGH: if (buttonState == HIGH) {
// turn on the LED: digitalWrite (ledPin, HIGH);
}
else {
// turns off the LED: digitalWrite (ledPin, LOW);
}
}
Tips
1. When you are programming with the Arduino software, many of the words
you write are reserved for the language. These words are placed in a different
color, and it is a hint to check if they are written correctly. As in the example:
void loop(){ digitalWrite(13,HIGH); delay(1000);
digitalWrite(13,LOW); delay(1000);
}
2. In a project with the use of several buttons with different functionalities, it
can be useful to work with parts like these:
Colorful touch button set.
Exercise 1
To prevent accidents in the workplace, a safety rule in several industrial types
of equipment is to require a user to press two buttons, one with each hand, to
drive a machine. This is the case with the cutting machine used in paper
mills.
With the following assembly, we can simulate this situation. The LED only
illuminates if both circuit buttons are pressed:
Exercise 2
Make one more change to the source code of exercise 1 so that you can light
the LED on pin 13 by pressing either button 1 or button 2. When you stop
pressing, the LED goes out.
Previous Knowledge
Digital Signal
DigitalRead() and Serial.print function
DigitalWrite() function and comparison operators
Required Materials
1 Arduino Uno
1 Button
1 LED
1 Resistor 10kΩ
1 AB USB cable Jumpers
1 Protoboard
Source Code
In this program, the first thing you will do in the configuration function is to
start the serial communication at 9600 data bits per second between Arduino
and his computer: Serial.begin (9600);
Remember to place the value 9600 also in the Serial Monitor, as explained
earlier.
Then initialize the digital pin 2, the pin that will scan the button as a digital
input:
int pushButton = 2;
When the button is pressed, 5 volts will flow freely through its circuit, and
when not pressed, the input pin will be grounded. This is a digital input,
which means that the key can only have one state (seen by your Arduino as
"1", or HIGH) or an off state (seen by your Arduino as a "0", or LOW), with
nothing in between.
Now when you open your Serial Monitor in the Arduino environment you
will see a stream of "0". if your key is open, or "1" if your key is closed.
/*
DigitalReadSerial
Read the digital input on pin 2 and print the result on the serial monitor.
This example is a public domain.
*/
int pushButton = 2; // pin 2 has a button connected to it. int ledPin = 13;
// LED input on pin 13.
void setup () {
// Initialize serial communication at 9600 bits per second: Serial.begin
(9600);
pinMode (pushButton, INPUT); // define the button as an input.
pinMode (ledPin, OUTPUT); // set the LED as an output.
}
void loop () {
// reads the input pin:
int buttonState = digitalRead (pushButton); if (buttonState == 1) {
digitalWrite (ledPin, HIGH);
} else {digitalWrite (ledPin, LOW);
}
// prints the state of the button: Serial.println (buttonState);
delay (1); // Delay between readings (in milliseconds)
}
Tips
1. The binary system is a positional numbering system in which all quantities
are represented based on two numbers, i.e., zero and one (0 and 1).
Computers work internally with two voltage levels, so their natural
numbering system is the binary system (on, off).
The binary system is the basis for Boolean algebra that allows logical and
arithmetic operations using only two digits or two states (yes and no, false
and true, all or nothing, 1 or 0, on and off). All digital electronics and
computing are based on this binary system and Boole's logic, which allows
representing by digital electronic circuits (logical gates) the numbers,
characters, perform logical and arithmetic operations. Computer programs are
encoded in binary form and stored in media (memories, disks, etc.) under this
format.
2. To remember:
To read a digital signal use: digitalRead(numeroPin).
To write a digital signal use: digitalWrite(numeroPin, value).
A digital output or input is always HIGH or LOW.
Exercise 1
Here we will do one more exercise using the same assembly of this Lesson.
Once you have the button working, you often want to do some action based
on the number of times the button is pressed. To do this, you need to know
when the button changes from off to on, and count how many times this
change of state happens. This is called state change detection. Every 4 pulses,
the LED will turn on.
/*
Pulse counter (edge detection)
created on 9/27/2005, modified on 8/30/2011 by Tom Igoe. This
example is from the public domain.
http://arduino.cc/en/Lesson/ButtonStateChange
*/
// constants are not changed:
const int buttonPin = 2; // the pin number of the const int ledPin button =
13; // the number of the LED pin
// variables that must change:
int buttonPushCounter = 0; // counter for the number of prints of the int
button buttonState = 0; // current status of the button
int lastButtonState = 0; // previous button state
void setup () {
pinMode (buttonPin, INPUT); // initialize the button pin as input
pinMode (ledPin, OUTPUT); // initialize the digital pin as output
Serial.begin (9600); // initialize the serial communication
}
void loop () {
// reads the button value: buttonState = digitalRead (buttonPin);
// compare the current state of the button with its previous state if
(buttonState! = lastButtonState) {
// if the button status has been changed, increment the if counter
(buttonState == HIGH) {
buttonPushCounter ++; Serial.print ("number of pulses:"); Serial.println
(buttonPushCounter);
}
}
// saves the current state of the button as the last state to start the
// next loop
lastButtonState = buttonState;
// Turn on the LED every 4 pulses by checking the if button counter
module (buttonPushCounter% 4 == 0) {
digitalWrite (ledPin, HIGH);
It is {digitalWrite (ledPin, LOW);
}
}
Previous Knowledge
Analog signal
Function analogRead() and Serial.print
Required Materials
1 Arduino Uno
1 LED
1 Resistor 330Ω
1 Potentiometer
1 AB USB cable Jumpers
1 Protoboard
Source Code
/*
Analog Input, Analog Output, Serial Output
Read the analog input pin, map the result to a range between 0 and 255,
and use the result to establish the PWM pulse of the output pin.
It is also possible to follow the result through the Serial Monitor.
The circuit:
- The central pin of the potentiometer connected to the analog pin 0. The
side pins of the Potentiometer connected to ground and 5V.
- LED connected to digital pin 9 and ground.
Created on 29/12/2008, Modified on 04/04/2012 by Tom Igoe
This example is a public domain.
*/
// constants are not changed:
const int analogInPin = A0; // Potentiometer analog input
const int analogOutPin = 9; // Analog output where the LED is
connected
int sensorValue = 0; // potentiometer reading
int outputValue = 0; // PWM output reading (analog)
void setup () {
// Initialize serial communication: Serial.begin (9600);
}
void loop () {
// sensorValue = analogRead (analogInPin);
// maps the result of the analog input within the range of 0 to 255:
outputValue = map (sensorValue, 0, 1023, 0, 255);
// changes the value of the analog output: analogWrite (analogOutPin,
outputValue);
// prints the result on the serial monitor: Serial.print ("sensor =");
Serial.print (sensorValue); Serial.print ("\ t output ="); Serial.println
(outputValue);
// Wait 2 milliseconds before the next loop: delay (2);
}
Tips
1. Note that the analog inputs of Arduino have a resolution of 10 bits (values
from 0 to 1023), but the analog outputs by PWM have a resolution of 8 bits
(values from 0 to 1023).
255). This is why you need the 'map' function to 'map' the values so that they
remain proportional.
2. Other elements that are also potentiometers:
Force-sensitive resistor 0.5".
Square force sensitive resistor.
Previous Knowledge
Boolean Variables
Serial.print
Required Materials
1 Arduino Uno
2 LEDs
1 Resistor 330Ω
1 Relay
1 AB USB cable Jumpers
1 Protoboard
Source Code
// ************************************************
**************************
// * Code for testing Arduino Multilogic triggering relay kit,
// * connected to digital output 2 and GND, monitored by LED 13
// * this code has public domain
// ************************************************
**************************
// initialize a char type variable that uses 1 byte to store
// 1 character char input = 0; int rele = 2; int led = 13;
boolean y = true; // initializes a boolean type variable
void setup () {pinMode (relay, OUTPUT); pinMode (led, OUTPUT);
Serial.Begin (9600); Serial.println ();
Serial.print ("** Code to trigger relay connected to Arduino pin 2");
Serial.println ("via serial monitor **");
Serial.println ("");
Serial.println ("Press 1 and then ENTER to invert the relay state again");
Serial.println ("Awaiting command:");
}
void loop () {
if (Serial.available ()> 0) {input = Serial.read ();
if (input == '1') {
Serial.print ("The re-read is now");
if (y) {
digitalWrite (relay, HIGH); digitalWrite (led, HIGH); Serial.println
("on");
}
else {
digitalWrite (relay, LOW); digitalWrite (led, LOW); Serial.println
("off");
}
y =! y; // alters or value of y, le and e equal to not
}
else {
Serial.println ("Invalid command");
}
}
}
Fade
This example demonstrates the use of the analogWrite() function to turn off a
fade LED. AnalogWrite uses a PWM pulse, switching the digital pin on and
off quickly, creating a fade effect.
What Will You Learn?
Switching a faded LED on and off
Intensify the concept of PWM
Previous Knowledge
PWM
AnalogWrite() function
The polarity of an LED
Increase and manipulate variables
Required Materials
1 Arduino Uno
1 LED
1 Resistor 330Ω
1 AB USB cable Jumpers
1 Protoboard
Source Code
/*
Fade
This example shows how to perform a fade on an LED on pin 9 using
the analogWrite() function.
This example is a public domain
*/
int led = 9; // LED pin
int brightness = 0; // LED brightness intensity
int fadeAmount = 5; // on how many points to apply the fade on the LED
void setup () {
// sets pin 9 as output:
pinMode (led, OUTPUT);
}
// the loop runs in sequence continuously: void loop () {
// sets the brightness of pin 9:
analogWrite (led, brightness);
// changes the brightness for the next loop: brightness = brightness +
fadeAmount;
// reverses the direction of the fade at the end of the fade:
if (brightness == 0 || brightness == 255) {fadeAmount = -fadeAmount;
}
// wait 3
0 milliseconds to see the dimmer effect: delay (30);
}
Tips
Connect the most extended leg of the LED to the digital pin 9 of your
Arduino via a
330Ω. Connect the shortest leg of the LED directly to the ground.
After defining that pin 9 will be your ledPin, nothing more should be done in
the setup() function of the code.
The analogWrite() function that you will use in the main loop of the code
requires two arguments: one telling the function which pin to trigger and the
other indicating which PWM value to use.
To run the fade on the LED, gradually increase the PWM value from 0
(entirely off) to 255 (fully on) and then decrease again to 0 to complete the
cycle. In the code below, the PWM value is set using a variable called
brightness. Each time the loop rotates, it increases the value of the variable
according to the fadeAmount.
If brightness is set between the extreme values (0 or 255), then fadeAmount
changes to its negative. For example, if fadeAmount is 5, then it is set to -5.
If it is -5, then it would be set to 5. The next time you rotate the loop, this
change causes the brightness increment also to change direction.
analogWrite() can change the PWM value very quickly, so the delay at the
end of the code controls the fade speed. Try to modify the delay value and
see how this changes the program.
Loop
Many times you want to repeat an action on a series of pins and do something
different for each one. In this case, the example flashes 6 LEDs using the
for() loop function to circulate back and forth between pins 2 and 7. The
LEDs turn on and off in sequence, using both the digitalWrite() and delay()
functions.
We can call this example "Super Machine" by recalling the television series
of the 80s in which the famous actor David Hasselhoff directed his Pontiac
with artificial intelligence. The car was turbocharged with various LEDs of
various possible sizes to reproduce bright effects.
We thought it would be interesting to use this metaphor of the "Super
Machine" to learn more about sequential programming and good
programming techniques for the I/O information on the board.
What Will You Learn?
for() loop function
digitalWrite()
delay()
Required Materials
1 Arduino Uno6 LEDs
1 ABJumpers USB cable
6 Resistors 330Ω
Source Code
The code below starts using the for() loop function to designate digital pins 2
to 7 as outputs of the 6 LEDs used. In the main loop of the code, two for()
loops are used to increase the loop by going through the LEDs, one by one,
from pin 2 to pin 7. Once pin 7 is lit, the process reverses, going back through
each LED.
For more information on the for() function, see page 82.
/*
Loop
Demonstrates the use of the for () loop function.
It lights up several LEDs in sequence, and then the coating.
The circuit:
* LEDs between pins 2 to 7 and ground
Created in 2006 by David A. Mellis
Modified on August 30, 2011, by Tom Igoe
This code is a public domain. http://www.arduino.cc/en/Lesson/ForLoop
*/
int timer = 100; // The higher the value, the slower the sequence of
LEDs. void setup () {
// Use for loop to initialize each pin as output: for (int thisPin = 2;
thisPin <8; thisPin ++) {
pinMode (thisPin, OUTPUT);
}
}
void loop () {
// loop from lowest to highest pin: for (int thisPin = 2; thisPin <8; thisPin
++) {
// Connect this pin: digitalWrite (thisPin, HIGH); delay (timer);
// turns off this pin: digitalWrite (thisPin, LOW);
}
// loop from highest to lowest pin: for (int thisPin = 7; thisPin> = 2;
thisPin--) {
// Connect this pin: digitalWrite (thisPin, HIGH); delay (timer);
// turns off this pin: digitalWrite (thisPin, LOW);
}
}
LDR Sensor
In this lesson, we will use an LDR (Light Dependent Resistor) to simulate a
light compensation of 5 levels, that is, depending on whether there is more or
less light focusing on the sensor, the system turns on or off a series of LEDs.
This program could be used in a lighting system with five lines of light that
they light up as the sun goes down, progressively compensating for the lack
of light.
In addition, a potentiometer adjusts the minimum critical light level from
which the circuit will activate.
What Will You Learn?
Serial reading of an analog sensor
Using an analog reading
Arduino AREF pin
Previous Knowledge
DigitalWrite() function
Conditional if/else
Required Materials
1 Arduino Uno
1 LDR
5 LEDs
1 AB USB
5 Resistors 330Ω
Source Code
/*
LDR sensor
Connect an LDR to an analog input to control five outputs depending on
ambient light.
*/
// Save the data collected by the LDR sensor: intLDR value = 0;
// Set the input pins of the LEDs:
int Ledpin1 = 12; int Ledpin2 = 11; int Ledpin3 = 10; int Ledpin4 = 9;
int Ledpin5 = 8;
// Set LDR sensor input pin
int pinLDR = 0;
void setup ()
{
Serial.Begin (9600);
// Set the LED output pins: pinMode (Ledpin1, OUTPUT); pinMode
(Ledpin2, OUTPUT); pinMode (Ledpin3, OUTPUT);
pinMode (Ledpin4, OUTPUT); pinMode (Ledpin5, OUTPUT);
// Defined the use of an external reference:
analogReference (EXTERNAL);
}
void loop ()
{
// Save the reading value of a variable: LDR value = analogRead
(pinLDR); Serial.println (LDR value);
// Definition of the control pattern of the LEDs:
if (LDR value> = 1023)
{
digitalWrite (Ledpin1, LOW); digitalWrite (Ledpin2, LOW);
digitalWrite (Ledpin3, LOW); digitalWrite (Ledpin4, LOW);
digitalWrite (Ledpin5, LOW);
}
else if ((LDR value> = 823) & (LDR value <1023)))
{
digitalWrite (Ledpin1, HIGH); digitalWrite (Ledpin2, LOW);
digitalWrite (Ledpin3, LOW); digitalWrite (Ledpin4, LOW);
digitalWrite (Ledpin5, LOW);
}
else if ((LDR value> = 623) & (LDR value <823)))
{
digitalWrite (Ledpin1, HIGH); digitalWrite (Ledpin2, HIGH);
digitalWrite (Ledpin3, LOW);
digitalWrite (Ledpin4, LOW); digitalWrite (Ledpin5, LOW);
}
else if ((LDR value> = 423) & (LDR value <623)))
{
digitalWrite (Ledpin1, HIGH); digitalWrite (Ledpin2, HIGH);
digitalWrite (Ledpin3, HIGH); digitalWrite (Ledpin4, LOW);
digitalWrite (Ledpin5, LOW);
}
else if ((LDR value> = 223) & (LDR value <423)))
{
digitalWrite (Ledpin1, HIGH); digitalWrite (Ledpin2, HIGH);
digitalWrite (Ledpin3, HIGH); digitalWrite (Ledpin4, HIGH);
digitalWrite (Ledpin5, LOW);
}
else
{
digitalWrite (Ledpin1, HIGH); digitalWrite (Ledpin2, HIGH);
digitalWrite (Ledpin3, HIGH); digitalWrite (Ledpin4, HIGH);
digitalWrite (Ledpin5, HIGH);
}
}
Tips
When the Arduino receives an analog signal, it converts it to digital in 1024
parts. This operation is standard since Arduino thinks that the signal he will
receive varies between 0v and 5v, which gives us a value for each part of
approximately 4.88 mV.
But we can say no, that really the system will work between 0v and 3v, thus
getting 1024 parts distributed between 0v and 3v, which gives us a value for
each part of 2.9 mV, i.e., a much higher resolution. The distribution of these
values we will divide equally in our program to make a progressive activation
of the lighting lines.
If we set the reference too low, the LEDs start working with less ambient
light than if we set a higher signal, remember:
More light = less resistance = more Volt less light = more resistance = less
Volt less
This control will be done via a potentiometer, where we can calibrate the
system through the ambient light.
pinMode(EXTERNAL);
With this instruction, we are telling our Arduino not to use the reference
voltage (+5V) but to apply it through the AREF pin.
Thermistor
In this lesson, you have to use a Thermistor (Temperature Dependent
Resistor) to do a temperature reading.
The result, in degrees Celsius, we will see through the Serial Monitor of
Arduino's IDE.
What Will I Learn?
Serial reading of an analog sensor (Thermistor)
Using an analog reading
Float variable
Previous Knowledge
analogRead function
Serial.print
Required Materials
1 Arduino Uno
1 Thermistor
1 Resistor 1KΩ
1 AB USB cable Jumpers
1 Protoboard
Source Code
Note that it is not an accurate thermometer, just an approximate example
based on empirical data.
Connect 1k resistor from A0 to ground and + 5V thermistor to A0 * /
#define pin_termistor A0
void setup (void) {Serial.begin (9600);
}
void loop (void) {float reading; float reading1;
reading = analogRead (pin_termistor); Serial.print ("Read pin A0 =");
Serial.println (read);
reading1 = (reading * 0.2027) -82; Serial.print ("Temperature approx.
Celsius ="); Serial.println (reading1);
Serial.println (""); delay (2500);
}
Tips
There are two types of thermistors:
NTC (Negative Temperature Coefficient) - thermistors whose
coefficient of resistance variation with temperature is negative:
resistance decreases with temperature increase.
PTC (Positive Temperature Coefficient) - thermistors whose
coefficient of resistance varies with the temperature is positive:
the resistance increases with the increase of the temperature
according to the characteristic curve/table of the thermistor, its
resistance value can decrease or increase in a greater or lesser
degree in a certain temperature range.
Thus, some can serve as overheat protection by limiting the electrical current
when a certain temperature is exceeded. Another application is the
measurement of temperature (in motors, for example) because we can, with
the thermistor, obtain a variation of electrical resistance in the function of the
variation of temperature.
DC Motor
In this lesson, we will control a DC motor through Arduino. The push of the
button will start our engine.
What Will I Learn?
Digital one-button reading
Controlling a DC motor with Arduino
Previous Knowledge
DigitalWrite() function
DigitalRead() function
Conditional if/else
Required Materials
1 Arduino Uno
1 DC motor
1 Resistor 330Ω
1 Resistor 15Ω
1 AB USB cable
Source Code
// Connect motor on pin 2 in series with a 15 ohm resistor
// to limit the current to 40mA just not to overload the Arduino
const int motorPin = 2; const int buttonPin = 7; int buttonState = 0;
void setup () {pinMode (buttonPin, INPUT); pinMode (motorPin,
OUTPUT);
}
void loop () {
buttonState = digitalRead (buttonPin); if (buttonState == HIGH) {
digitalWrite (motorPin, HIGH);
}
else {
digitalWrite (motorPin, LOW);
}
}
Tip
We can change the direction of rotation of a DC motor by simply reversing
the direction of the current. With the same assembly of this lesson, the test
reverses the connections of the motor and verify that it will start to rotate in
the opposite direction.
LCD
The LCD is an important part of projects where you need to visualize the
reading of a sensor or even to transmit information to the user.
In this exercise, you will learn how to connect the 2x16 LCD Display of your
Kit, which already comes with the welded pins.
What Will You Learn?
Connect your LCD to Arduino Uno
Programming phrases to appear on the LCD
Adjust the brightness of the display with a potentiometer
Know the functions of the LiquidCrystal.h library
Use the functions:
LCD.print
LCD.setCursor
scrollDisplayLeft()
scrollDisplayRight()
Required Materials
1 Arduino Uno
1 LCD display
1 Potentiometer
1 AB USB cable Jumpers
1 Protoboard
Source Code
/*
LiquidCrystal Multilogic Code Library
This library works with all displays compatible with the
Hitachi HD44780 driver.
Circuit:
* LCD RS pin on digital pin 12
* LCD pin Enable on digital pin 11
* LCD pin D4 pin on digital pin 5
* LCD pin D5 pin on digital pin 4
* LCD pin D6 pin on digital pin 3
* LCD pin D7 pin on digital pin 2
* LCD pin R / W on ground
* 10K Trimpot:
+ 5V on + 5V
* Earth on earth
* wiper to LCD VO pin (pin 3)
Public domain code based on the original lesson:
http://www.arduino.cc/en/Lesson/LiquidCrystal
*/
// Includes library code: #include <LiquidCrystal.h>
Exercise 1
The Arduino website offers several other projects with the LiquidCrystal.h
Library. Here we will do one more exercise using the same assembly of this
Lesson.
In this exercise, you can also modify the original text and control how long
your text stays fixed and how long it scrolls to the right or left.
/*
LiquidCrystal Library - scrollDisplayLeft () and scrollDisplayRight ()
LiquidCrystal Multilogic Code Library
This library works with all displays compatible with the
Hitachi HD44780 driver
This code writes "Multilogic Shop" on the LCD and uses
scrollDisplayLeft () and scrollDisplayRight () to pass the text.
Circuit:
* LCD RS pin on digital pin 12
* LCD pin Enable on digital pin 11
* LCD pin D4 pin on digital pin 5
* LCD pin D5 pin on digital pin 4
* LCD pin D6 pin on digital pin 3
* LCD pin D7 pin on digital pin 2
* LCD pin R / W on ground
* 10K Trimpot:
+ 5V on + 5V
* Earth on earth
* wiper to LCD VO pin (pin 3)
Library originally added 18 Apr 2008 by David A. Mellis
library modified 5 Jul 2009 by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009 by Tom Igoe
modified 22 Nov 2010 by Tom Igoe
Public domain code based on the original lesson:
http://arduino.cc/en/Lesson/LiquidCrystalScroll
*/
// Includes library code:
#include <LiquidCrystal.h>
// Initialize the library and define the pins used
LiquidCrystal lcd (12, 11, 5, 4, 3, 2);
void setup () {
// define the number of columns and rows:
lcd begin (16, 2);
// Send the message to the display. lcd print ("Desired Text"); delay
(2000);
}
void loop () {
// walks 16 positions for the text to exit the display on the left:
for (int positionCounter = 0; positionCounter <16; positionCounter ++)
{
// walk a position to the left: lcd. scrollDisplayLeft ();
// Wait a moment: delay (250);
}
// walks 32 positions for the text to exit the display on the right:
for (int positionCounter = 0; positionCounter <32; positionCounter ++)
{
// walk a position to the right: lcd. scrollDisplayRight ();
// Wait a moment: delay (250);
}
// walks 16 positions to the left to move back to the center: for (int
positionCounter = 0; positionCounter <16; positionCounter ++) {
// walk a position to the left: lcd. scrollDisplayLeft ();
// Wait a moment: delay (250);
}
// delay at the end of the full loop:
delay (2000);
}
Required Materials
1 Arduino Uno
1 LCD display
1 Potentiometer
1 AB USB cable Jumpers
1 Protoboard
Source Code
/*
This code sends a text entered via USB to the Circuit display:
* LCD RS pin on digital pin 12
* LCD pin R / W on pin 11
* LCD pin Enable on digital pin 10
* LCD pin D4 pin on digital pin 5
* LCD pin D5 pin on digital pin 4
* LCD pin D6 pin on digital pin 3
* LCD pin D7 pin on digital pin 2
* 10K Trimpot:
+ 5V on + 5V
* Earth on earth
* wiper to LCD VO pin (pin 3)
*/
#include <LiquidCrystal.h>
LiquidCrystal lcd (12, 11, 10, 5, 4, 3, 2); void setup ()
{
Serial. begin (9600); lcd begin (2, 20);
lcd clear (); lcd setCursor (0,0); lcd print ("Multilogic"); lcd setCursor
(0.1); lcd print ("shop");
}
void loop ()
{
if (Serial.available ())
{
// f reads through the serial monitor // char cr = Serial. read ();
// determine a character to clear the screen /// if (cr == '%')
{
lcd clear ();
}
// determine a character to jump to the bottom // else line if (cr = '>')
{
lcd.setCursor (0.1);
}
else
{
// if the typed character doesn't clear or skip line goes to display ///
// does not accept accent // lcd. write (cr);
}
}
}
Required Materials
1 Arduino Uno
1 Electric piezo
1 AB USB cable Jumpers
1 Protoboard
Tip
Do you want to amplify the sound of the piezo?
Place the back of the piezo (the whole golden part) on the bottom of a can of
soda or chocolate can, and you will hear the loudest sound.
Use your creativity and test that other elements can amplify the sound of the
piezo.
Source Code
/*
Scroll Bar with Processing
*/
char val; // variable to save the value received by the serial interface
char val_old; // variable to store the previous value received by the
serial interface
// setup function runs only once when program execution starts void
setup () {
// we initialize the pins from 2 to 6 as pinMode (2, OUTPUT) outputs;
pinMode (3, OUTPUT);
pinMode (4, OUTPUT); pinMode (5, OUTPUT); pinMode (6,
OUTPUT);
// we initialize the serial communication with a speed of 115200 baud
Serial. begin (115200);
}
// the loop function is executed indefinitely
void loop () {
if (Serial. available ()) {// checks if data is available for reading
val = Serial. read (); // read the data and store it in val
}
if (val! = val_old) {// acts only if there is a change in the value of val
alloff (); // perform the alloff function that erases all LEDs for (int i = 2;
i <(int (val) +2); i ++) {
// causes the value of i to vary from 2 to val + 2
// note that val stores a character and we need
// of the int (val) function to convert to a digitalWrite (i, HIGH)
numerical value; // turns on the LED on pin i
}
val_old = val; // saves the value of val in val_old
}
}
void alloff () {// function to turn off all LEDs
for (int i = 2; i <7; i ++) {// causes i to vary from 2 to 6 digitalWrite (i,
LOW); // turns off the LED on pin i
}
}
Arduino - Thermostat
In this lesson, we will set up a simple experimental thermostat with Arduino.
This mounting causes a relay and an LED to turn on when the temperature
drops below a set minimum value or turn off when it exceeds a set maximum
temperature.
Note that temperature measurement is empirical and should not be used as an
accurate instrument.
What You Will learn?
Use your Arduino to control devices from the ambient
temperature reading.
For this experiment, you can vary the temperature of the sensor
just by holding it with your fingertips.
Note that just as we are using a relay to light an LED, you could
drive any other device (a motor, for example) within the relay's
power range.
Necessary Materials
1 Arduino Uno R3
2 LEDs
1 Relay
1 Resistor 1kΩ
1 Resistor 300Ω
1 Thermistor
1 Protoboard
1 USB - AB Cable and Premium Jumpers. Or you can use the
Arduino Uno R3 Starter Kit components.
Source Code
// Example of a simple experimental Arduino thermostat
// This setup makes the relay and a led
// turn on when the temperature drops below a minimum
// and turn off when it exceeds a maximum
// The temperature measurement is an empirical approximation
// Do not use an accurate instrument, but rather as a
didactic // thermostat model.
// relay connected to digital pin 2
// Led connected to digital pin 13
// resistive divider of thermistor connected to pin A0 analog
// declaration of variables:
#define pin_termistor A0
int rele = 2;
int led = 13;
float reading;
float read1;
// set acting mode:
void setup (void) {
pinMode (relay, OUTPUT);
pinMode (led, OUTPUT);
Serial.Begin (9600);
}
// infinite loop:
void loop (void) {
read = analogRead (pin_termistor);
Serial.print ("Read pin A0 =");
Serial.println (read);
read1 = (read * 0.2027) -85; // Calculate the temp. approximate
if (read1 <32) // set trigger temperature
{
digitalWrite (relay, HIGH); // relay
digitalWrite (led, HIGH); // turn on Led
}
if (read1> 35) // set cutoff point
{
digitalWrite (relay, LOW); // turn off
digitalWrite relay (led, LOW); // turn off Led
}
Serial.print ("Temperature approx. Celsius ="); // send and temp. for
serial monitor
Serial.println (read1);
Serial.println ("");
delay (2500);
}
Chapter 6
And of course, you will learn how to use the if statement with Arduino
through a case study.
Take the plate out of the box, and let's start with this chapter.
What will you learn in this chapter?
if with Arduino necessary material
Syntax of the if statement with Arduino
Comparison operators in if statements with Arduino
Example if statement with Arduino
Boolean operators if with Arduino
if-else with Arduino
Example if-else statement with Arduino
else if with Arduino
Example else if statement with Arduino
Let's now see the syntax that is hidden behind the if-else statement with
Arduino.
I am sure that more than one comparison operator sounds to you. They are
often used to express mathematical formulas.
The first 4 (greater than, less than, greater than or equal to or less than or
equal to) are quite explicit. However, the last two (equal to and different
from) require a little explanation.
Let's see some examples of each of them.
Comparison operator greater than (>)
As long as the number on the left is greater than the number on the right, the
condition of the if statement with Arduino is true. Otherwise, it is false.
50> 10 -> true
15> 80 -> false
Look at the operator symbol equal to (==), why do you use a double equal
sign? Do you need to verify twice that they are equal? The answer is simpler
than it seems.
The equal sign already has a function, that of the assignment. When we
assign a value to a variable, for example. The double equal sign is used as an
equality comparator so as not to confuse the compiler since otherwise, I
would not know if we are comparing or assigning a value.
Comparison operator other than (! =)
As long as the number on the left is different than the number on the right,
the condition of the if statement with Arduino is true. Otherwise, it is false.
20! = 10 -> true
10! = 10 -> false
As I said, they serve to combine conditions. For example, you can know if
the value obtained from analogRead is between 300 and 500.
It's something like when you press two keys on your keyboard. If you press
the c key, write that letter in a document, for example. But if you press the
control key (Ctrl) and the c key, what you do is copy what you have selected.
More or less, it is something similar.
We are going to see each of these Boolean operators with examples so that
you understand it better.
Boolean Operator or (||)
It can be translated as "or this or that." It is represented with two vertical lines
(||) that you find on key 1 of the keyboard. To use it, you must first press Alt
Gr and then the 1 key.
This operator makes the if condition with Arduino true if either of the two or
more conditions are met. For example, if we have this code:
if (value> 300 II value <200) {
// Show text by serial monitor
Serial.println ("Value exceeded");
}
We are saying that whenever the value is greater than 300 or that the value is
less than 200, display a text on the serial monitor. This means that whenever
the value is between 201 and 299, it will not show any text.
In the rest of the cases, it will show the text on the serial monitor.
Boolean Operator and (&&)
It can be translated by "this and that." It is represented by two ampersands
(&&) symbols found on key 6 of the keyboard. Pressing capital letters and 6,
you can use it in your codes.
This operator makes the if condition with Arduino true only if both or several
conditions are met. For example, if we have the code:
if (value> 300 && value <500) {
// Show text by serial monitor
Serial.println ("Value exceeded");
}
It means that it will only be true if the value is greater than 300, and the value
is less than 500. This gives us a range of values between 301 and 499 (don't
forget that the symbols> and <exclude the numbers on the right).
Therefore, only when you are in that range will you show the text on the
serial monitor.
Boolean Operator not (!)
It translates as "no." It is represented by the final exclamation mark (!)
Located on the 1 key. You can use it by pressing the uppercase key plus the 1
key.
What this operator does is something strange. If an expression is true, it
returns false, and if it is false, it returns true.
To understand the following example, you also have to understand what is
true and what is false. They are still two states, like the binary code of which
I have spoken to you before. We can have a 0 (false) or a 1 (true).
But the reality is that there are more numbers. The question is, is 2 true or
false? Boolean data types are always false as long as it is 0. Otherwise, it is
true. Therefore 2 and any other numbers are true if evaluated in a condition.
This is only a reminder.
In a digital pin, we also have two values, LOW and HIGH. If you enter the
Arduino core code, you can verify that these two reserved words are actually
two constants whose value is 0 for LOW and 1 for HIGH.
Therefore, if we have a digital pin connected to a button, and the input is 0V,
the status will be LOW. If we store that value in a variable, we could evaluate
its value if it is false or true in an if conditional statement with Arduino.
For example, it can help us to know if a button is not pressed. In normal use,
when pressed, it will have a HIGH state that, as we have seen, is true. While
when not pressed, it has a LOW status, false.
boolean button = digitalRead (Buttonpin),
// If the button is false (equal to 0) everything is true
if (! button1) {
// Turn on the LED
digitalWrite (led Warning, HIGH);
}
This would be the way we would detect if a button is not pressed. In this
case, it will pass inside the if with Arduino and execute the code inside.
Other Considerations of Boolean Operators with an Arduino if
Finally, I want to add that you can join as many conditions as we want to an
if with Arduino. It is convenient, as far as possible, not to add many
conditionals as this would make our code unreadable.
Also, note the use of the not (!) Operator with other comparison operators.
For example, the same expression can be expressed in different ways thanks
to the not operator. If you want to know if a number is between 300 and 500,
you can use these two conditions:
(number> = 300 && number <= 500)
! (number <300 && number> 500)
These two expressions return the same value for the same number.
Now we will continue to see how you can execute different pieces of code
depending on different conditions with if-else in Arduino.
In this chapter, I will explain how we can make a battery and battery charge
meter. We will do it through the assembly of a circuit with Arduino.
It is usually very typical that we have at home different electrical devices that
use batteries. Sometimes, we doubt whether the device is broken or the
batteries have run out.
Thanks to this project, this will no longer be a problem. The battery and
battery charge meter will give you the solution.
What will you learn in this chapter?
The objective of the battery and battery charge meter with the
Arduino board
Arduino components that we will use
Riding the circuit with Arduino
Programming the battery and battery charge meter with Arduino
Arduino native code
As you can see, it is a very simple circuit. With three LEDs and four
resistors, it is enough to build a battery or battery charge meter with Arduino.
What is an ADS1115?
Now that we are clear about what a digital-analog converter is let's move on
to see the ADS1115. The ADS1115 is an ideal external digital-analog
converter when more resolution or more analog pins are required.
A typical case is when you want to measure different analog signals with an
ESP8266. This SoC only incorporates an ADC. In these cases, it is essential
to use an external digital-analog converter (ADC) such as the ADS1115.
As with many components of this type, the ADS1115 is the chip that names
the electronic component. You will find it in different shapes and formats,
according to the manufacturer.
One of the most famous is that of Adafruit, although you can find other
similar ones from other brands. I am going to work with the GY-ADS1115 /
ADS1015, whose price is about $ 5.
Everything you see in this lesson will also be useful for any other ADS1115,
no matter the manufacturer. The most normal thing is to come with the
solderless pins. So prepare the soldering iron and tin because you have to
weld.
Next, we will see the main features of the ADS1115.
Main Features of the ADS1115
The first thing is to always go to the technical data sheet, where you will get
the best and most reliable information on an electronic component.
On the website of the chip manufacturer, Texas Instruments, you will find it
here.
Characteristic Value
Operating voltage from 2V to 5.5V
Current consumption 150 µA (continuous mode)
Programmable Sampling
8 Hz to 860 Hz
Rate
Resolution 16-bit
4 input channels or 2
Channels
differentials
Communication interface I2C (4 addresses)
We will be explaining all these features of the ADS1115 throughout this
lesson.
Before we go to see the pins.
ADS1115 Pins
The number of pins depends a lot on the component, but, normally, we have
access to 10 pins.
The VDD and GND pins are the power pins.
The SCL and SDA pins are the I2C clock and data pins.
Pins A0, A1, A2, and A3 are the four analog input pins.
The ADDR and ALERT pins are special, and we will see them in
more detail.
ADDR Pin
The ADS1115 digital-analog converter can be configured with 4 I2C
addresses. This means that you can connect up to 4 ADS1115 on the same
I2C bus.
The ADDR pin is used to select an address from the four possible ones.
Depending on where you connect, you will use one address or another.
The possible I2C addresses are 0x48, 0x49, 0x4A and 0x4B.
In the following table, I show the possible connections with their
corresponding addresses.
ADDR connection Direction
GND 0x48
5V 0x49
SDA 0x4A
SCL 0x4B
What this table means is that the ADDR pin has to be connected to the GND,
5V, SDA or SCL pin to get the corresponding address.
This type of addressing allows up to 4 ADS1115 modules to be connected to
the same board.
ALERT Pin
The ADS1115 digital-analog converter is equipped with a customizable
comparator that issues an alert on the ALERT / RDY pin. This feature is very
useful since it can significantly reduce external circuits in many projects.
Imagine you have a sensor to detect floods. Thanks to a comparator like the
ADS1115 you could do that when it exceeds the threshold, on the ALERT
pin it emits a signal and wakes the microcontroller. This allows device
consumption to be very low.
It can work in two ways.
In traditional comparator mode, the ALERT pin is activated when the signal
exceeds a set high threshold (TH_H) and is deactivated when the threshold
drops below the low threshold (TH_L).
In the window comparator mode, lets you know if the signal is between the
limits of a window set by the high threshold (TH_H) and the low threshold
(TH_L).
This means that it is activated when the high threshold is exceeded or when
they fall below the low threshold.
These two modes can be configured at the software level.
ADS1115 Conversion Modes
The ADS1115 digital-analog converter can operate in two conversion modes:
single-shot mode and continuous conversion mode.
In single-shot mode, the digital-analog converter (ADC) converts the input
signal to demand and stores the result in an internal register.
By sending a signal to ADS1115, we can indicate when to convert.
Then the ADS1115 enters the energy-saving mode. This mode is used to save
energy on systems that only require periodic conversions, or there are long
periods of inactivity between conversions.
In continuous conversion mode, the digital-analog converter (ADC)
automatically begins converting the input signal as soon as the previous
conversion is complete. That is, convert a value from analog to digital and
when it finishes, take another sample. At what velocity?
The conversion rate, as we have seen before, is programmable.
The data can be read at any time and always reflect the most recent
conversion.
Resolution of the ADS1115 Digital-Analog Converter
Although I have already commented that the resolution of the ADS1115 is
16-bit, the reality is that not all 16-bit bits are used to express the voltage
value. The output you get from the ADS1115 is known as a signed integer,
that is, one of the bits of the 16-bit word is used to set the sign, positive or
negative.
Therefore, only 15-bit of the 16-bit is used, which means that there are
32,768 possible values (2 15).
The first value would be 0, and the last would be 32,767.
Programmable Gain Amplifier or PGA
Another of the peculiarities that give the ADS1115 even greater precision and
reliability is the programmable gain amplifier or PGA that is incorporated.
Ok, but what is a programmable gain amplifier?
Basically, it is an operational amplifier to which we can modify the gain
through the code, programming. The programmable gain amplifier sets the
full scale, that is, indicates the reference value.
In Arduino, this value is determined by the reference voltage, which in the
case of Arduino UNO is 5V and in the Arduino MKR range, and the
ESP8266 is 3V3.
In ADS1115, it is established by the PGA. By default, this reference value is
± 6,144 V. This means that the value of 32,677 (maximum value with 15-bit)
corresponds to 6,144 V.
In Arduino UNO, with a 10-bit ADC (1024 possible values), the value 1023
corresponds to 5 V.
If you do the conversion, you have to for the ADS1115
And for an Arduino UNO
Differential Mode
As I said, the differential mode of the ADS1115 allows us to measure the
difference between two analog pins of this module.
You can measure the voltage difference between A0 and A1 or between A2
and A3. That is why it is called differential.
But why can this type of measure be useful?
If you usually do projects with Arduino at some point, you will need to power
your project with batteries.
The differential mode will allow you to make a measurement in which none
of the sides of the measurement is connected to GND, as is the case when
measuring a battery or battery with Arduino.
In addition, another benefit of this mode is that you can perform negative
voltage measurements.
In the following example, I will show you how you can do it.
ADS1115 Connection with Arduino UNO
Assemble the circuit starting from the following scheme.
I have used a battery holder with two AA batteries, but you can use another
class of batteries, such as AAA or even a single 1.5V battery.
The positive end of the battery holder is connected to the A1, and the
negative end is connected to the A0 of the ADS1115.
When the two batteries are connected in series, the voltages are added.
Therefore 1.5 + 1.5 = 3V. This will be at best.
The programming will be the same: what will change will be the value
obtained from the difference.
ADS1115 Connection with ESP8266
In the following scheme, I show you how to connect the ADS1115 with a
NodeMCU ESP8266 board to make a differential measurement.
As in the scheme with the Arduino UNO, I used an AA battery holder.
The positive end of the battery holder to A1 and the negative end to A0.
Be very careful if you are going to measure a voltage higher than 3.3V with
which the ADS1115 is powered. Remember that you cannot beat VDD +
0.3V, that is 3.3 + 0.3 = 3.6V
delay (2000);
}
The first thing the code does is import the libraries and create an instance of
the Adafruit_ADS1115 class called ads.
Then I declare a float type variable to store the scale factor called the Scale
factor.
The scale factor depends on the voltage reference that has been selected. By
default, it is 6.144V, which corresponds to a scale factor of 0.1875mV.
If the voltage reference is modified, you will have to modify the scale factor
and put the corresponding one according to the table we have seen in the
previous section.
In the setup () function, serial communication is initiated, the scale factor is
set with the ads.setGain function (GAIN_TWOTHIRDS), and the ADS1115
sensor is started with the ads.begin () function .
As I said, if you modify the scale factor with the function ads.setGain (...)
will have to change the initial value of the variable scalefactor to the match.
In the loop () function, the first thing is to obtain the difference between pin
A0 and A1 using the ads.readADC_Differential_0_1 () function.
This function returns the difference between A0 and A1; that is, the value in
A0 subtracts the value from A1.
If you need to use the other two pins you can use the
ads.readADC_Differential_2_3 () a function that will return the difference
between A2 and A3.
This difference is expressed as a signed 16-bit number that is between 32,768
and 32,767. This value must be converted to volts.
To do this, multiply by a Scalefactor and get millivolts. To get volts, you
have to divide by 1,000. The same is what is done on line 27 of the code.
Finally, the information is shown by the serial monitor.
Now you just have to load the code to the board and open the serial monitor.
You will get something similar to this.
As you can see, negative numbers come out. This is because we are
subtracting the voltage we have on pin A0 minus pin A1.
As we have connected the positive of the battery holder to A1, the result is
negative.
You can try changing the cables (positive at A0 and negative at A1) and see
how the positive voltage appears.
Finally, we will see how to make the ADS1115 launch an alert when it is
running in comparator mode.
Comparator Mode
The comparator mode allows a comparison of the value obtained by one of
the analog pins with a preset threshold.
As we have seen before, two types of comparisons can be configured: the
traditional one or by a window.
If the traditional one is used, as long as the value exceeds the maximum
threshold, the ALERT pin will be set to LOW. By default, it is always in the
HIGH state.
If you use the type per window, it will change state whenever the high
threshold is exceeded and whenever it falls below the low threshold.
With the Adafruit library, you can only work with a threshold, high threshold,
and traditional mode. It has not implemented the other mode.
This is precisely what we will see next.
ADS1115 and Arduino UNO Connection
The circuit we are going to use is the same as the one we have seen in a
previous section.
Follow the following scheme to connect the components.
The photoresistor or LDR is connected to pin A0, and we also connect an
LED to the ALERT pin.
The idea is to set a threshold in the ADS1115, and every time you lower the
brightness of that threshold, turn on the LED.
ADS1115 and NodeMCU ESP8266 Connection
The connection with the NodeMCU ESP8266 board is practically the same.
Follow the following scheme.
As with the Arduino board, the photoresistor or LDR is connected to pin A0,
and the LED to pin ALERT.
Now only programming remains.
Programming in Comparator Mode
Below is the complete code with the comparator example.
#include <Wire.h>
#include <Adafruit_ADS1015.h>
// Create class object
Adafruit_ADS1115 ads;
void setup (void)
{
Serial.begin (9600);
delay (200);
// Scale factor
ads.setGain (GAIN_TWOTHIRDS);
// Start ADS1115
ads.begin ();
// Scale factor. By default the reference value is 6.144V
// The scale factor of this reference is 0.1875mV
float scale factor = 0.1875F;
// Comparator threshold at 2.5V
// To calculate, divide the (voltage / scale factor) * 1,000
float threshold = (2.5 / Scale factor) * 1000.0F;
Serial.print ("Threshold =");
Serial.println (threshold);
// Assign the threshold to analog pin A0
ads.startComparator_SingleEnded (0, threshold);
}
void loop (void)
{
// Only the comparison will be made after reading
short readADC0 = ads.getLastConversionResults ();
Serial.print ("ADC0:");
Serial.println (read ADC0);
delay (100);
}
The first part of the code is the same as the codes we have seen so far in this
lesson, importing libraries and instance to the Adafruit_ADS1115 class.
In the setup () function, the serial communication starts, the scale factor is set,
and the ADS1115 starts.
In the next part of the code, the high threshold of the comparator mode is set
from line 20 to line 29.
The first thing is to declare a variable with the scale factor. Remember that by
default, the scale factor is 0.1875mV, corresponding to 6.144V voltage
reference.
The variable that stores this value is a scale factor of the float type.
The threshold must be set to a number that ranges from 0 to 32,767 (they are
15-bit resolution). The logical thing is to set a threshold voltage and then pass
it to the number.
To do that conversion you have to apply the following formula:
In the loop () function, you must constantly check the value on the analog pin
with the ads.getLastConversionResults () function so that the ADS1115
internally makes the comparison.
If the voltage on the A0 is greater than 2.5V, the ALERT pin of the ADS1115
will be in the LOW state, that is, the pin will be activated.
If the voltage at A0 is less than 2.5V, the ALERT pin will be in the HIGH
state, that is, the pin will be deactivated.
By default, the ALERT pin works inverted.
Now there is only one thing left, upload the code to the board and try
zooming in and out of light to the photoresistor or LDR.
You will see how, when the light hits the LED, the LED goes out, and when
the light doesn't hit, the LED goes off.
With this, I conclude this lesson on the digital-analog converter.
The ADS1115 digital-analog converter can be a great ally when we need
more analog pins or more precision in our projects.
It is very simple to use with an Arduino or an ESP8266 thanks to its I2C
interface.
It allows working in different operating modes: single-ended mode,
differential mode, or comparator mode.
Using one or the other will depend on the requirements of our project.
Thanks to the Adafruit library, its use with any of these two plates is very
simple, and also the code is 100% compatible between them.
Chapter 9
Arduino Interruptions
There is the fifth state that only the Arduino Due, Zero and MKR1000 allow:
HIGH: the interrupt will be launched when the pin is in a high
state.
detachInterrupt (pin)
If attachInterrupt () allows us to configure a pin as an interrupt, the
detachInterrupt () method overrides that setting. As a parameter, we pass the
pin, and we can do it with the digital function PinToInterrupt (pin number)
that will return the ordinal of the pin from which we want to cancel the
configuration.
Each button will be connected to a pin and will have a pull-down resistor.
This will make in a normal state, without pressing, the pin will have a low
state. When the button is activated, we will have a high state. Therefore we
must detect a change of state from low to high (RISING).
On the other hand, the LEDs will do a sequence of turning on and off from
left to right and from right to left. Simulate the fantastic car lights. We will
start with speed, and as we press the buttons, the speed will increase or
decrease.
The electrical scheme is as follows.
Programming the Interruption Sketch with Arduino
The first part is the declaration of counters and variables. At this point, it is
necessary to make a clarification. When we work with interruptions with
Arduino, we must take special care with the ISR methods that will be
executed when the event occurs.
In general, we must make ISR methods or functions as short and as fast as
possible. A blockage between the different ISRs can occur. What happens in
these cases is that only one is executed at a time, the rest of the interruptions
being queued.
Within the interruptions, the delay () (delay) does not work; therefore, do not
use it. Remember that it is about executing code as quickly as possible. If you
want to make the process stop within an ISR, use the delayMicrosends ()
function since it works normally.
The variables that we will use both within the ISR methods and outside,
either in the loop () or in any other function, we must declare them as
volatile. This reserved word tells the compiler that these variables can change
their value at any time and, therefore, the compiler must reload the variable
every time reference is made to it. In contrast, other variables require the
compiler to rely on a copy that it may have in a processor register.
Sketch Fantastic Car Lights with Interruptions
*/
// Global speed variable
volatile int speed = 20;
// Constants of maximum, minimum speed and how much increases
maximum int const = 1000;
minimum int const = 20;
const int increases = 20;
// Array with the pin numbers where they are connected
// the LEDs of the fantastic car lights
int leds [5] = {8, 9, 10, 11, 12};
void setup () {
// Initialize the LED pins as output and at low state
for (int i = 0; i <5; i ++)
{
pinMode (leds [i], OUTPUT);
digitalWrite (leds [i], LOW);
}
// We assign the minimum speed
speed = minimum;
// Configure the interrupt pins so that
// detect a change from low to high
attachInterrupt (digitalPinToInterrupt (2), speedLess, RISING);
attachInterrupt (digitalPinToInterrupt (3), speedMas, RISING);
}
void loop () {
// This first loop travels the array from left to right
for (int i = 0; i <5; i ++)
{
// Only for the second and consecutive pin, we turn off the previous
pin
// In the case of 0, it is not necessary since by default it is off
// Be careful that we go out of the range of the array 0-1 = -1 this
element does not exist
if (i> 0)
{
// Turn off the LED on the left
digitalWrite (leds [i - 1], LOW);
}
// We turn on the LED in which we are
digitalWrite (leds [i], HIGH);
// We wait for the time marked by speed
delay (speed);
}
// Turn off the last LED on, element 5 of the array
digitalWrite (leds [4], LOW);
// We traverse the array in the reverse direction from right to left
for (int i = 4; i> = 0; i--)
{
// In the first case as the LED is off, we do nothing
// Be careful that we go out of the range of the 4 + 1 = 5 array this
element does not exist
if (i <4)
{
// Turn off the LED on the right
digitalWrite (leds [i + 1], LOW);
}
// We turn on the LED in which we are
digitalWrite (leds [i], HIGH);
// We wait for the time marked by speed
delay (speed);
}
// Turn off the last LED on, element 0 of the array
digitalWrite (leds [0], LOW);
}
// ISR pin 2, slow down
void speed Less ()
{
// Decrease the set value
speed = speed - increases;
// If we have reached the minimum speed we do not decrease more
if (speed <minimum)
{
speed = minimum;
}
}
// ISR pin 3, increase the speed
void speedMore ()
{
// Increase the set value
speed = speed + increases;
// If we have reached the maximum speed we do not increase more
if (speed> maximum)
{
speed = maximum;
}
}
And finally, here in this chapter, we have seen the interruptions with
Arduino. It is very important to know this technique very well since it will
save us a lot of work on certain occasions.
Conclusion
Now that you have a little more skills and intimacy with electronics and
programming, do you feel safe to create something? If you need more
knowledge on Arduino, our Arduino series has several books ranging from
super basic to advanced. Here are some projects that may be interesting for
those like you who just had their first contact with Arduino.
Some components that we didn't work so hard on were the sensors, we saw
only vibration and light, but there is a sensor for almost everything you can
imagine! With them, you can carry out various projects, such as those listed
below:
1. Temperature sensor
2. Proximity sensor, which measures distance using ultrasound
3. Touch sensor to play songs
4. Soil moisture sensor to know when your plant needs water
5. Flame sensor, be careful with this sensor testing
https://classroom.littlebits.com/projects/pokelight
https://fabacademy.org/archives/2012/students/di_vozzo.romain/week_7_fab_academy_el
https://www.littlebits.com/projects/croq-cat
https://digitalmedia.risd.edu/pbadger/PhysComp/index.php?
n=Devices.MomentaryCode
https://www.arduino.cc/en/Tutorial/ForLoopIteration
https://sites.google.com/site/hwcontwerpen/sketches-les-0-t-m-9/les1d-
looplicht
http://fritzing.org/projects/brightness-indicator-photocell-with-tweak
https://www.arduino.cc/en/tutorial/loop
https://stackoverflow.com/questions/50251876/how-can-i-blink-a-led-
differently-when-i-press-a-toggle-button/50259528
https://stackoverflow.com/questions/50251876/how-can-i-blink-a-led-
differently-when-i-press-a-toggle-button/50259528
https://www.arduino.cc/en/Tutorial/AnalogInOutSerial
https://www.arduino.cc/reference/en/#structure
ARDUINO
PROGRAMMING
STUART NICHOLAS
Introduction
Have you ever wondered how to start the adventure with microcontrollers?
Check Arduino. This open platform has been prepared for all DIY
enthusiasts, including robot builders. The first part of the book discusses the
basics required for further lessons.
If you are interested in electronics at least to a small degree and would like to
start programming your own systems, then Arduino will be the perfect
solution to start with. You won't have to waste time designing your own tiles,
choosing the right programmer, and tedious environment configurations.
Everything will work almost immediately.
This book has been planned for 11 parts (with possible continuation). Of
book, he does not discuss the whole Arduino, and the subject is so extensive
that you can write about it (several) books. The purpose of this book is to
explain the basics in practice and to interest the reader in further exploring
this platform.
What is Arduino?
For a beginner, Arduino is a ready "development kit" with the popular AVR
microcontroller. Created according to the relevant assumptions, thanks to
which:
1. Does not require an external programmer
2. Works well with a dedicated compiler
3. You can buy an "infinite" number of expansion boards (e.g.,
motor controllers, displays, executive modules)
Advantages of Arduino
The project began to be developed in 2005 in Italy. Since then, he has
gathered a mass of supporters and fanatical users. From the very beginning,
Arduino was prepared for people who did not have much in common with
programming microcontrollers.
Excellent environment, friendly syntax, and low prices have made Ardunio
extremely popular. The community built around this project is huge. This
brings many benefits. From a beginner's point of view, three are most
important:
A huge number of ready-made solutions. Various projects are
created on Arduino. If you came up with something "new" and
interesting, then 90% someone has already done it on Arduino
earlier and posted a description of the project on the Internet.
The popularity of the platform has meant that manufacturers
have prepared countless tile varieties and extensions - you will
find more about this later in the book.
A large number of users make it easier to find help when they get
stuck in an important point of the project.
For example, if you are looking for the Arduino UNO mentioned above and
you find a plate identical to my photos at a price of less than $120, it will be
100% fake. You can take a chance and buy one. The choice is yours, whether
you want to support companies that earn dishonestly or choose those that
have put a little more effort into the production of their version.
Warning. The cheap imitation ones are often made of inferior quality
elements that can damage the entire system.
Materials you need to program Arduino
In addition to the Arduino UNO mentioned above, a handful of additional
elements will be used in the first seven parts of the book. A USB cable and
connection cables will definitely be useful. Plus colored LEDs and buttons.
We will present more complicated items on a 2x16 character text display.
In the further chapters of the book, we will also discuss controlling actuators
such as servos and motors. Sensors will also be useful. We will use light
sensors ( photoresistors ) and an ultrasonic distance sensor.
The set of necessary elements is visible in the photo below:
Now we will deal with the installation of the environment. I assume you don't
have the equipment you need yet. However, Arduino will be necessary for
further learning.
If the first address occurs, download the environment from here. However, if
you find a second address on the back of the tile, get it from here.
Conversions
Often, we need to convert the numbers to different bases. We will find two
methods and it’s good to know both. The first will teach you how to do the
conversions "by hand,” allowing you to understand things well. The second
that of the calculator will allow you to make conversions without getting
tired.
QUICK Method
For this, go to Start / All programs / Accessories / Calculator. Who Said I
Was Lazy?
You see at the top, that there are options to check to display the number
entered in the base that we want. Currently, I am in base 10 (decimal - Dec
button). If I click on Hex:
I see that my number 42 has been converted to 2A. And now if I click on Bin:
Yes, that's right. Why didn't we start by explaining that? Who knows.
Now that you have acquired the essential basics to continue the book, we will
see how the material you bought looks and which we will need to follow this
book.
The Software
To give you a little extra time to get your Arduino board, I will briefly show
you how the Arduino software looks.
Installation
There is no need to install the Arduino software on your computer since it is a
portable version. Let's look at the steps together to prepare your computer for
using the Arduino board.
Downloading
To download the software, go to the download page of the Arduino.cc
website. You have two categories:
Download: In this category, you can download the latest version of the
software. Windows platforms,
The software supports Linux and Mac. This is where you will download the
software.
Previous IDE Versions: In this category, you have all the versions of the
software, under the platforms previously mentioned, since the beginning of
its creation.
Windows
For me, it will be under Windows. I click on the Windows link, and the file
appears:
Once the download is complete, you have to decompress the file with a
decompression utility (7-zip, WinRar, etc.). Inside the folder are a few files
and the software executable:
Mac Os
Click on the Mac OS link. A.dmg file appears. Save it.
Double-click on the.dmg file: There is the Arduino application (.app), but
also the driver to install (.mpkg). Proceed with the driver installation then
install the application by dragging it into the shortcut of the "Applications"
folder, which is normally present on your computer.
Under Linux
Nothing could be simpler, by going to the software library, look for the
"Arduino" software. Several outbuildings will be installed at the same time.
Software Interface Software Launch
Launch the software by double-clicking on the icon with the "infinite"
symbol in green. It is the executable of the software. What jumps out at first
is the clarity of the presentation of the software. We immediately see its
intuitive interface.
Correspondence
Frame number 1: these are the software configuration options
Frame number 2: it contains the buttons that will serve us when we are going
to program our cards Frame number 3: this block will contain the program
that we are going to create
Frame number 4: This is important because it will help us to correct the faults
in our program. It's a debugger.
Equipment
I hope that you now have the equipment required to continue the book
because, in this chapter, I will show you how your card looks, then how to
test it to verify that it works.
Materials
To operate, the card needs a power supply. The microcontroller operating
under 5V, the card can be supplied with 5V by the USB port (in 2) or by an
external power supply (in 3), which is between 7V and 12V. This voltage
must be continuous and can, for example, be supplied by a 9V battery. A
regulator then takes care of reducing the voltage to 5V for the proper
functioning of the card. No danger of toasting everything. Please only respect
the interval of 7V to 15V (even if the regulator can support more, do not
bother to subtract it within its limits)
Visualization
The three "white dots" circled in red (4) are, in fact, LEDs whose size is of
the order of a millimeter. These LEDs are used for two things:
The one at the top of the frame: it is connected to a pin of the microcontroller
and will be used to test the hardware.
Note: When you connect the card to the PC, it flashes for a few seconds.
The two LEDs at the bottom of the frame: are used to display activity on the
serial channel (one for transmission and the other for reception). The
downloading of the program in the microcontroller being done in this way,
one can see them flashing during the loading.
Connectivity
The Arduino board does not have any components that can be used for a
program, put by the LED connected to pin 13 of the microcontroller, and it is
necessary to add them. But to do this, you must connect them to the card.
For example, we want to connect an LED to an output of the
microcontroller. connect it, with a resistor in series, to the card, on the card's
connection plugs.
This connection is important and has a pinout that must be respected. We will
see it when we learn to do our first program. It is with this connection that the
card is "expandable,” because you can connect all types of assemblies and
modules. For example, the Arduino Uno board can be extended with shields,
such as the "Ethernet Shield," which allows the latter to be connected to the
internet.
Installation
To use the card, it must be installed. Normally, the drivers are already
installed under GNU / Linux. Under Mac, double click on the.mkpg file
included in the download of the Arduino application, and the installation of
the drivers is executed automatically.
Windows
When you connect the card to your computer on the USB port, a small
message appears at the bottom of the screen. Theoretically, the card you use
should install itself. However, if you are on Win 7 like me, it may not work
the first time. In this case, leave the card connected and then go to the control
panel. Once there, click on "system," then in the left panel, select "device
manager." Once this menu is open, you should see a component with a
yellow "caution" sign. Right-click on the component and click "Update
Drivers." In the new menu, select the option "Search for the driver myself."
Finally, you have to select the right folder containing the driver. It is in the
Arduino folder that you had to unzip a little earlier and is called "drivers" (be
careful, don't go down to the "FTDI" folder). For example, for me, the path
will be:
[The way-to-folder] \ Arduino-0022 \ Arduino-0022 \ drivers
It seems that there are problems using the French version of Arduino (the
drivers are missing from the file). If this is the case, you will need to
download the original version (English) to install the drivers. After
installation and a sequence of flashing on the micro-LEDs of the card, it
should be functional; a small green LED indicates that the card is properly
powered.
It is this last point that we must acquire. The purpose of this chapter is to
teach you how to program with the Arduino language. However, this is only a
book material that you can browse when you have to program your card by
yourself. Indeed, it is by manipulating that you learn, which implies that your
programming learning will be more consistent in the next chapters than in
this book itself.
I specify a small hazard: the Arduino language not having the coloring of its
syntax in the zCode. I will put it as C code because their syntax is very close:
Code: C
// here is colored Arduino code thanks to the "code: C" tag in zCode
void setup ()
{
//...
}
The Arduino language is very close to C and C ++. For those whose
knowledge of these languages is based, do not feel obliged to read the two
chapters on the Arduino language. Although there are some somewhat
important points.
Language syntax
The syntax of a programming language is the set of writing rules linked to
this language. We will, therefore, see in this section the rules which govern
the writing of the Arduino language.
Function
In this code, there are two functions. Functions are portions of code.
Code: C
void setup ()
// card initialization function
{
// content of initialization
// we write the code inside
}
This setup () function is called only once when the program starts. This is
why it is in this function that we will write the code which only needs to be
executed once. This function is called: "initialization function." We will find
the implementation of different outputs and some other settings. It's a bit like
the start-up check-up. Imagine an airplane pilot in his cabin doing the
inventory:
- leg 2 at the exit, high state?
- OKAY
- timer 3 to 15 milliseconds?
- OKAY
Once you have initialized the program, you must then create your "heart,” in
other words, the program itself.
Code: C
void loop () // main function, it repeats (runs) endlessly
{
// content of your program
}
It is, therefore, in this loop () function where we will write the content of the
program. It should be known that this function is called permanently, that is
to say, that it is executed once, then when its execution is finished, it is re-
executed and again and again. We are talking about an infinite loop.
For your information, you don't have to write anything on these two
functions. However, it is mandatory to write them, even if they do not contain
any code.
The Instructions
In these functions, what do we write? This is precisely the purpose of this
paragraph.
In your list for dinner tonight, you write down the important tasks that await
you. These are instructions. The instructions are lines of code that say to the
program: "do this, do that." It is very simple but very powerful because it is
what will orchestrate our program.
The semicolons end the instructions. If, for example, I say in my program:
"call the function cutFromSausage" I must put a semicolon after calling this
function.
Semicolons (;) are synonymous with errors because they are very often
forgotten at the end of the instructions. Therefore, the code does not work,
and the search for the error can take us considerable time. So be careful.
The Braces
The braces are the "containers" of the program code. They are specific to
functions, conditions, and loops. The program instructions are written inside
these braces. Sometimes they are not mandatory in the conditions (we will
see below what it is), but I recommend to put them all the time. This will
make your program more readable.
Comments
Finally, we will see what a comment is. I already put some in the example
codes. These are lines of code that will be ignored by the program. They are
useless during the execution of the program. But then is it useless?
No, because this will allow the programmers who will read your code and us
(if there are any) to know what the line of code you wrote means. It is very
important to put comments, and it also makes it possible to resume a
forgotten program more easily.
If, for example, you are unfamiliar with an instruction that you have written
in your program, you put a comment line to remind you the next time you
read your program what the line means.
Single comment line:
Code: C
// this line is a comment on ONLY ONE line
Line or paragraph on several lines:
Code: C
/ * this line is a comment, on SEVERAL lines
which will be ignored by the program, but not by anyone who reads the code
;) * /
Accents
It is strictly forbidden to put accents in programming, except in the
comments.
The Variables
As we have seen, in a microcontroller, there are several types of memory. We
will only deal with "live" memory (RAM) and "read-only" memory
(EEPROM).
I'm going to ask you about a problem. Let’s say you’ve connected a push
button to a pin on your Arduino board. How will you store the state of the
button (pressed or off)?
What is a Variable?
A variable is a number. This number is stored in a memory space (RAM) of
the microcontroller. The way to store them is similar to that used to store
shoes: in a numbered locker.
Shoes stored in numbered boxes
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
A Variable is a Number
This number has the distinction of changing its value. Strange, isn't it? Well,
not that much, because a variable is the container of the number in question.
And this container will be stored in a memory box. If we materialize this
explanation by a diagram, it will give:
number => variable => memory
the symbol "=>" meaning: "is contained in..."
Define a Variable
If we give a number to our program, it doesn't know if it's a variable or not.
You have to tell it. For that, we give a type to variables. Yes, because there
are several types of variables. For example, the variable "x" has a value of 4,
so it is an int type.
Code: C
Well, this code would not work because it is not enough. Indeed, there is a
multitude of numbers: whole numbers, decimal numbers, etc. This is why we
must assign a variable to a type.
These are the most common types of variables:
int integer -32,768 to +32,767 16 bit 2 byte
long integer -2 147 483 648 to +2 147 483 647 32 bits 4 bytes
whole char -128 to +127 8 bits 1 byte
decimal float -3.4 x to +3.4 x 32 bit 4 byte
double decimal -3.4 x to +3.4 x 32 bit 4 byte
For example, if our variable "x" only takes decimal values, we will use the
types int, long, or char. If now the variable "x" does not exceed the value 64
or 87, then we will use the char type.
If, on the other hand, x = 260, then we will use the higher type (which accepts
a greater quantity of number) than char, in other words, int or long. But
you're not smart; to avoid overspending, we put everything in double or long.
Yes, but no. A microcontroller is not a 2GHz multicore computer, 4GB of
RAM. Here we are talking about a system that works with a CPU at 16MHz
(0.016 GHz) and 2 KB of SRAM for the RAM. So there are two reasons why
you should choose your variables wisely:
- RAM is not extensible when there is more, and there is more.
- The processor is of the 8-bit type (on Arduino UNO), so it is optimized for
processing on variables of 8-bit size, processing on a 32-bit variable will,
therefore (much) take longer.
If our variable "x" never takes a negative value (-20, -78,...), then we will use
an unsigned type. That is, in our case, a char whose value is no longer from
-128 to +127, but from 0 to 255.
Here is the table of unsigned types, we identify these types by the word
unsigned which precedes them:
Type what number does it store? Maximum values of the stored number,
Number of bits and Number of bytes like below:
unsigned non-negative integer char 0 to 255 - 8 bits, 1 byte
unsigned int non-negative integer 0 to 65,535 - 16 bits, 2 bytes
unsigned long non-negative integer 0 to 4,294,967,295 - 32 bits,
4 bytes
What is a Loop?
In programming, a loop is an instruction that makes it possible to repeat a
piece of code. This will allow us to repeat an end of program or an entire
program.
There are two main types of loops:
The conditional loop tests a condition and executes the instructions it
contains as long as the condition tested is true.
The repeat loop executes the instructions it contains a predetermined number
of times.
Concatenation
A loop is an instruction that has been spread over several lines. But we can
write it on one line:
while(…) {…}
This is why you should not forget the semicolon at the end (after the while).
While in a simple while loop, the semicolon should not be put.
The for loop
This is a very special loop. What it will allow us to do is quite simple. This
loop is executed X times. Unlike the two previous loops, we must give it
three parameters.
First, we create the loop with the term for (means "for that"). Then, between
the parentheses, we must give three parameters which are creation and
assignment of the variable to a starting value followed by the definition of the
condition to be tested followed by the instruction to execute
The Arduino language does not accept the absence of the following line:
We are forced to declare the variable we are going to use (with its type) in the
for a loop.
So, if we link this line: "FOR counter = 0 and counter less than 5, we
increment counter". More concisely, the loop is executed as many times as it
takes counter to get to 5. So here, the code inside the loop will be executed
five times.
The infinite loop
The infinite loop is very simple to achieve, especially since it is sometimes
very useful. You need to use a while and assign it a value that never changes.
In this case, we often put the number
We can read: "As long as the condition is equal to 1, we execute the loop".
And this condition will always be met since "1" is not a variable but a
number. Also, it is possible to put any other whole number, or the boolean
"TRUE":
do {
Block of statements;
}
while(1);
This will not work with the value 0. Indeed, 0 means "false condition," so the
loop will stop immediately... The loop () function behaves like an infinite
loop since it repeats itself after it has finished executing its tasks.
The Functions
In a program, the lines are often numerous. It then becomes imperative to
separate the program into small pieces to improve the readability of it, in
addition to improving the operation and facilitating debugging. We will see
together what a function is, and then we will learn how to create and call
them.
What is a Function?
A function is a "container" but different from the variables. Indeed, a variable
can only contain a number, while a function can contain an entire program.
In fact, when we program our Arduino board, we will write our program in
functions. For the moment, we only know 2: setup () and loop ().
In the previous example, instead of the comment, we can put instructions
(conditions, loops, variables, etc.). This is these instructions that will make up
the program in itself.
To be more concrete, a function is a piece of program that allows you to
perform a specific task. For example, to format a text, you can color a word
in blue, put the word in bold or even enlarge this word.
Bold - to put the word in bold color, to put the word in blue enlarge, to
increase the size of the word in programming, we will use functions. So these
functions are "divided into two large families." What I mean by that is that
there are ready-made functions in the Arduino language and others that we
will have to create ourselves.
You cannot write a program without putting functions inside. We are forced
to use the setup () and loop () function (even if we don't put anything in it). If
you write instructions outside of a function, the Arduino software will
systematically refuse to compile your program. There are only global
variables that you can declare outside of the functions.
Make a Function
To make a function, we need to know three things:
What type of function do I want to create?
What will his name be?
What parameter (s) will it take?
Function Name
To start, we will, first, choose the name of the function. For example, if your
function has to retrieve the temperature of a room supplied by a temperature
sensor: you will call the function RoomTemperaturePiece, or
room_temperature_piece, or lecture_temp_piece.
Well, names can be given full, but be logical about the choice of the latter. It
will be easier to understand the code than if you call it tmp (for temperature).
An explicit function name guarantees quick reading and easy understanding
of the code. A reader should know what the function is doing by name,
without reading the content.
Types and Parameters
The purpose of the functions is to split your program into different logical
units. Ideally, the main program should only use function calls, with minimal
processing. To be able to function, they mostly use "things" as inputs and
return "something" as outputs. The inputs will be called function parameters,
and the output will be called the return value.
The Settings
The parameters are used to feed your function; they are used to give
information to the process it must carry out. Let’s take a concrete example.
To change the state of an output of the microcontroller, Arduino offers the
following function: digitalWrite (pin, value). Thus, the reference explains to
us that the function has the following characteristics:
pin parameter: the number of the pin to be changed
value parameter: the state in which to put the spindle (HIGH,
(high, + 5V) or LOW (low, ground))
return: no return of result
As you can see, the example is self-explanatory without reading the function
code. Its name, digitalWrite ("digital writing" for anglophobes), means that
we will change the state of a digital pin (therefore not analog). Its parameters
also have explicit names, pin for the pin to change, and value for the state to
give it.
When you go to create functions, it is up to you to see if they need parameters
or not. For example, you want to do a function that pauses your program, and
you can do a Pause () function that takes a parameter of type char or int, etc.
(this will depend on the size of the variable). This variable will, therefore, be
the parameter of our Pause () function and will determine the duration during
which the program will be paused.
We will, therefore, obtain, for example, the following syntax: void Pause
(char duration).
To sum up a bit, we have the choice of creating empty functions, therefore
without parameters, or else "typed" functions that accept one or more
parameters.
Empty Functions
We have seen that a function could accept parameters. But it is not
compulsory. A function that does not accept parameters is empty.
We, therefore, use the void type to say that the function will have no
parameters. A void type function cannot return a value. For example:
void Arrange(int left,int right){
int i,j,x,w;
i=left,j=right;
x=(left+right)/2;
do{
while(struct[i].number < struct[x].number)i++;
while(struct[j].number > struct[x].number)j--;
if(i<=j){
w=struct[i].number;
struct[i].number=struct[j].number;
struct[j].number=w;
i++;j--;
}}while(i<=j);
if(left<j)
return Arrange(left,j); //1st recursive call. It doesn't work.
if(right>i)
return Arrange(i,right); //2nd recursive call.It doesn't work either.
};
This code will not work because the function () is of type void. However, it
must return a variable that is of type int. Which is impossible.
The Tables
As the name suggests, this part will talk about tables.
What is the point of talking about this? Well, think again, on the computer a
table has nothing to do. If we had a lot to summarize, an array is a big
variable. Its purpose is to store elements of the same types by putting them in
boxes. For example, a teacher who stores the grades of his students will use a
floating table (a floating-point number) with one box per student.
We will use this example throughout this section. Here are some details to
understand everything: each pupil will be identified by a number going from
0 (the first pupil) to 19 (the twentieth pupil of the class) one starts from 0
because in data processing the first value in a table is 0.
A Table in Programming
A table, like in Excel, is a set made up of boxes, which will contain
information. In programming, this information will be numbered. Each box in
an array will contain a value.
Average Calculation
Here, we will look for the average of the grades. The signature of the function
will be exactly the same as that of the previous function, unlike the name. Let
you think, here is the signature of the function, the code is lower but try to
find it yourself before:
Code: C
float mediumNote (float array [], int numberHigh)
A solution:
Secret (click to display)
Code: C
float mediumNote (float array [], int numberHigh)
{
int i = 0;
double total = 0; // add all the grades
average float = 0; // average of grades
for (i = 0; i <highNumber; i ++)
{
total = total + table [i];
}
mean = total / number High;
average return;
}
We finish with the tables, we may see more things in practice.
Now you are joyful because you have finished the first part.
You are ready to start using your card. So go to the next part of the book.
Chapter 2
Now that you have gained enough programming knowledge and some
notions of electronics from the previous chapter and in this chapter, we will
look at the use of the Arduino board. I will tell you about the inputs and
outputs of the card. We are going to start simply, so do not be surprised if
you go quickly to reading the chapters.
Do not neglect the basics; otherwise, you may not be able to follow the more
complex chapters. A piece of advice – make sure you understand everything
before you move on – there is no rush; everyone should work at their own
pace.
Where do we start?
The Goal
The aim of this first program is to light an LED, however, it may feel
somewhat tricky here but everything will be in control over time. The plan is
to show you two or three things that can help you when you want to leave the
nest and take the flight to new skies.
Equipment
To be able to program, you obviously need an Arduino board and an USB
cable to connect the board to the PC. But to see the outcome of your program,
you will need additional items. In particular, an LED and a resistor.
Production
With the pinout of the Arduino board, you will need to connect the larger tab
to the + 5V (5V pin). The smallest tab being connected to the resistor, itself
connected to pin number 2 on the card. We could do the opposite, connect the
LED to the ground and turn it on by supplying 5V from the signal pin.
However, components like microcontrollers do not like to deliver current too
much, and they prefer to absorb it. For this, we will, therefore, prefer to
power the LED by placing it at + 5V and putting the Arduino pin to ground to
pass the current. If we put the pin at 5V, in this case, the potential is the same
on each side of the LED, and it does not light up.
The Program
Normally, its design should not cause you any problems. It suffices to
retrieve the code of the previous program ("light a group of LEDs") and
modify it according to our needs.
This code, I give it to you, with the comments that go well:
Code: C
// we keep the same start as the previous program
const int L1 = 2; // pin 2 of the microcontroller is now called: L1
const int L2 = 3; // pin 3 of the microcontroller is now called: L2
const int L3 = 4; //...
const int L4 = 5; const int L5 = 6; const int L6 = 7;
void setup ()
{
pinMode (L1, OUTPUT); // L1 is a pinMode output pin (L2, OUTPUT);
// L2 is a pinMode output pin (L3, OUTPUT); //...
pinMode (L4, OUTPUT); pinMode (L5, OUTPUT); pinMode (L6,
OUTPUT);
}
// we change the inside of the loop to reach our goal
void loop () // the loop () function executes the following code by
repeating it in a loop
{
digitalWrite (L1, LOW); // switch on L1 delay (1000); // wait 1 second
digitalWrite (L1, HIGH); // we extinguish L1
digitalWrite (L2, LOW); // we switch on L2 at the same time as we
switch off L1
delay (1000); // we wait 1 second digitalWrite (L2, HIGH); // we turn off
L2 and digitalWrite (L3, LOW); // we immediately turn on L3 delay
(1000); //...
digitalWrite (L3, HIGH); digitalWrite (L4, LOW); delay (1000);
digitalWrite (L4, HIGH); digitalWrite (L5, LOW); delay (1000);
digitalWrite (L5, HIGH); digitalWrite (L6, LOW); delay (1000);
digitalWrite (L6, HIGH);
}
As you can see, this code is very heavy and not practical. We will see later
how to make it lighter. But before that, a TP arrives...
Millis () Function
We will end this chapter with a point that can be useful, especially in certain
situations where we do not want to stop the program. If you want to flash an
LED without stopping the execution of the program, you cannot use the delay
() function, which pauses the program for the defined time.
1. Variables to Name
In the first area, elements have named the program (What that means, we
learn in the program No. 3). This part is not mandatory.
Instructions
A Flashing LED
Task: A light-emitting diode to blink.
Material: Only the microcontroller board with the USB cable.
On the Arduino, an LED is connected to pin 13 is already installed (for test
purposes). Often this light blinks on when you connect a new Arduino board,
as the flashing program is already pre-installed for testing the board
depending on the manufacturer. We will program this flashing now itself.
Circuit
The existing on the board
LED is circled in red in the diagram.
You have to connect to the computer, only the board via an USB cable.
1.1 Program Section 1: variable name
- Here we go, first nothing.
In part between the braces, we now introduce the setup information. In this
case, "an output pin 13 is supposed to be."
void set up() // Here the setup starts
{ // Here a program section starts.
pinMode(13, OUTPUT); // Pin 13 is what the output should be.
} // Here, a program segment ends.
Finished. The sketch should now look exactly as it appears on the screen is
shown on the right. It has to be now uploaded to the board. This works with
the red circled button (top left of the software).
1.4 Now we can create variation to the program. For example, the LED will
blink rapidly. To do this, we reduce waiting times (from 1000ms to 200ms)
void set up() // Here the setup starts
{ // Here a program section starts.
pinMode(13, OUTPUT); // pin 13 to be an output.
} // Here, a program segment ends. void loop() // Here the main
program begins
{ // Program section begins.
digitalWrite(13, HIGH); // Turn the the voltage at pin 13 a (LED on).
delay(200); // Wait 200 milliseconds
digitalWrite(13, LOW); // Turn the the voltage at pin 13 from (LED
off). delay(200); // Wait 200 milliseconds
} // Program section completed.
The new Sketch must now again be uploaded to the board. If all goes well,
the LED is now flashing faster.
Sketch:
int LED = 9; // The word "LED" is now available for the value. 9
int Brightness = 0; // The word "brightness" is now available for the
value in the
// PWM output. The number 0 is only an arbitrary starting value.
int fade steps = 5; // fade steps: determines the speed of the "thread"
void set up()
{ // Here the setup starts.
pinMode(LED, OUTPUT); //// The pin with the LED (Pin9) is an output
}
void loop()
{
analog write(LED, brightness); // The function analog write is here at
the
// Pin activated with the LED (Pin9) the PWM output. The PWM value
is the value
// stored under the name of "brightness". In this case, "0" (See
// first program section)
brightness + = brightness fade steps; // Now, the value of the PWM
output
// changed. Under the value "brightness" is now the previous brightness
// the value for the fade steps added. In this case: brightness = 0 + 5. The
// new value for "brightness" is therefore no longer 0 but 5. Once the
loop
// part is once gone through, he repeats. Then the value is for
// the brightness of 10. In the next cycle 15, etc., etc...
delay(25); // The LED should for 25ms (milliseconds), so only very
briefly
// maintained brightness. Decreasing this value, the pulsation
// also faster.
if(Brightness == 0 || brightness == 255) { // Command explanation:
When the
// brightness has reached the value 0 ORDER 255, the value for the
change
// "fade steps" from positive to negative or vice versa. Reason: The LED
is
always a bit brighter // first with each pass of the loop part.
// However, at some point the maximum value for the PWM output with
the value 255
//reached. The LED will then gradually become darker. So
// the value for the "fade steps" is at this point Negating (A
// minus sign is placed in front of it)
fade steps = -fadeschritte; // That means for the next pass that in
// the line "brightness = brightness + fade steps," the brightness
decreases.
// Example: "brightness = 255 + (- 5)". The value of brightness is from
then 250. In
// next pass 245, etc., etc... Once the value for brightness at 0
// has arrived, returns the sign. (Consider the old
// mathematical rule: "minus and minus gives plus").
}
} // This last clip of the loop portion is closed.
Sketch:
// This time, we also use the first program section. We enter
// variables. This means that behind a letter or
// one word hides a number. For us, the LED on pin 4 is connected and
// the piezo speaker to pin 5. This is the two pins later not
// confused, we call Pin4 and Pin5 simply.
int LED = 4; // The word "LED" is now available for the number "4".
int pieps = 5; // The word "beep" is now available for the number "5".
void set up()
{ // We start with the setup.
pinMode(LED, OUTPUT); // pin 4 (pin "LED") is an output.
pinMode(Beeping, OUTPUT); // Pin 5 (Pin "beep") is
an output.
}
void loop()
{ // The main program starts. digitalWrite(LED, HIGH); // Turn
the light on
digitalWrite(Beeping, HIGH); // Switch to the piezo speaker.
delay(1000); // wait 1000 milliseconds. (It beeps and lights
up.)digitalWrite(LED, LOW); // Switch from LED.
digitalWrite(Beeping, LOW); // Turn on the piezo out.
delay(1000); // wait 1000 milliseconds. (No noise, no light)
} // Here at the end of the program jumps to the start of the loop part. so
becomes
// it beeps again and lights. If one reduces the pause (delay)
// or enlarged beeps and lights it faster or slower.
Sketch:
int LEDblue = 6; // The word "LEDblue" is now available for the
value. 6
int taster = 7;// The word "taster" is now available for the value. 7
int button status = 0; // The word "taster status" is now available for
the first
// value 0 is later stored under this variable, if the button is pressed
// or not. void set up()
{ // Here the setup starts.
pinMode(LEDblue, OUTPUT); // The pin with the LED (pin 6) is now
an output. pinMode(Push buttons, INPUT); // The pin with the button
(pin 7) is now an entrance.
}
void loop()
{ // This clip the loop portion is opened taster status =digital
read(Button); // Here the Pin7 is read
// (Command: digital read). The result is below the variable "taster
status" with
// the value "HIGH" for 5V or "LOW" saved for 0Volt.
if (Taster status == HIGH) // Processing: When the pushbutton is
pressed (The
// voltage signal is high)..
{ Open // Program section of the IF command. digitalWrite(LEDblue,
HIGH); //..dann should light up the LED..
delay(5000); Although for //..und for 5 seconds (5000 milliseconds).
digitalWrite(LEDblue, LOW); // then the LED off should be.
} // close the program section of the IF command. else //...
otherwise...
{ Open // Program section of the else command digitalWrite(LEDblue,
LOW); //... to be the LED off.
} // close the program section of the else command
} // This last clip of the loop part closed.
Sketch 1:
In this code, the three individual colors are sequentially switched on and off.
int LEDblue = 3; // color blue to pin 3 int LEDrot = 5; // color red on pin
5 int LEDgreen = 6; // color green to pin 6
int p = 1000; // p is a break with 1000ms So one second
int brightness1a = 150; // numerical value between 0 and 255 - are
// the luminance of each color at
int brightness1b = 150; // numerical value between 0 and 255 - are
// the luminance of each color at
int brightness1c = 150; // numerical value between 0 and 255 - are
// the luminance of each color at
int dark = 0; // Neumericalvalue 0 means 0V - so LED off void set up()
{
pinMode(LEDblue, OUTPUT); pinMode(LEDgreen, OUTPUT);
pinMode(LEDrot, OUTPUT);
}
void loop()
{
analog write(LEDblue, brightness1a); // turn blue delay(P); // Break
analog write(LEDblue, dark); off // blue analog write(LEDrot,
brightness1b); // turn on red delay(P); // Break
analog write(LEDrot, dark); rotausschalten //
analog write(LEDgreen, brightness1c); turn green // delay(P); // Break
analog write(LEDgreen, dark); // greenausschalten
}
Sketch 2:
In this code, the three individual colors are in pairs on and off in sequence.
Thereby, the color mixing yellow, turquoise, and purple arise.
int LEDblue = 3; // color blue to pin 3 int LEDrot = 5; // color red on pin
5 int LEDgreen = 6; // color green to pin 6
int p = 1000; // p is a break with 1000ms So one second
int brightness1a = 150; // numerical value between 0 and 255 - are
// the luminance of each color at
int brightness1b = 150; // numerical value between 0 and 255 - are
// the luminance of each color at
int brightness1c = 150; // numerical value between 0 and 255 - are
// the luminance of each color at
int dark = 0; // value 0 means 0V - so LED
//out
void set up()
{
pinMode(LEDblue, OUTPUT); pinMode(LEDgreen, OUTPUT);
pinMode(LEDrot, OUTPUT);
}
void loop()
{
analog write(LEDgreen, brightness1c); // green and red on yellow =
analog write(LEDrot, brightness1b);
delay(P);
analog write(LEDgreen, dark); // green and red from yellow = from
analog write(LEDrot, dark);
analog write(LEDgreen, brightness1c); // green, and blue =
//turquoise
analog write(LEDblue, brightness1b); delay(P);
analog write(LEDgreen, dark); // green and blue from turquoise from =
analog write(LEDblue, dark);
analog write(LEDrot, brightness1b); // red and blue = purple analog
write(LEDblue, brightness1b);
delay(P);
analog write(LEDrot, dark); // red and blue from purple from = analog
write(LEDblue, dark)
}
The Motion
Task: A piezo speaker to beep when motion is detected. Material: Arduino /
Motion / Breadboard / cable / piezo speaker
Course content: voltage of a motion to read and use for output.
The motion, also called the PIR sensor, is very simple in construction.
Once it detects motion, it is on a pin a voltage
of 5 volts. This only needs to be read and processed by the microcontroller.
Two knobs can ad the duration of the output signal and sensitivity (range).
The plastic lens is lightly connected. If one sets them apart can be seen the
infrared detector and can be seen from the label under the lens, as the sensor
has to be wired: GND (-), OUT (output of the signal), VCC (+).
There is also a jumper which allows you to switch between two modes at the
bottom of the movement.
1. A jumper is quite outside: it detects The output signal after it
maintained a motion for a certain time and then deactivated
definitely be back, even if there is a movement that could be
detected in the action area of the motion. After a certain time, the
output signal is generated again.
2. The jumper is like a right slightly offset on the image inside. The
output signal remains constantly active as long as the motion is
detected a movement and this mode is recommended for Arduino
projects.
Sketch:
int piezo = 5; // The word "piezo" is now available for the value. 5
int motion = 7; // The word "movement" is now available for the value. 7
int motion status = 0; // The word "movement status" first, is now
available for the
// value 0 is later stored under this variable, whether a movement
// is recognized or not.
void set up() // Here the setup starts.
{
pinMode(Piezo, OUTPUT); // The pin with the piezo (pin 5) is now an
output. pinMode(Move, INPUT); // The pin with the motion detector
(pin 7) is now
//an entrance.
}
void loop() // The loop part begins
{ // This brace is the Loop section opened. motion status =digital
read(Move); // ier of Pin7 is read. The
// result is under the variable "moving status" with the value "HIGH" for
// 5V or "LOW" saved for 0Volt.
if (Movement status == HIGH) // processing: When motion is detected
// (The voltage signal is high)
{ Open // Program section of the IF command. digitalWrite(Piezo,
HIGH); // then the piezo will beep. delay(5000); Although //...and for 5
seconds. digitalWrite(Piezo, LOW); //...then it should be quiet.
} // close the program section of the IF command. else //otherwise...
{ Open // Program section of the else command.
digitalWrite(Piezo, LOW); //...should the piezo speaker to be.
} // close the program section of the else command.
} // This last clip of the loop portion is closed.
Read Voltages
The microcontroller is to read about a photoresistor how bright it is. For this,
one uses a simple physical principle. If in a circuit two consumers are
connected one behind the other (in series), then "shared" it is also commonly
applied voltage. An example: two identical lamps connected in series, and
there is applied a voltage of 6 volts.
Then you can determine with a voltmeter that each abut the lamps only 3
volts. If we connect two unequal lamps (One has a lower resistance), then one
can use two different voltages to the two lamps measure, for example. 1.5
volts and 4.5 volts. A photoresistor changes its resistance as a function of
light intensity. This effect is exploited so one can generate a voltage division
here at all, and it closes the photoresistor and a resistor (1 - 10 K ohms,
depending on the photoresistor. The resistor should have a similar resistance
value as that of the photoresistor have.) in series and connects it to 5 volts
and the "grounding" (ground / GND) - see construction. The microcontroller
board is to measure capability of analog signals (voltage) and to process
these.
We can do this with the analog inputs on the board and this converts the
measured voltage value into a number that can then be further processed. 0
volt corresponds to the number 0, and the highest measured value 5 volts
corresponds to the number 1023 (0 to 1023 equals 1024 digits = 10 bits).
Example: A voltage of 2.5 volts is measured, then the microcontroller returns
the value 512 (1024: 2).
Sketch:
int input = A0; // The word "input" is now available for the value
"A0" (name
// the analog port 0)
int LED = 10;// The word "LED" is now available for the value 10
int Sensor value = 0; // variable for the sensor value with 0 as the
start value
void set up() // Here the setup starts.
{
Serial.begin(9600); // Communication with the serial port
// started. This one needs to be the actual value read later
let // Display serial monitor in.
pinMode (LED,OUTPUT); // The pin with the LED (pin 10) is now an
output
}
void loop()
{ // This brace is the Loop section opened. Sensor value =analog
read(entrance); // Read the voltage on the photoresistor
// store and under the variable "sensor value". Serial.print("Sensor value
=");// Output on Serial Monitor: The word "sensor value"
Serial.print(Sensor value); // Output on Serial Monitor. The
command
the sensor value of the photoresistor is in the form of a number
//Serial.print
// sent 0-1023 to the serial monitor.
if(Sensor value> 512) // If the sensor value is over 512....
{
digitalWrite(LED,HIGH); //... is to light the LED...
}
else
{
digitalWrite(LED,LOW); //... otherwise, they will not shine
}
delay(50); // A short break, during which the LED is on or off
} // This last clip of the loop portion is closed.
// Now, if the sensor value, for example, at normal brightness. Only the
value of 100 has
// (The value depends on the used resistors of the brightness
// and of the current direction), then take the place of the value 512
// much smaller value at which the LED will begin to glow. For
example.
// then you take the value of 90. The current sensor value you can now
use
// using the "Serial monitor" display. Click at the top "Tools."
// and then click "serial monitor."
Knobs
Task: An LED should blink. The blink rate is to be added with a knob.
Material: Arduino / a knob (potentiometer) / Breadboard/cable read voltage
of a rotary control, processing sensor values, and mathematically to use for
output (in this case, for the duration of a pause): learning content.
A knob has three terminals. Outside is + and - connected. From the middle,
pin cable goes to an analog input pin on the microcontroller board. By
turning the knob, the middle pin outputs a voltage between 0 and 5 volts.
Knobs far left: 0 V and knobs on the far right: 5V, or mirror-inverted
depending on the wiring.
As LED should blink, we use as the first sketch the LED, which is secured by
pin 13 on the microcontroller. In addition, it still connects further LEDs.
Sketch:
int input = A0; // The word "input" is now available for the value
"A0" (name
// the analog port 0)
int LED = 13;// The word "LED" is now available for the value 13
int Sensor value = 0; // variable for the sensor value with 0 as the
start value void set up()
{ // Here the setup starts.
pinMode (LED,OUTPUT); // The pin with the LED (pin 13) is now an
output.
}
void loop()
{ // This brace is the Loop section opened.
Sensor value = analog read(entrance); // The voltage on the control
dial will read
// and in the previous sketch as a number from 0 to 1023 under the
variable
// "sensor value" stored.
digitalWrite (LED,HIGH); // The LED is turned on
delay(Sensor value); // The LED remains on for so many
milliseconds,
// as the value of "sensor value" it has stored. digitalWrite(LED,
LOW); // The LED is turned off.
delay(Sensor value); // The LED remains off for so many
milliseconds,
// as the value of "sensor value" it has stored.
} // This clip the loop portion is closed
// The loop part is now restarted. If the value of the read
// knob changes, then the time between the input and output changes
// phases of the LED. The flashing is faster and slower. The longest
In this skit // delay is 1023ms (milliseconds). If you long delays
// required then builds to a small mathematical line in the code.
// For example, to change the line "sensor value = analog read (input),"
in
// "sensor value = analog read (input) * 2;" This is the stored sensor
value
// magnified by a factor 2nd Since longest delay would be 2046ms etc.
Measure Temperatures
Task: With the temperature sensor TMP36, the temperature should read and
display monitor serial-by.
Material: Arduino / Breadboard / cable / Temperature Sensor TMP36 /
External Power Supply
The sensor has three connections. When looking at the flat side of the sensor:
left 5V, GND, and right in the middle of the pin for the temperature signal.
On this pin, the sensor outputs a voltage between 0 and 2.0 volts. Wherein 0V
-50 ° C and the corresponding value of 2.0V corresponds to 150 ° C.
According to the manufacturer, the sensor is between -40 ° C and + 125 ° C
with reasonable accuracy (± 2 ° C). The voltage of this pin has to read from
the microcontroller board and converted into a temperature value.
NOTE:
If the sensor is connected incorrectly, it will burn out.
In the structure of an external power supply should be used if
possible, as it improves considerably the sensor accuracy (9V
AC adapter or 9V battery).
Sketch:
int TMP36 = A0; // The sensor A0 is to be connected to the analog
pin. We
// call the pin from now "TMP36"
int temperature = 0; // Under the variable "temperature" is later
// temperature value stored
int temp [10];// This yields good values, you first read multiple values
// and then averages the results. The square bracket "[10]" generated
here
// equal to ten variables named "temp [0],” "temp [2],” "temp [3]"... to...
//"temp[9]".Mit the notation [10] So you can save only a
little Place.
int time= 20; // The value for "time" is in the code, the time intervals
// ago between the individual measurements. void set up() {
Serial.begin(9600); // In the setup we start serial communication so
// we can show us the temperature later. About the serial
// communication the board, sending measurements to the computer. In
the Arduino
// software can be under "Tools" the "Serial Monitor" start the readings
// to see.
}
void loop() {
temp [0] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [1] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [2] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [3] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [4] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [5] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [6] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [7] = map(analog read(TMP36),0 410 -50, 150);
delay(time);
temp [8] = map(analog read(TMP36), 0, 410, -50, 150); delay(time);
temp [9] = map(analog read(TMP36), 0, 410, -50, 150); // From
here is ten times the
read // temperature. In between is ever a break with the duration
// "time" in milliseconds. But what happens here, exactly? Let's look at
the
// command once more closely.
// temp [1] = map (analog read (TMP36), 0, 410, -50, 150);
//Sequentially:
// temp [1] - is the name of the first variable.
// "map (a, b, c, d, e)" - This is the so-called "Map command". Allows
// to a read-in value (a) in which the values between (b) and (c) lie,
// convert it into a different speed range, and that (d) in the area between
// and (e).
// following our command happens:
// the value of the sensor is read out directly in the "Map" command with
// "analog read (TMP36)". The measured values should be between 0
and 410th The
// corresponds to the analog port of the values between 0V and 2V. is the
voltage
// the sensor out at temperatures between -50 ° C and + 150 ° C. These
values on
// analog port will now be through the "Map command" directly to the
Celsius values
// -50 to 150 converted.
temperature = (temp [0] + temp [1] + temp [2] + temp [3] + temp [4] +
temp [5] + temp [6] + temp [7] + temp temp [8] + [ 9]) / 10; // All in a
row. Here every ten are found
// temperature values added together and divided by ten. The
// average value is stored under the variable "temperature"
Serial.print(temperature); // Now, the value of "temperature" over
the serial
// sent communications to the PC. Now you have the serial monitor in
the
// Open Arduino software to the temperature at the sensor to read.
Serial.println("Degree");
}
Expansion of the Program:
Once the temperature has reached 30 ° C, to a warning sound (beep of a piezo
speaker).
int TMP36 = A0;
int temperature = 0; int temp [10];
int time= 20;
int piezo = 5; // The word "piezo" is now the number 5, that is to port 5 of
the
// Piezo connected. void set up() { Serial.begin(9600);
pinMode (Piezo, OUTPUT); // The piezo speaker to pin 5 should be a
starting
// (logical because of the yes from the microcontroller board yes a voltage
required to
// beeping.
}
void loop() {
temp [0] = map(analog 0 410 -50, 150);
read(TMP36),
delay(time); 0 410 -50, 150);
temp [1] = map(analog read(TMP36),
Measure Distance
Task: the ultrasonic sensor HC-SR04 and a microcontroller Arduino a
distance to be measured and displayed with the "serial-monitor".
How does the ultrasonic sensor? The sensor has four terminals.
a) 5V (+) b) GND (-) c) echo d) trigger
The connections 5V and GND are self-evident; they supply the sensor with
power.
The "trigger" of the contacts inserts a short signal (5 V) into the
microcontroller board, causing an acoustic wave through the ultrasonic
sensor. Once the sound wave hits a wall or other object, it is reflected and at
some point reaches the ultrasonic transducer again.
Once the transducer detects these reflected sound waves, it sends a 5V signal
to the "echo" contact on the microcontroller board. The microcontroller only
measures the time between the radiation and the return of the sound wave and
converts this time into distance. Here we go.
Material: microcontroller board / cable / Breadboard / Hc-SR04 ultrasonic
sensor
Code:
int trigger = 7; trigger // The word is now the number. 7 int echo =
6; // The word echo is now the number sixth
long time = 0; life // The word is now a variable under which the
time
// is stored, to the reflection and requires a sound wave back.
// Start value here 0th
long distance = 0; // The word "distance" is now variable, under the
is stored // the calculated distance.
// Info: Instead of "int" is faced with the two variables "long." That has
// the advantage that a larger number can be saved. Disadvantage:
// variable takes up more space in memory. void set up()
{
Serial.begin (9600);// start communication Serial, so you later
can view the serial monitor // values.
pinMode(Trigger, OUTPUT); // "trigger" (pin 7) is an output.
pinMode(echo, INPUT); // "echo" (pin 6) is an input.
}
void loop()
{
digitalWrite(Trigger, LOW); // Here, take the voltage for a short
period
// trigger pin, so that one later sending the trigger signal a noise-free
// Signal.
delay(5); // Duration: 5 milliseconds
digitalWrite(Trigger, HIGH); // Now you send off an
ultrasonic wave delay(10); // This "tone" is heard for 10
milliseconds. digitalWrite(Trigger, LOW); // Then the "tone" is
turned off.
duration = pulseIn(echo, HIGH); // The command "pulseIn" is one
of the
// microcontroller the time in milliseconds until the sound to
// ultrasonic sensor returns.
Distance = (time / 2) / 29.1; // Now we calculate the distance in
// centimeters. First, you divide the time by two (because only one
// Section wants to calculate and not back the track and back). The value
// can still be divided by 1.29 and then receives the value in centimeters
because of the
// sound in the air at a speed of one centimeter per 29.1
// microseconds.
// Example: The sensor measures time from 2000 microseconds. These
are then
// 1000 microseconds each way. Now one in 1000 because of the sound
divided by 1.29 (
// yes 1cm travels per 29.1 microseconds) and receives the value 34,3cm
{
digitalWrite(Trigger, LOW);
delay(5); digitalWrite(Trigger, HIGH); delay(10); digitalWrite(Trigger,
LOW); duration =pulseIn(echo, HIGH); Distance = (time / 2) / 29.1;
if (Distance> = 500 || distance <= 0)
{
Serial.println("No reading");
}
else
{
Serial.print(distance); Serial.println("cm");
}
if (Distance <= 80) // If the value for the distance below or equal to 80
//, then...
{
digitalWrite(Piezo,HIGH); //... start beeping.
}
else // And if that is not so...
{
digitalWrite(Piezo,LOW); //... then be quiet.
}
delay(1000);
}
Code:
/*
* IrRemote: IRrecvDemo - Demonstrates receiving IR codes with
IRrecv
* An IR detector/demodulator must be connected to the input
RECV_PIN.
* Version 0.1 July 2009
* Copyright 2009 Ken Shirriff
* http://arcfn.com
* /// Information over the original program
"IrrecvDemo". #include <Irremote.h> // The program
encroaches on a
// "Library" back. This does a lot of work. Because of the infrared light
// will be encrypted with a code. To read this code itself
// convert and appropriate values, a lot of lines of code would be
required.
int RECV_PIN = 11; // outputs The contact of the infrared sensor
data,
// is connected to pin 11 of the Arduinoboards.
IRrecv irrecv (RECV_PIN); // At this point, an object is defined
that
// reads the infrared sensor to pin. 11
decode_results results; // This command ensures that the
data by
// infrared is read stored under "results."
void set up()
{
Serial.begin(9600); // In the setup the serial connection is started, so
// you look at the data to receive the remote control via the serial monitor
// can.
pinMode (13, OUTPUT);
irrecv.enableIRIn();// This command initializes the infrared receiver.
}
void loop()
{ // The loop portion turns out very shortly by resorting to the "library".
if (irrecv.decode(Results)) { // If data has been received,
Serial.println (results.value, DEC); // they are as a decimal (DEC) to the
// Serial Monitor output.
irrecv.resume(); // The next value to be read from the IR receiver
}
One press on the button "1" of the infrared remote control unit causes the
number "16724175" is output at the Serial Monitor. This is the decoded
numerical code behind this button.
If you hold the button down permanently, the number "4294967295" is
displayed permanently. This indicates the code that a key is pressed
permanently. This number is regardless of which button is pressed, but it can
also appear other numbers if a button is pushed only very short or pulsed. In
this case, the sensor can read no unique value.
Expansion of the Program:
When pressing the "1" LED will go on and on pressing the button "2,” the
LED will go out.
#include <Irremote.h> int RECV_PIN = 11;
IRrecv irrecv (RECV_PIN);
decode_results results; void set up()
{
Serial.begin(9600);
pinMode (13, OUTPUT); // To pin 13 an LED is connected.
digitalWrite(13, LOW); // This should first of all be
irrecv.enableIRIn();
}
void loop() {
if (irrecv.decode(Results)) { Serial.println(Results.value, DEC);
if (Results.value == 16724175)// If the infrared receiver, the number
// read "16724175" (the key According to "1" on the remote control) has
{digitalWrite (13, HIGH)} // the LED should go on.
if (Results.value == 16718055)// If the infrared receiver, the number
// read has "16718055" (corresponding to "2" of the remote control
button)
{digitalWrite (13, LOW)} // the LED should go out. irrecv.resume();
}
}
Servo Drive
Task: A servo is to be controlled by an Arduino microcontroller. The servo
should drive to three different positions in this example and wait a short time
between positions.
Material: A microcontroller board, a servo, three plug-in cable
Code:
#include <Power.h> // The servo library is called.
Power servo-blue; // Create the program a servo with the name
// "servo blue"
void set up()
{
servo blue.attach(8th); // servo is connected to Pin8
}
void loop()
{
servo blue.write(0); // Position 1 controlled with the angle 0 °
delay(3000); // The program stops for 3 seconds servo
blue.write(90); // position 2 controlled with the angle 90
° delay(3000); // The program stops for 3 seconds servo
blue.write(180); // position 3 controlled with
the angle 180 ° delay(3000); // The program stops for 3 seconds
servo blue.write(20); // position 4 controlled with the angle 20 °
delay(3000); // The program stops for 3 seconds
}
LCD Display
Task: An LCD display is to be controlled with an Arduino microcontroller.
After that, a predetermined text should appear as in the following example
photo on display.
Material: Microcontroller Board (In this example, UN R3), a wheel (or
potentiometer), jumper cables 14, Breadboard
Based on the material and the sketch, you quickly realize that the wiring is
not so easy. This is because the LCD display must be connected to a large
number of cables. Another difficulty is with which one could connect the
cables missing sockets.
Therefore, it is advisable to solder a terminal strip or to solder the cable
directly to the LCD. In the second case, it is advisable to use a ribbon cable
(for example, from old IDE drives like hard disks, CD or DVD drives).
Without a soldered connection, it is almost impossible to achieve good
results.
The knob is there to ad the contrast of the LCD. The LED backlight, as
shown in the sketch supplied with 5V. Since it would not recognize the label
on the LCD in the sketch, it is not shown. You have, therefore, the position of
the cable to the LCD counting (Example: The LCD is the first cable from the
right GND.
The second cable from the right is connected to 5V, etc.). Info: For quick
tinkering, many hobbyists prefer to use an LCD Keypad Shield or I2C LCD
because you do not have to worry about the two alternatives to the wiring of
the LCD must. However, the two alternatives mentioned above are also more
expensive.
If you have successfully made the wiring, you can take the software with
many other components, and use is made here to a "Library." The Library for
the LCD display is part of the Arduino software and must not be installed
separately.
Code:
#include <Liquid Crystal.h> // Load LCD library
Liquid Crystal LCD (12, 11, 5, 4, 3, 2); // This line is set,
// which pins is the microcontroller boards used for the LCD (Best
// first do not change). void set up() {
lcd.begin(16, 2); // In the Setup specifies how many characters and
lines are applied. Here: 16 characters in 2 lines
}
void loop() {
lcd.setCursor(0, 0); Set the LCD // start position of the display.
// Means: The first character in the primal line.
lcd.print("Www.xyz.com"); // There should text "Www.xyz.com"
//appear.
lcd.setCursor(0, 1); // lcd.setCursor (0.1) means: First character in the
// second line.
lcd.print("I wish you success..."); // There will be the text "Good
luck ..."
//Pop up.
}
A variation: to alternately first up and then down a text message display. In
this example, the text "up" and "down".
#include <Liquid Crystal.h> Liquid Crystal LCD (12, 11, 5, 4, 3, 2);
void set up() {
lcd.begin(16, 2);
}
void loop() {
lcd.setCursor(0, 0); // start at the first character in the first line with the
// text "Up." lcd.print("Above");
delay (2000); Wait // Two seconds. lcd.clear(); //
Clear display.
lcd.setCursor(5, 1); // Renewed beginning at the fifth character in the
second
// line with the text "Down". lcd.print("Below");
delay (2000); Wait // Two seconds. lcd.clear(); //
Clear display.
}
An LCD is particularly well suited to sensor values or other issues of
microcontroller boards display. For more help, you get, for example, in the
Arduino software. Among the sample Sketches, one finds a number of
different examples under the menu item "Liquid Crystal."
Relay Card
When tinkering with Arduino relay is very important. Relays are switches
that can flow a larger current than would be possible by the microcontroller.
With the Arduino, so you now enabled only a very small current relay, which
can then also run large electrical items.
The relay card is connected to the Arduino to the contacts (in the photo on the
right edge, between the red and green LED). The card is in operation
permanently + 5V and GND - connected (). The pin labeled "IN" is
connected to a pin of the digital Arduino boards. As long as at pin "IN" no
signal (output from the digital pin of Arduino), the screw terminals A and B
are connected together. As soon as a signal is present, contacts B and C are
connected to each other.
Warning: relay cards that switch when applied to the pin "IN" GND, and
there are relay cards that switch when applied to the pin "IN,” a voltage of 5V
+. Which version you can easily tell by combining the "signal" Pin once with
GND and once with 5V + Arduino boards. A loud crack can clearly see the
switching of the relay card.We can connect an electric device, at which a
higher electric current flows as if it could provide the Arduino to the bottom
contacts (A, B, C). For example, a large electric motor, a large lamp, etc.
As an example code, in this case, the simple "blink" code can be used. In
place of the LED, you to close the output pin of the Arduino boards to the
"signal" Pin the relay card. The relay will then switch every second.
Code:
void set up()
{
pinMode(6, OUTPUT);
}
void loop()
{
digitalWrite(6, HIGH); // At this point, would one turn on the relay
delay(1000); //... wait a second
digitalWrite(6, LOW); And off again //
delay(1000); //... and wait a second.
}
Stepper Motor
In this step, the motor is a stepper motor suitable for small applications with
the Arduino board. The special feature is that we can operate it without an
external power supply. The motor develops a relatively high torque. This is
realized by a transmission, which has been installed within the metal casing
before the actual step motor.
This makes it possible at all in this compact design, is that a complete
revolution of the driveshaft to 2048 individual steps can be divided. A small
resultant disadvantage is the slow maximum rotational speed.
We connect the stepper motor to a motor control board. This supplies the
engine with sufficient electrical power so that the power need not apply to the
digital pins on the Arduino board. The control board is available in two
versions, in which the side-mounted pins are protruding either upward or
downward out of the board. However, the pin assignment is the same.
Cabling
PIN2 the Arduino board to IN4 of the motor control board - 2 to 4
PIN 3 on the Arduino board to IN2, the motor control board - 3 to 2
PIN4 the Arduino board to IN3 of the motor control board - 4 to 3
PIN 5 on the Arduino board to IN1 of the motor control board - 5 to 1
PIN "GND" on the Arduino board to GND, the motor control board
PIN "5V" on the Arduino board to VCC, the motor control board
This is an example code that the motor turns by 2048 steps (corresponding to
a full revolution) above and can turn back.
Code
#include <stepper.h> int SPMU = 32;
stepper myStepper (SPMU, 2,3,4,5); void set up()
{
myStepper.setSpeed(500);
}
void loop() {MyStepper.step(2048); delay(500); myStepper.step(-2048);
delay(500);
}
Instructions for a Humidity Sensor
With a moisture sensor (Moisture sensor), you can, as the name suggests
measuring the moisture. However, this refers to the directly adjacent
moisture, such as skin moisture or soil moisture, but not from humidity. You
can use it, for example, to measure the moisture in the soil of plants. In the
case of dryness, then an alarm signal may be heard, or an electric water pump
could automatically the plant with water supply.
The sensor is also suitable to measure the water level in the sensor's range.
The operation is simple. a voltage is applied to the two contacts of the sensor.
The higher the moisture between the two contacts, the better the current to
flow to the other from a contact.
This value is processed electronically in the sensor and transmitted to an
analog signal on the molded card. Since the card, as described in previous
manuals, cannot measure voltage per se, it converts the voltage present on the
analog contact to a digital value. From 0 to 12 V corresponds to a digital
value of 0 to 1023 (the digits 1024, since zero, is considered first).
In the humidity sensor, however, the upper limit is about at the numerical
value of 800 when the sensor is completely immersed in the water. The exact
calibration is, however, dependent on the sensor and of the kind that is
measured of the liquid/moisture (e.g., saltwater has better conductivity, and
the value would be correspondingly higher).
The programming is very simple and very similar to the very reading of
potentiometers, as an analog value is read.
int reading = 0; // Under the variable "reading" is later, the measured
value of the
// sensor stored.
void set up()
{ // Here the setup starts.
Serial.begin(9600); // Communication with the serial port is started.
// This is required to display the value read in the serial monitor to
//to let.
}
void loop()
{ // This brace is the Loop section opened.
reading =analog read(A0); // The voltage on the sensor is read out
and
// under the variable "reading" saved.
Serial.print("Humidity Reading"); // Output on Serial Monitor: The
word
// "Humidity Reading"
Serial.println(Measured value);// and following the actual measured
value delay(500); // Finally, a little break, so not too many
// rushing numbers on the Serial Monitor.
}
Expansion of the Program:
Now, an alarm signal with the aid of piezo speakers to sound as soon as the
measured humidity falls below a certain limit.
As the limit of the value "200" is set in this case.
Code:
int reading = 0;
int Beep = 6; // The name "PIEPS" the Pin6 is now referred to which a
piezo speaker is connected.
void set up()
{
Serial.begin(9600);
pinMode (6,OUTPUT); // In the setup of the pin 6 is set as output
}
void loop()
{
reading =analog read(A0); Serial.print("Humidity Reading");
Serial.println(Measured value);
delay(500);
if (Reading <200) // Here the query begins: When the sensor value is
less
// is called "200,” then...
{
digitalWrite(PIEPS, HIGH); //... to beep the piezo speaker
}
else //…otherwise…
{
digitalWrite(PIEPS, LOW); //... he should be quiet.
}
}
Drop Sensor
A drop sensor or liquid sensor, as the name suggests, can detect a liquid. For
this purpose, the liquid must be located directly on the sensor. It is enough, a
small drop, to get a clear reading.
You can use the sensor, for example, as a rain sensor. Once a drop strikes the
sensor, the Arduino board can perform an action such as roll-up an awning,
blinds close, trigger an alarm, or actuate a wiper.
The operation is simple. Traverse the sensor at the long contact point is a
voltage (either + or -). As soon as a liquid, for example. Connects through a
tropical two contacts, a small current flows from one contact to another. This
value is processed electronically in the sensor and transmitted as an analog
signal to the analog input of the card in a form.
Since the card cannot measure the voltage per se as described in previous
instructions, it converts the voltage applied to the analog pin into a digital
value. From 0 to 12 volts corresponds to a digital value of 0 to 1023 (the
number 1024 because zero is considered the first value).
In the liquid sensor, the value in the dry is zero "0". When a drop of water
hits the contacts of the sensor, the Who at about "480" is located. The more
drops are on the sensor, the higher the value.
The first code it's all about, read the Sensorvalue with the Arduino board and
display with the "serial monitor."
The programming is very simple and very similar to the very reading of
potentiometers or the reading of the humidity sensor, as an analog value is
read.
int reading = 0; // Under the variable "reading" is later, the measured
value of the
// sensor stored.
void set up()
{ // Here the setup starts.
Serial.begin(9600); // Communication with the serial port is started.
// This is required to display the value read in the serial monitor to
//to let.
}
void loop()
{ // This brace is the Loop section opened.
reading =analog read(A0); // The voltage on the sensor is read out
and
// under the variable "reading" saved.
Serial.print("Humidity Reading"); // Output on Serial Monitor: The
word
// "Humidity Reading"
Serial.println(Measured value);// and following the actual measured
value delay(500); // Finally, a little break, so not too many
// rushing numbers on the Serial Monitor.
}
Expansion of the Program:
Now an alarm signal using piezo speakers to alert you when a raindrop hits
the sensor. As the limit, in this case, the measured value is determined 400, as
expected with a drop on the sensor, a measured value of about 480 for sale.
Code:
int reading = 0;
int Beep = 6; // The name "PIEPS" the Pin6 is now referred to which a
piezo speaker is connected.
void set up()
{
Serial.begin(9600);
pinMode (6,OUTPUT); // In the setup of the pin 6 is set as output
}
void loop()
{
reading =analog read(A0); Serial.print("Humidity Reading");
Serial.println(Measured value);
delay(500);
if (Reading > 400) // Here the query begins: When the sensor value is
less
// is called "400,” then...
{
digitalWrite(PIEPS, HIGH); //... to beep the piezo speaker
}
else //…otherwise…
{
digitalWrite(PIEPS, LOW); //... he should be quiet.
}
}
RFID Kit
The RFID ( "radio frequency identification") reader is used (also called
"RFID tags") of RFID transmitters read a particular code by radio. Each
transmitter has a unique case, only own individual code. Thus can be realized
with the Arduino locking systems or similar projects where a person to
identify with a transmitter.
RFID tags can have different forms, such as key fobs or cards in credit card
format.
How does it work? An RFID receiver contains a small copper coil that
generates a magnetic field. An RFID transmitter also includes a copper coil
that picks up the magnetic field and generates an electric voltage in the
transmitter. This voltage is then used to bring a small electronic chip to emit
an electrical code by radio. This code is then received directly from the
transmitter and processed so that the Arduino microcontroller may further
process the received code.
You can also describe RFID tags with a code. This is not taken into account
because of the complexity of this manual. Other guides are available online.
In this example, the 90° curved contact pins are soldered to the RFID receiver
so that the receiver can be placed vertically in a breadboard.
HEX number with this written succession does not work well. So we change
the line "Serial.print (mfrc522.uid.uidByte [i], HEX)," To
Then one gets as the result of the individual blocks of the UID code is output
as a decimal number; "Serial.print (mfrc522.uid.uidByte [i], DEC".
RFID Sketch 2
Now the UID code is being issued as a decimal number, but it is still divided
into four blocks. We change the code now with a little math to the effect that
we obtain a single contiguous normal number for the UID (decimal).
Why do we do that? If we want to use the sketch later to trigger a correctly
read RFID tags (e.g., an LED should light, or a servomotor is to be rotated 90
degrees...), we can better use an IF command with an associated number. For
example:
"If the RFID code = is 1031720, then an LED for 5 seconds to light up."
Harder would contrast with the command "If the first block is 195 and the
second block 765 reads and the third block 770 blocks 233 and the fourth is...
Then turn the LEDs for 5 seconds.
However, a disadvantage is that the sketch is thus somewhat uncertain
because all the numbers of the four blocks (max. 12 digits) can not be
represented in a continuous number. If there is to be more secure, you would
have every single block a query.
#include <SPI.h> #include <MFRC522.h> #define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522 (SS_PIN, RST_PIN);
void set up()
{
Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init ();
}
void loop()
{
if (. Mfrc522.PICC_IsNewCardPresent ())
{
return;
}
if (. Mfrc522.PICC_ReadCardSerial ())
{
return;
}
long code = 0; // As a new variable we add "code" under which the UID
later is output as a continuous number. Instead of int, we now use the
number range "long" because they can store a larger number.
for (byte i = 0; i <mfrc522.uid.size; i ++)
{
code = ((code + mfrc522.uid.uidByte [i]) * 10); // Now, as also
previously read out the four blocks, and in each pass of the code is
"stretched" by a factor of 10 degrees. (, here you would use the value in
1000, but the number would become too large.
}
Serial.println(code);
}
Great, now we can read a unique identification number of an RFID tag (it
displays The number on the Serial Monitor). In this case, the identification
number of that individual RFID tags 1031720 is.
And how does it continue? Now we want to turn on an LED for 5 seconds if
it holds the desired RFID tag in front of the RFID READER.
Sketch 3
#include <SPI.h> #include <MFRC522.h> #define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522 (SS_PIN, RST_PIN);
void set up()
{
Serial.begin(9600); SPI.begin(); mfrc522.PCD_Init ();
pinMode (2, OUTPUT); // The pin 2 is now an output (Connects a LED)
}
void loop()
{
if (. Mfrc522.PICC_IsNewCardPresent ())
{
return;
}
if (. Mfrc522.PICC_ReadCardSerial ())
{
return;
}
long code = 0;
for (byte i = 0; i <mfrc522.uid.size; i ++)
{
code = ((code + mfrc522.uid.uidByte [i]) * 10);
}
Serial.print("The card number is"); Serial.println(code);
// From here takes place the expansion of the program.
if (Code == 1031720) // If the number code is 1031720...
{ // Open Programmabschniss
digitalWrite (2, HIGH); should //...dann the LED on pin 2 light... delay
(5000); // for 5 seconds
digitalWrite (2, LOW); //... and then go out again
} // close the program section
} Completing // Sketch
Chapter 4
Keypad Shield
A Keypadshield has that one, the LCD display need not wire up in a
complicated way, and that six additional buttons has that you can use to
advantage. The special lies with the keys are that we can read them using an
analog pin in the program code. Because it connects the keys via different
resistances, all with an analog pin (A0). Pin A0 can, therefore, be restricted
only used for other things. The reason is on the Shield no slot for the A0 pin.
The Keypadshield is placed such a way so that the pins for the power right
into the pins of the power supply on the Arduino board fits (see in the image
below in the middle of the pins for the power supply. A clue can be the pin
that says "VIN" ). The upper slots of the Arduino boards also are covered by
the shield (Pin 0-13). Some may anyway not be used because the LCD
display uses. The unneeded pins were summarized in a series of slots (see
photo above).
If you want to use these slots, you should solder the cable sockets there. As
an example, we can use the following code:
Code:
// Sample using Liquid Crystal library #include <Liquid Crystal.h>
/ ************************************************* ******
This program will test the LCD panel and the buttons Mark Bramwell,
July 2010
************************************************** ****** /
// select the pins used on the LCD panel Liquid Crystal lcd (8, 9, 4, 5, 6,
7);
// define some values used by the panel and buttons int lcd_key = 0;
int adc_key_in = 0; #define btnRIGHT 0
#define btnUP 1
#define btnDOWN 2
#define btnLEFT 3
#define btnSELECT 4
#define btnNONE 5
// read the buttons int read_LCD_buttons ()
{
adc_key_in = analog read(0); // read the value from the sensor
// my buttons When read are centered at Valie thesis: 0, 144, 329, 504,
741
// we add approx 50 tons Those values and check to see if we are close
if (Adc_key_in> 1000) return btnNONE; // We make this the 1st option
for speed reasons since it will be the most likely result
if (Adc_key_in <50) return btnRIGHT; if (Adc_key_in <195) return
btnUP; if (Adc_key_in <380) return btnDOWN; if (Adc_key_in <555)
return btnLEFT;
if (Adc_key_in <790) return btnSELECT;
return btnNONE; // When all others fail, return this...
}
void set up()
{
lcd.begin(16, 2); // start the library lcd.setCursor(0,0);
lcd.print("Message"); // print a simple messagepinMode (2, OUTPUT);
}
void loop()
{
digitalWrite (2, HIGH);
lcd.setCursor(9,1); // move cursor to second line "1" and nine spaces
over LCD.print(millis() / 1000); // display seconds elapsed since power-
up
Program
To work with the I2C LCD module needs a library that is not pre-installed in
the Arduino program. This can be downloaded, for example,
https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library as a.ZIP
file. After that, the library must be added to the program in Arduino.
This can be done under the "Sketch" then "Include Library" and "add.ZIP
Library..". Now it can be accessed in the code to the library.
Sketch:
#include <Wire.h> // Wire Library Upload
#include <LiquidCrystal_I2C.h>// Previously added LiquidCrystal_I2C
// Library Upload
LiquidCrystal_I2C lcd (0x27, 16, 2); // This determines what kind
// a display it is. In this case, a 16-character 2
// lines.
void set up()
{
lcd.begin(); // In the setup, the LCD is started (unlike the simple LCD
module without 16.2 in brackets for the previously specified
}
void loop()
{
lcd.setCursor (0,0); // From here the I2C LCD module as the simple
LCD module can be programmed exactly.
lcd.print("XYZ GmbH");
lcd.setCursor (0.1); // lcd.setCursor to characters and line indicate
lcd.print("I wish you success.");//lcd.print something on the screen to
show
//to let.
}
Example of use:
With the I2C LCD module can as with the simple LCD module, it displays
also measured values.
Here is an example code in which a moisture sensor to pin A0 is connected:
#include <Wire.h>
#include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd (0x27, 16, 2);
int reading = 0;
void set up()
{
lcd.begin();
}
void loop()
{
reading =analog read(A0); // The value from analog input A0 to
// read, and the variable "reading" are stored.
lcd.setCursor(0,0); // The first line of the text is "reading"
//are displayed.
lcd.print("Reading");
lcd.setCursor(0.1); // In the second line to the measured value from
// moisture sensor has been determined to be displayed.
lcd.print(Measured value);
delay(500);
}
// I2C scanner
// Written by Nick Gammon
// Date: 20th April 2011 #include <Wire.h>
void setup () {
Serial.begin (115200); // Leonardo: wait for serial port to connect while
(.
// Serial)
{
}
Serial.println ();
Serial.println ( "I2C scanner scanning...."); byte count = 0;
Wire.begin ();
for (i byte = 8; i <120; i ++)
{
Wire.beginTransmission (i);
if (Wire.endTransmission () == 0)
{
Serial.print ( "Found address"); Serial.print (i, DEC); Serial.print ( "
(0x"); Serial.print (i, HEX); Serial.println ( ")");
count ++;
delay (1); // maybe unneeded?
} // end of good response
} // end of for loop Serial.println ( "Done."); Serial.print ( "Found");
Serial.print (count, DEC); Serial.println ( "device (s).");
}
void loop () {}
3. Open Serial Monitor in the Arduino software
4. Change baud rate to 115200
5. Possibly. Press the Reset button on the Arduino
In the serial monitor, the following should be shown (HEX address is
highlighted in red):
Arduino RTC
Time Module for Arduino: Real-Time Clock - RTC compatible with Arduino
Real Time Clock DS1307 I2C can display time and date in near real time.
Material: Microcontroller Board (In this example, UN R3). Navigation
wheel (or potentiometer), dashboard, LCD display, DS1307 I2C Real-Time
Clock, connection cable.
Cabling:
We wire the LCD display in principle as in the instruction no. 13. These then
must be added to the RTC, which is again connected to 5V and GND, the
SDA contact to the analog input A4, and the SCL contact to the analog input
A5.
Caution.: In the MEGA2560 R3, microcontrollers are available for the SDA
- separate entrances on the board at 20 and 21 and SCL contacts.
If everything is wired, you can also be able to start correctly with
programming, almost. Before must need for programming, download
libraries and added to the Arduino software.
If you have downloaded both libraries, you have to add them to the Arduino
software to the existing libraries. For this, open the Arduino software and
selects the Punk "sketch" the "Include Library" box. Then you can select
"Add.ZIP Library" and add the previously downloaded Time and
DS1307RTC Library.
We can now draw this in code.
Next, you have to the so-called "Set Time" Sketch Upload the time and date
from the device (computer, laptop, etc.), on which the microcontroller is
connected to add to the real-time clock.
This is done by then "DS1307RTC" select "File" to "examples" to select "Set
Time." This opens the appropriate Sketch which we now upload on the UN
R3.
If you have done all, you can get to the actual code.
Code:
#include <Time.h> Libraries invite #include <Wire.h>
#include <DS1307RTC.h> #include <Liquid Crystal.h>
Liquid Crystal LCD (12, 11, 5, 4, 3, 2); which pins is the microcontroller
boards used for the LCD // This line is set,
void set up()
{
lcd.begin(16, 2); // In the Setup specifies how many characters and lines
are applied.
Serial,begin(9600); // Opens the serial port and sets the baud rate (9600)
determined for the serial transmission. setSyncProvider (RTC.get); //
This is to get the function to the time and date of the RTC
}
void loop()
{
Serial,print(Hour ()); //Serial.print is the command show something in
the serial monitor (hour, minute, second, space, day, spaces, etc.)
print digits (minute ()); // in minutes and seconds, the command is
print digits (second ()); // print digits specified which will be determined
at the end of the code.
Serial,print(""); Serial,print(Day ()); Serial,print(""); Serial,print(Month
()); Serial,print( " "); Serial,print(Year ()); Serial,println();
delay(1000); //wait a second
lcd.setCursor(2, 0); // setCursor indicates where the text should begin. In
this case, the third character in the front row.lcd.print(Hour ()); // Here is
the time to be displayed now, so "hour" "" "minute,” etc..
lcd.print ( ":"); lcd.print (minute()); lcd.print(":"); lcd.print(Second ());
lcd.print("");
lcd.print("Clock"); // Here the word "clock" is after the time are
displayed to have to follow NOCH 3 spaces, otherwise in numbers <10
would always another "r" are displayed behind PM. This is because the
LCD Library command a view 0 before numbers <10 does not exist.
lcd.print("");
lcd.print("");
lcd.print("");
lcd.setCursor(1, 1); // The next "text" will now start at the second
character in the second row.
lcd.print(Day ()); // The date is now as
lcd.print("."); // "day,” ".,” "Month,” etc. are given. lcd.print(Month ());
lcd.print(".");
lcd.print(Year ());
}
void print digits (int digits) // This section fixed that automatically
becomes 0 before the digits for numbers <10 in the serial monitor. This
only applies to the serial monitor instead of the LCD display.
{
Serial,print(":"); if(Digits <10) Serial,print('0'); Serial,print(Digits);
}
Note: The DS1307 Real Time Clock is not accurate to the second. The reason
is that between uploading the Set Time Sketch and uploading the final sketch,
a certain period of about 15 seconds can not compensate for the RTC.
In addition, you can still display the week before the date.
For this purpose just before the date in lcd.print section of printDay ()
command; are added and are inserted after the loop following code:
void printDay () is // This sets a meaning for those already used in the
code before command printDay
{
int day;
day = weekday (); // The weekdays are to be displayed depending on the
date.
if(Day == 1) {lcd.print("So,")} // If this is Day 1 to display "Sun" and so
on.
if(Day == 2) {lcd.print("Mo,")}
if(Day == 3) {lcd.print("Di")}
if(Day == 4) {lcd.print("Mi")}
if(Day == 5) {lcd.print("Do,")}
if(Day == 6) {lcd.print("Fri")}
if(Day == 7) {lcd.print("Sa")}
}
Extension:
Two I²C Activate components simultaneously: the time and date with a Real
Time Clock with I²C bus, LCD display on a I²C.
To accommodate the two I²C components actuate the same time, one of the
components must be another I²C address than the other. In our case, we can
only change the address of the LCDs. Provided that the three soldering points
A0, A1, and A2 on the rear of the module has I²C.
The I²C address of the Real-Time Clock is set and can not be changed.
To change the address of LCDs, the solder joints need to be connected
differently (separated all three solder joints) at the beginning. Thus, the HEX
address changes of LCDs (s.
Table) (I = connected,: = not connected):
"simultaneously control two displays with I²C module" are checked with the
"Scanner" from the manual.
If the address of LCDs has been changed, we can now proceed to the wiring:
For programming as already mentioned above, the time and the DS1307RTC
Library needed. In addition, the NewliquidCrystal_1.3.4 Library is required
for the I²C LCD.
All libraries have the Arduino software is added:
Select Sketch> Include Library> Add ZIP library> previously downloaded
file Next, you have to the so-called "Set Time" Sketch Upload the time and
date from the device (computer, laptop, etc.) On which it connects the
microcontroller, on the set of real-time clock.
This is done by "File" to "examples" then "DS1307RTC" the point
"Set Time" selects. This opens the appropriate Sketch which we now upload
on the UN R3.
If you have done all you can get to the actual code.
#include <Time.h>
#include <Wire.h> #include <DS1307RTC.h>
#include <LiquidCrystal_I2C.h> // Load Libraries
LiquidCrystal_I2C lcd (0x3D, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // The
I²C Display rename and the HEX address // Insert (for us 0x3D)
void set up() {
lcd.begin(16, 2); // Start the display, specify that it is a display with 16
characters in 2 lines are //
lcd.backlight(); Switch // lighting of the display Serial,begin(9600); //
start serial connection with baud rate 9600 setSyncProvider(RTC.get); //
Retrieve data from the RTC
}
void loop() {
Serial.print(hour()); //Serial.print is the little display in the serial monitor
(hour, minute, second //, space, day, spaces, etc.) Command print digits
(minute()); // in minutes and seconds, the command is print digits
(second()); // print digits used, which is still set at the end of the code
Serial.print(""); Serial.print(day()); Serial.print ("");
Serial.print(month()); Serial.print(""); Serial.print (year ());
Serial,println();
delay(1000); // wait one second
lcd.setCursor(2, 0); // setCursor indicates where the text should begin. In
this case, the third character in // the front row.
lcd.print(hour()); // The time is to be displayed in the format:
lcd.print(":"); //Hours minutes seconds
lcd.print (minute()); lcd.print(":"); lcd.print(second()); lcd.print("");
lcd.print("Clock"); // Behind, the word "clock" display lcd.print("");
lcd.print("");
lcd.print("");
lcd.setCursor(1, 1); // The second line will display the date // be
lcd.print(day());
lcd.print(".");
lcd.print(month());
lcd.print(".");
lcd.print(year());
}
void print digits (int digits) { // The print command digits for the serial
monitor Serial,print(":");
if(Digits <10) Serial,print('0'); Serial.print(Digits);
}
Keypad
A keypad on the Arduino.
Task: With the Arduino, a keypad (keyboard) to read out, and the pressed
key are displayed on the Serial Monitor.
These instructions a 3 x 4 keypad used. Alternatively, a4 x 4 keypad is used
here pins, and defined keys (COLS / HEXAKeys) need to be added (see
below).
Material: Arduino / cable (7x) / keyboard / power supply
To use the keypad, you need the keypad Library. The Library of the Arduino
IDE to add:
Open the Arduino IDE
Menu item: - embed> Library - Sketch> Library Management
Search -with the search line to "Keypad,” find and install (the version of
Mark Stanly)
The keypad comprises a 3 x 4 array of 12 keys.
To understand the functioning of the keypad you have to imagine how a
coordinate system. Each key is associated with two pins; a pin for the
columns (COLS) and one for the rows (ROWS). If a key is pressed, the
corresponding pins are connected. These pins can read the Arduino with the
digital read () function. (The keyboard requires no external power supply.)
The Sketch:
#include <keypad.h>
// Here, we define the size of the keypad const byte COLS = 3; // 3
columns
const byte ROWS = 4; // 4 lines
// The digits / characters:
char HEXAKeys [ROWS] [COLS] = {
{.# '..0 '..* '},
{.9 '..8th'..7 '},
{.6 '..5 '..4 '},
{.3 '..2 '..1'}
};
byte colPins [COLS] = {8, 7, 6}; // definition of the pins for the 3
columns byte rowPins [ROWS] = {5, 4, 3, 2};// definition of the pins for
the 4 lines char pressedKey; // pressedKey corresponds in the future, the
keys pressed keypad myKeypad = keypad(makeKeymap(HEXAKeys)
rowPins, colPins, ROWS,
COLS); // The keypad can be addressed from now on // with myKeypad
void set up() {
Serial.begin(9600);
}
void loop() {
pressedKey = myKeypad.getKey(); // pressedKey corresponds to the
pressed key if (PressedKey) { // If a key is pressed
Serial,print("The key "); Serial,print(PressedKey); Serial,print(" was
pressed");
Serial,println(); // Tell us the Serial Monitor the pressed key with
}}
Using a 4 x 4 keypad (the sections are changed):
> const byte COLS = 4; // 4 columns
> byte colPins [COLS] = {9, 8, 7, 6}; // definition of the pins for the 4
columns
> char HEXAKeys [ROWS] [COLS] = {
{, D '. , #.. , 0.. *.},
{, C '..9 '..8th'. , 7 '},
{, B '. , 6.. , 5...4 '},
{, A '..3 '. 2...1'}
};
Keypad - Castle
With the number keypad code lock programming Task: With the entry of a
code 3 digit on the keypad to an LED light up and a servo occupy a certain
position. The servo example could be a bolt are attached that unlocks a door.
Material: Arduino / Breadboard / keypad (in this example, 4 × 4) / cable / a
red LED / green LED / two 100 Ohm resistors / Servo
We want to leave a green LED light up, typing a 3-digit password on the
keypad and can occupy a certain position a servo. If the "lock" is closed to
light up and the servo taking another position, a red LED. This tutorial serves
as inspiration and an example of how a "safe" can be built from these simple
components, for example.
We now come to the construction. This is quite simple and goes from the
following Fritzing sketch out.
For Better Orientation in Wiring the Keypad:
At the extreme contacts of the keypad to enter the numbers, you can see one
and seventh it connects The contact 1 at the keypad to pin 2 on the Arduino.
Ascending, it then proceeds to contact 7 which is connected to the pin 8 at the
Arduino, the keypad.
For the code, we need the keypad library, what the Arduino software has to
be added.
Open Arduino Software> "Sketch"> Select "Include Library"> choose
"Manage Libraries.." select> In the search bar of the new window "Keypad">
enter the top library Select by Mark Stanley and install.
From now on, we can use the keypad Library in the code.
Code:
#include <keypad.h> // keypad and servo Library is integrated #include
<Power.h>
Power servo-blue; // servo is now addressed with "servo blue"
char* Password = "123"; // The password is set. In this example
// "123"
int position = 0;
const byte ROWS = 4; // This indicates how many rows and columns the
const byte COLS = 3; // keypad has
char keys [ROWS] [COLS] = { be // The numbers and characters on the
keypad
{# ". '0'. * '}, // specified
{9 '. ,8th'. , 7 '},
{6 '. , 5 '. , 4 '},
{, 3 '. , 2 '. ,1'}
};
byte rowPins [ROWS] = {5, 6, 7, 8}; // The connection with the Arduino
is
byte colPins [COLS] = {2, 3, 4}; // set
keypad = keypad( makeKeymap(Keys), rowPins, colPins, ROWS,
COLS); int RedLED = 12; // The red LED is connected to pin 12
int GreenLED = 13; // The green LED is connected to pin 13 void set
up()
{
pinMode(RedLED, OUTPUT); // The LEDs are set as output
pinMode(GreenLED, OUTPUT);
servo blue.attach(11); // The servo is connected to pin 11
setLocked (true);
}
void loop()
{
char key = keypad.getKey();
if (Key == * ' || key ==# ") // when the lock is unlocked it can with the
// key or "#" are blocked again "*"
{
position = 0;
setLocked (true); Lock // castle once was * or press #
}
if (Key == password [position])
{
position ++;
}
if (position == 3) // This line length indicates the password. In our
// Case 3 points.
{
setLocked (false);
}
delay(100);
}
void setLocked (int locked)
{
if (Locked) // If the lock is locked to..
{
digitalWrite(RedLED, HIGH); //..die red LED lights..
digitalWrite(GreenLED, LOW); //..die green LED does not light.. servo
blue.write(90); // and the servo is to control 0 degrees.
}
else // when the lock is unlocked to..
{
digitalWrite(RedLED, LOW); //..die red LED does not light..
digitalWrite(GreenLED, HIGH); //..die green LED lights.. servo
blue.write(0); //..und the servo drive 90 degrees.
}
}
This guide serves as an example and foundation of how a simple "castle"
using fewer components and can construct the Arduino.
Color Sensor
Task: Using a color sensor, the colors are red, green, and blue are detected,
and a corresponding LED light up.
Material: Arduino / cable / color sensor / Red LED / Green LED / Blue LED /
resistors for LEDs are to obtain more accurate values 4 white LEDs on the
color sensor. In the center of the LEDs is a small square of photodiodes,
which may filter the intensity of a color. There are photodiodes for the green,
red and blue color, and photodiodes without color filters present. This "filter"
out what color is held before the color sensor and convert them to values
around that can handle the microcontroller.
We can use the color sensor, for example, in the construction of a sorting
machine.
For our test setup, we made the following structure with appropriate wiring
Cabling:
Color sensor >>> Arduino VCC 5V >>>
GND GND >>>
S0 >>> 8th
S1 >>> 9
S2 >>> 12
S3 >>> 11
OUT >>> 10
OE >>> GND
LEDs >>> Arduino Red LED >>> 2
green LED >>> 3 Blueness LED >>> 4
This is a sample code with the three colors of red, green and blue are read by
Arduino. At the same time indicate three correspondingly colored LEDs
which color has been recognized by the sensor.
const int s0 = 8; // Set the connection of the color sensor contacts with
the Arduino const int s1 = 9;
const int s2 = 12; const int s3 = 11; const int out = 10;
int RedLED = 2; // Set the connection of the LEDs with Arduino int
GreenLED = 3;
int BlueLED = 4;
int red = 0; call // variables for LEDs int green = 0;
int blue = 0; void set up()
{
Serial.begin(9600); // Start Serial Communications
pinMode(S0, OUTPUT); // The contacts of the color sensor are used as
output or pinMode(S1, OUTPUT); // Input festgelgt
pinMode(S2, OUTPUT); pinMode(S3, OUTPUT); pinMode(out,
INPUT);
pinMode(RedLED, OUTPUT); // The LEDs are defined as output
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
digitalWrite(S0, HIGH); // The four white LEDs at the color sensor will
light up digitalWrite(S1, HIGH);
}
void loop()
color ();// This function is determined at the end of the code (s. "Void
color ();") Serial.print("Value Red"); // On the serial monitor is to
"value" each Serial.print(red, DEC); // with the appropriate color display
Serial.print("Value Green");// be behind it and the value obtained in the
Serial.print(green, DEC); // void color (); Function was read out.
Serial.print("Value Blue"); Serial.print(blue, DEC);
// Here are the commands for the LEDs
if (Red <blue && red <green && red <20) // If the filter value for red
// is smaller than all other values..
{
Serial.println(" - (Red color)"); are displayed on the serial monitor //
//..should "red color" and..
digitalWrite(RedLED, HIGH); //... ie red LED lights up, the others
digitalWrite(GreenLED, LOW); // stay out
digitalWrite(BlueLED, LOW);
}
else if (blue <red && blue <green) // The same in blue and green
{
Serial.println (" - (Blue colour)"); digitalWrite(RedLED, LOW);
digitalWrite(GreenLED, LOW); digitalWrite(BlueLED, HIGH);
}
else if (Green <red && green <blue)
{
Serial.println(" - (Green colour)"); digitalWrite(RedLED, LOW);
digitalWrite(GreenLED, HIGH); digitalWrite(BlueLED, LOW);
}
else{ // If there are no values..
Serial.println(); Show //..nichts on the serial monitor and..
}
delay(300);
digitalWrite(RedLED, LOW); //... turn off all LEDs
digitalWrite(GreenLED, LOW); digitalWrite(BlueLED, LOW);
}
void color () // This is where the values are read by the color sensor and
under the
// corresponding variables stored
{
digitalWrite(S2, LOW); digitalWrite(S3, LOW);
red = pulseIn(out, digital read(Out) == HIGH ? LOW : HIGH);
digitalWrite(S3, HIGH);
blue = pulseIn(out, digital read(Out) == HIGH ? LOW : HIGH);
digitalWrite(S2, HIGH);
green = pulseIn(out, digital read(Out) == HIGH ? LOW : HIGH);
}
To check our building, we have printed us a table with a red, green and blue
surface.
Depending on what color you hold the color sensor, the corresponding LED
should now light up.
Generate Tones
Produce with the Arduino and a speaker sounds.
With the Arduino can produce sounds in different ways. The simplest way is
the tone generation with an active loudspeaker (active buzzer), which is
connected to only the voltage of 5V. The sounds produced by a built inside
electronics. The disadvantage is that a
"Active buzzer" can only produce a single tone - tunes or siren sounds are not
possible.
With a passive Loudspeaker (passive buzzer), you have the option using the
Arduino microcontroller different sounds, tunes, or siren signals to generate,
since buzzer in passive no electronics is present, sets a tone.
Task: Passive speakers are different tones and a melody to be generated.
Material: Arduino microcontroller / A passive speaker (passive buzzer) /
Breadboard / cable
The generation of sound is largely based on the command "tone (x, y),”
where the x value indicative of the pin on which it connects the speaker to the
positive side and the Y value that indicates the pitch.
An example:
tone (8, 100); // The speakers on pin 8 is activated with the pitch "100."
delay (1000); // break with 1000 milliseconds, or 1 second - The speaker
remains active for this time.
noTone (8); // The speakers on pin 8 is disabled
Code 1: Simple Tone
void set up() // The Setup information is not required.
// The voltage output for the piezo speaker no command "tone" is
automatically set in the sketch by the Arduino,
{
}
void loop()
{
tone(8, 100); // The main part will be given the command "tone (x, y)" a
sound.
delay(1000); // with a duration of 1 second noTone(8th); // The sound is
turned off
delay(1000); // The speaker one second remains off
}
Code 2: Alternating Pitches
In the second example, only a few lines are complemented in the main
part (loop). Characterized sounding two tones alternately with the pitch
"100" or "200,” as in a siren. A break between the tones does not exist.
void set up()
{
}
void loop()
{
tone(8, 100); delay(1000);
noTone(8th); // At this point, the first sound goes out.
tone(8, 200); sounds // The second tone with the new pitch "200".
delay(1000); //... and that for a second...
noTone(8th); // At this point, the second sound goes off, and the loop
part of the sketch begins again.
}
Code 3: Tone Generate by Keystroke
In the third example, a button on pin 6 is added to the construction. In the
main part of the button is read by an "IF query." If the button is pressed, you
will hear a tone for one second with the pitch "300".
int Taster1 = 6;
int Button status = 0; void set up()
{
pinMode(Taster1, INPUT);
}
void loop()
{
Probe status = digital read(Button); if (Button == Status HIGH)
{
tone(8, 300); noTone(8th);
}}
Code 4: Sounds Depending on Different Keys
In the fourth example, different keys should be decided depending on the
actuation of which sound is emitted from the speaker. For this purpose, it
connects a probe connected to pins 6 and 7 in each case. The main part is
decided by two "IF statements," in which sound is emitted.
Code:
int Taster1 = 6; // Taster1 connected to pin 6 int Button2 = 7; // button2
connected to Pin7
int Tasterstatus1 = 0; save // variable to indicate the status of the probe.
1 int Tasterstatus2 = 0; save // variable to indicate the status of the
probe. 2
void set up()
{
pinMode(Taster1, INPUT); // Set Taster1 as input pinMode(Button2,
INPUT); // Set button2 as input
}
void loop()
{
Tasterstatus1 = digital read(Taster1);// Status of Taster1 read (HIGH or
LOW)
Tasterstatus2 = digital read(Button2); // Status of button2 read (HIGH or
LOW)
if (Tasterstatus1 == HIGH) // If the Taster1 is pressed, then...
{
tone(8, 100); // outputting a sound with the pitch 100th delay (1000); //
with the duration of one second noTone(8th); // off the sound.
}
if (Tasterstatus2 == HIGH)
{
tone(8, 200);
delay (1000); // with the duration of one second noTone(8th); // off the
sound.
}
}
Create Melodies
In the Arduino software is a file containing specially designed to generate
sounds using a speaker (passive buzzer). Instead of the pitch in the form of
numbers such as. "Tone (8, 200),” and sounds from the Sounds can now be
selected.
As an example, there is for it in the Arduino software to sketch
"toneMelody."
To see "examples" -> "02.Digital" -> "toneMelody"
In the example, the file is already stored, the association is in the pitch and
numerical value. She has the name "pitches.h." The content you can see if
you click in the opened sample program on the second tab in the sketch.
To have access to the file must be in the sketch only the command #include
"Pitches.h" be installed and must be opened as a tab file. This is best done by
opening the sketch "toneMelody" from the examples in the Arduino software
and then edited. Thus, the "pitches.h" file is automatically invoked as a tab.
This is clear in the following example.
This is a very small sketch of the alternating plays, two tones from the file
"pitches.h".
#include "Pitches.h" void set up()
{
pinMode (8th,OUTPUT); // speaker Pin8
}
void loop()
{
tone(8, NOTE_C4, 1000); // At Pin8 played the note C4 for 1000ms
delay(3000); // After the note sounds, the Sketch for 3 seconds pause.
This means that after it plays the sound to the end, the remaining two-
second pause with no sound.
tone(8, NOTE_G3, 1000); // At Pin8 played the note G3 for 1000ms
delay(3000); // After the note sounds, the Sketch for 3 seconds pause.
This means that after it plays the sound to the end, the remaining two-
second pause with no sound.
}
In this sketch, the "Tone" command is no longer needed to end the sound
through the extension.
Command:
"tone (x, y, z)" x = Pin of the speaker, y = pitch = z duration of tone in
milliseconds.
The Sketch:
int LED = 6; // The word "LED" is now available for the value. 6
int TILT = 7; // The word "TILT" is now available for the value 7 - The
inclinometer is thus connected to Pin7
int TILT = 0; // The word "TILT" is now first for the value 0. Later will
be saved under this variable, whether a slope of more than 45 degrees or
not.
void set up() // Here the setup starts.
{
pinMode(LED, OUTPUT); // The pin with the LED (pin 6) is now an
output. pinMode(TILT, INPUT); // The pin with the tilt sensor (pin 7) is
now an entrance.
}
void loop()
{ // This brace is the Loop section opened.
TILT =digital read(TILT); // Here the Pin7, so the inclination sensor is
read (: digital read command) is. It stores the result under the variable
"TILT" with the value "HIGH" for 5V or "LOW" for 0Volt. When the
sensor is even, the current can flow between the two contacts of the
sensor. It is then up to Pin7 to a voltage. The status would be so
"HIGH." When the sensor 45 or more degrees is inclined, no current can
flow, and the status would be "LOW."
if (TILT == HIGH) // processing: If the sensor is inclined less than 45
degrees
{ Open // Program section of the IF command. digitalWrite(LED,
LOW); // then the LED will not light
} // close the program section of the IF command. else //...otherwise...
{ Open // Program section of the else command. digitalWrite(LED,
HIGH); //...should the LED lights.
} // close the program section of the else command.
} // This last clip of the loop portion is closed.
Code:
int LM35 = A0; // The sensor A0 is to be connected to the analog pin.
We call the pin from now "LM35."
int temperature = 0;// Under the variable "temperature" the temperature
value is saved later.
int temp [10]; // This yields good values, one first read several values
and then averages the results. The square bracket "[10]" produced here
equal to ten variables named
"Temp [0],” "temp [2],” "temp [3],” … to … "Temp [9]." With the
notation [10], So it saves only a little Place.
int time = 20; // The value for "time" specifies the time intervals between
the individual measurements in the code.
void set up()
{
Serial.begin(9600); // In the setup we start serial communication
}
void loop()
{
// more detailed explanation under the code * 1
temp [0] = map(analog read(LM35),
delay(Time); 0 410 -50, 150);
temp [1] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [2] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [3] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [4] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [5] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [6] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [7] = map(analog read(LM35), 0 410 -50, 150);
delay(Time);
temp [8] = map(analog read(LM35), 0, 410, -50, 150); delay(Time);
temp [9] = map(analog read(LM35), 0, 410, -50, 150);
temperature = (temp [0] + temp [1] + temp [2] + temp [3] + temp [4] +
temp [5] + temp [6] + temp [7] + temp temp [8] + [ 9]) / 10;
Serial.print(temperature); Serial.println(" Centigrade");
}
Detailed Explanation for Loop * 1:
Here the temperature is ten times read in between is ever a break with the
duration
"Time" in milliseconds. But what happens here, exactly? Let's look at
the command once more closely.
temp [1] = map (analog read (LM35), 0, 307, 0, 150); Sequentially:
temp [1] - is the name of the first variable.
"Map (a, b, c, d, e)" - This is the so-called "Map" command. This may
be a read-in value (a) in which the values between (b) and (c) are,
convert them into a different speed range, in the range between (d) and
(e).
In our command, the following happens:
The value of the sensor is directly read out in the "Map" command with
"analog read (LM35)". The measured values should be between 0 and 307th.
This corresponds to the analog port of the values between 0 V and 1.5V. The
voltage is the sensor at temperatures between 0 ° C and
+ 150 ° C from. These values on the analog port will now be through the
"Map command" directly into the
° C values between 0 and 150 are converted.
Then every ten ascertained temperature values are added together and divided
by ten. The average value is stored under the variable "temperature."
Finally, the value of "temperature" on the serial communication to the PC is
sent. Now the serial monitor you have to open the Arduino software to read
the temperature on the sensor.
Code:
int LM35 = A0;
int temperature = 0; int temp [10];
int time = 20;
int piezo = 5; // The word "piezo" is now the number five, so five of the
piezo is connected to the port.
void set up()
{
Serial.begin(9600);
pinMode (Piezo, OUTPUT); // The piezo speaker to pin 5 should be
(logic one output, because the yes from the microcontroller board yes a
voltage needed to beep.
}
void loop() {
temp [0] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [1] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [2] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [3] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [4] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [5] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [6] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [7] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [8] = map(analog read(LM35), 0 307 0 150);
delay(Time);
temp [9] = map(analog read(LM35), 0 307 0 150);
temperature = (temp [0] + temp [1] + temp [2] + temp [3] + temp [4] +
temp [5]
+ Temp [6] + temp [7] + temp [8] + temp [9]) / 10; // All in a
row.Serial.print(temperature);
Serial.println(" Centigrade");
if (Temperature> = 30) // Creates a IF condition: If the value for the
temperature above or equal to 30, then...
{
digitalWrite(Piezo,HIGH); //... start beeping.
}
else // And if that is not so...
{
digitalWrite(Piezo,LOW); //... then be quiet.
}
}
Cabling:
This is simply because the sensor has only three contacts, which must be
connected to the Arduino.
Voltage sensor >>> >>> Arduino S A1
+ 5V >>>
– >>> GND
On the other side, there are labeled GND and VCC contacts to which is
connected to the voltage to be measured.
Explanation of Contacts:
Programming
A 7-segment display to program without endless code, you need a library that
is not installed in the Arduino software. This "SevenSeg" Library of Dean
Reading can be downloaded here: https://github.com/DeanIsMe/SevSeg, and
The library must then be known as already from the previous instructions,
added to Arduino software.
This goes on easiest in the Arduino software at Sketch> Include Library>
Add.ZIP Library.
Code:
#include "SevSeg.h" // Load The previously added Library SevSeg
sevseg; // initialize a seven segment object
void set up() {
byte numDigits = 4; // Here the number of digits is specified
byte digitPins [] = {2, 3, 4, 5}; // The pins on points are set
byte segmentPins [] = {6, 7, 8, 9, 10, 11, 12, 13}; // The pins on the
// segments are defined
sevseg.begin(COMMON_CATHODE, NumDigits, digitPins,
segmentPins); //In this
// section you can either test what kind of display you own or
// you can specify it. Try both as the display works only when the correct
//type is entered - COMMON_CATHODE or
// COMMON_ANODE display. The wrong type will make all digits,
and //segments light up simultaneously.
}
void loop() {
sevseg.SetNumber(1234.3); // Here we can now enter the desired
number.
// 1234 is the example we used. The number after the comma represents
// the lit-up dot, i.e., 3 indicates the dot beside the first digit and 0
//indicates the dot beside digit 4. If you do not want a dot showing,
// input 4.
sevseg.refresh display(); // This is where the numbers are started on the
displays
sevseg.SETBRIGHTNESS(90); // Here the brightness of the display can
be
//added in a range of 0-100 where 100 is the brightest.
//0 doesn’t indicate a completely dark display. Only using
// ,,sevseg.refreshDisplay ();controls what is on the display
}
In the sevseg library, there are some interesting sample codes available.
These can be in File> Samples> SevSeg-master.
Conclusion
Well, here in the closing of this book, we want to detail the reasons why we
think Arduino should be in your life, both professional and private.
Arduino boards are interesting, especially for students and teachers because
of their low cost. For less than 100 dollars you can buy the official Arduino
Starter Kit that comes with all the necessary components to get started in this
world, and if it seems expensive, there are always Arduino starter kits
composed of fully functional Arduino board clones (advantages of free
hardware on which Arduino is based), and for less than 50 dollars you can get
more than enough to start. Even if you're not a student and you're only
interested in finding a hobby to spend time with, Arduino is going to be
cheaper than photography, painting, or gardening.
With Arduino, you can work on almost all computer platforms, from Mac OS
X to Linux through Windows. Thanks to the fact that it is open-source,
multiple tools have appeared that make it easy to use, for example, Scratch or
its equivalent for Arduino Scratch for Arduino. Apart from the software, it is
also flexible when using different accessories available in different kits, so
you have the freedom to choose the components to use in your project. There
is also flexibility regarding the Arduino itself since depending on the project
you have in mind there is an Arduino for each project, from the smallest to
make wearables such as the Arduino Gemma to other more powerful ones
such as the Arduino Mega or the Arduino Yun in which you can install a
network server.
The limit is your imagination. If you have been reading about Arduino for a
while, you will have realized that many projects can be done with Arduino,
from the simple ones that come in the starter kits to 3D printers or robots
such as those from Star Wars, R2D2 or new BB8.
Or how about making a surveillance system for your home or building your
own drone. All these things you can do with Arduino. Now is the time to get
started!
References
https://stackoverflow.com/questions/15113128/ir-hex-comparison
https://www.copyscape.com/prosearch.php
https://arduino.stackexchange.com/questions/18503/ script-stops-functioning-
after-calling-irsend-function-in-irlibrary
http://archive.fabacademy.org/fabacademy2017/fablabbottrophrw/students/64/
week13.html
https://forum.sparkfun.com/viewtopic.php?t=46505
https://github.com/miguelbalboa/rfid/issues/496
https://community.particle.io/t/rfid-code-explanation-needed/53961
https://forum.arduino.cc/index.php?topic=424620.0
https://community.platformio.org/t/wire-h-is-missing-and-cause-a-simple-
program-to-not-compile/550
https://forum.arduino.cc/index.php?topic=424620.0
https://media.digikey.com/pdf/Data%20Sheets/DFRobot%20PDFs/DFR0009_Web.pdf
https://community.platformio.org/t/wire-h-is-missing-and-cause-a-simple-
program-to-not-compile/550
https://www.geeetech.com/wiki/index.php/Arduino_1602_LCD_KeyPad_Shield
https://protosupplies.com/determining-unknown-i2c-addresses/
https://forum.arduino.cc/index.php?topic=315058.15
https://www.instesre.org/ArduinoWeatherStationCode.txt
http://arduino-tutorials.eu/real-time-clock-tutorial
http://arduino-tutorials.eu/arduino-keypad-lock-tutorial
https://www.instructables.com/id/EAL-MM-Sorting-Machine/
http://tinkbox.ph/sites/mytinkbox.com/files/downloads/
TCS230_COLOR_SENSOR.pdf
https://github.com/Nikaoto/Shamen/blob/master/lib/deep.lua
http://arduino-tutorials.eu/arduino-four-digit-seven-segment-display
ARDUINO
PROGRAMMING
STUART NICHOLAS
Introduction
Arduino Hardware
The piece of hardware that the user will end up interacting with is the
‘Arduino board.’ The software that we created using the Arduino IDE
directly interacts with this board, executing any instructions embedded within
the program. Generally, people do not use just the Arduino board itself; on
the contrary, there are extra components available that pop onto the Arduino
board extending its usability. For instance, we can attach things like switches,
thermal-sensors, gyroscopes, pressure sensors, LEDs, output displays, and
even motors to the Arduino board, all depending on what the project requires.
When using the Arduino environment for a project, users can choose from a
variety of Arduino hardware boards according to the needs of the project and
the Arduino software. There are a variety of Arduino boards available in the
community for users to pick up. There are official Arduino boards released
by the Arduino team, as well as Arduino boards that are released by the
members of the community. Suppose you are picking up a project from the
community and modifying it according to your needs. In that case, it's
recommended to use the tools as specified by the original project designer or
swap a few things in and out as you see fit. Arduino boards come in a variety
of form-factors. You can find boards that are as small as credit cards and
boards that are just large enough to design a project that features applications
such as wearables. However, one thing to note is that different sized boards
do not have the same specifications. Generally, smaller Arduino boards have
fewer connection points for external peripherals and an underwhelming
processor. In contrast, bigger boards feature a more robust processor and an
increased number of connections (since the size is bigger, it can easily
accommodate more ports). A quick run-through of the popular Arduino
boards has been given below;
Arduino Nano
Arduino Bare Bones
Boarduino
Seeduino
Arduino Teensy and Arduino Teensy plus
So far, we’ve studied what an Arduino micro-controller is, and how the
native coding environment that is provided alongside works. Let’s now step
up into learning about how actually to use all of this. This chapter will serve
to create a basis for understanding and writing Arduino code, that we can
interface into micro-controllers and create wonderful things as we so desire.
Curly Bracket
The pair of curly brackets are used to tell the IDE where a block of code will
start and where it will end; the left ( { ) for the former and the right ( } ) for
the latter. You might have seen examples of this in prior sections, though we
would like to mention these are used to make code blocks other than those of
functions as well; this will be elaborated on further into this chapter.
Do note that full pairs of brackets must exist (an equal number of left and
right brackets means that they’re “balanced”); otherwise, errors such as crypt
compiler errors will occur, in which case counting these pairs is a good idea.
Semicolons
A semicolon is used to close off and end a statement of code (i.e., put at the
end, like a period for normal sentences) to distinguish it from other lines. Not
doing so will result in a fairly easy-to-debug error during compilation, as the
IDE will mention where this has occurred.
Another use for semicolons is separating elements in for loops, which will
also be discussed later.
Comments
Comments are bits of written text tagged with a syntax (in our case, a mix of
forwarding slashes and asterisks) so that the compiler doesn’t read them and
add them to the functionality of the program, allowing us to write whatever
we want as comments to the actual code. There are two kinds of comments
that the IDE has: Block comments and Line comments. Block comments are
usually big blocks of text that describe the code around it, whereas line
comments usually serve as a heading or a nametag for the code near it, telling
the reader what it does.
A block comment uses ‘ /* ’ and ‘ */ ‘ to define where it starts and ends,
respectively:
Using comments to describe your work is a very good habit for readers to be
able to discern what you want to do.
Variables
Variables are the meat and potatoes of coding. These are objects that store
information for further application by the functionality of the code. Every
variable has a unique name used to identify it and thus the information it
stores. A good habit for naming variables is using Camel Case (i.e., writing
the first word in lowercase, and then the first letter of the second word in
uppercase, like a camel’s humps, e.g., oldGreyDog, warmApplePie)
Another good habit is to initialize the variable by assigning it a value, which
helps in errors where the variable is called without a value. To do so, we tell
it what data type it will be, give it a name, use an equal sign, and then give it
an initial value (usually zero).
int myInt =
0;
Datatype
What is ‘int’? It is a datatype, a kind of badge that says what set of values
the variable can hold. Let’s examine some more built-in datatypes commonly
used in coding with the Arduino language.
Boolean
This datatype is used for basic logical decisions at least as old as
Shakespeare: true or false. This datatype‘s size is one bit. These are the only
values this set has.
boolean myBool =
true;
This code declares the variable myBool as being a boolean, with an initial
value ‘true.’ As you might expect, this datatype is extremely common in
Arduino, and all comparison operations produce (or ‘return’) a Boolean
value.
Byte
A byte is eight bits, i.e., it is eight binary digits long, capable of referring to
integer values from zero or 255. The keyword for this datatype is ‘byte.’
byte myByte =
128;
Integer
By far the most used data type, we use this to store integer values; the total
number of unique values allowed is 2^16 or two bytes (sixteen binary digits
long): from –32768 to 32767. We can also have it be unsigned, via adding the
keyword ‘unsigned,’ to have this range go from 0 to 65,535. The keyword for
this datatype is ‘int.’
Long
Similar to the previous datatypes, the long datatype can store four bytes
(thirty-two binary digits) worth of integer numbers, from –2,147,483,648 to
2,147,483,647. ‘unsigned’ can be used as well for the same effect, going from
0 to 4,294,967,295. The keyword for this datatype is ‘long.’
long myLong =
123,456,789;
Do note that this consumes more memory (double that of integer), so take
care to not use it unless it is necessary to store numbers that large.
double myDouble =
1.25;
float myFloat = 1.5;
Character
Characters are generally referred to as the glyphs of alphabets and various
other symbols, i.e., characters. However, on the back end, these characters are
a numerical value that refers to the ASCII chart; we can store a character as
either of these. The keyword for this datatype is ‘char’
char myChar =
'A';
char myChar =
65;
Both lines of the above code declare a character ‘myChar’ storing capital A.
We can store a group of these characters using a method that will be
discussed later, which will let us store words and sentences.
Arrays
An array is a storage structure that assigns an index value to some data and
allows us to store multiple data entries into one structure, with the caveat that
it must be of one datatype that is declared alongside the array during
initialization. A few ways to define arrays are as follows:
int myInts[10];
int myInts[] = {1, 2, 3, 4};
int myInts[8] = {2, 4, 6, 8,
10};
Notice that the name has a pair of square brackets, which is how we tell the
environment that we’re creating an array.
The first line defines an uninitialized array that can store ten
values in a row but doesn’t store any at the moment. Be careful
of declaring uninitialized arrays, as its interactions with memory
spaces can be quite weird.
The second line initializes an array with an undefined size but
with a defined number of values. In this case, the array matches
the size of the row of values that we defined.
The third line initializes an array with both a defined size and
values. In this case, the defined values are assigned to the first
spaces in the array, but the last three are not. Care must be taken
in this case for the same reason as the first declaration, which
will be demonstrated shortly.
The above code notes that for most programming languages, we count
indexes starting from zero. The following should serve as further
clarification:
Now let’s look at what happens when arrays aren’t initialized. Run the
following in the Arduino IDE, and you’ll notice that the Serial Monitor
displays a jumbled mess that is definitely not integers since they were never
initialized.
int myInts[5];
Serial.println(myInts[0]);
Serial.println(myInts[1]);
Serial.println(myInts[2]);
Serial.println(myInts[3]);
Serial.println(myInts[4]);
Fortunately, providing values to uninitialized indexed array space is the same
as providing a value to any variable, as follows:
int myInts[2];
myInts[0] =
0;
myInts[1] =
1;
int myInts[3][4];
int myInts[][] = { {0,1,2,3}, {4,5,6,7},
{8,9,10,11} };
int myInts[3][4];
int myInts[][] = { {0,1,2,3}, {4,5,6,7},
{8,9,10,11} };
Now let’s use what we’ve learned about arrays and characters, and combine
them into something that will let us write sentences:
Character Arrays
Character arrays are arrays that store characters. They’re initialized the same
way as regular arrays:
char myStr[10];
char myStr[8] = {'A,’ 'r,’ 'd,’ 'u,’ 'i,’ 'n,’ 'o,’
'\0'};
The first line makes an array that resizes to contain 9 characters - the word
‘Arduino’ and the null terminator, whereas the second line’s array leaves
space for them to be put in their respective positions.
Note that a string object exists, which will be discussed outside of this
chapter, but we’ll be using character arrays more often than not.
Let’s now look at something that allows us to lock a value in stone, providing
some sort of bedrock for functions to refer to and work.
Constants
A constant remains constant, i.e., any value that it is initialized with does not
change during runtime. There are two ways to declare constants; by either
using the keyword ‘const’ for it or using ‘#define.’
The first method, using the keyword ‘const,’ changes the variable's behavior,
similar to how ‘unsigned’ works. The ‘const’ keyword serves to make the
variable read-only and cause an error if there is code that tries to change the
variable during compilation. An example is as follows:
We often use ‘const’ to declare constants, though we might prefer to use the
other method if memory is a concern.
The second method, using ‘#define,’ allows the user to name the constant for
use before the code is fully compiled, allowing you to reduce the amount of
memory (by skipping allocation of the name) that is required. This trick
proves useful in micro-controller models with smaller memory sizes, such as
Arduino Nano.
An important thing to keep in mind while using the latter method to declare a
constant is if the name we’re using for it is used elsewhere. For example,
some other array or variable or even another constant, the original constant’s
name will be replaced by its value instead. A good idea to counteract this is
to have completely uppercase names for constants and regular Camel Case
for other names.
‘#define’ also does not need to use a semicolon to terminate its line, as
follows:
#define LED_PIN
8
We’ve defined objects and initialized them with values. Let’s now look at
how we can use these values and work with them, using basic arithmetic.
Arithmetic Functions
The four basic arithmetic processes, summation, subtraction, multiplication,
and division, are allowed for by most if not all programming languages.
Arduino provides operators - characters that when used in code refer to these
arithmetic operations. These processes only work between operands of the
same datatype; however, an int will not add to a float. We can create an
exception to this rule using casting, which will be discussed in a short while.
For now, let’s look at how to implement these basic functions:
Sometimes, we might only need the remainder of the division (in the case of
integer operations), and we’ll use another tool for this, called the modulo
operator ( ‘%’ ). An example of how this would work is as follows: when 5 is
divided by 2, the result is 2.5. If we do not go into decimal places, this would
instead return a remainder of 1. This value is the result of the modulo
operation between these two numbers.
Another nifty syntax tool we can use is compound assignment operators,
which combine the arithmetic operation with the assignment (or
reassignment) operation of the variable. Here’s a list of these operators:
Comparison Operators
The Arduino language contains operator characters that allow us to make
comparisons between two objects and return a Boolean value of either one or
zero to confirm true or false, respectively. Here’s a list of those operators in
use:
Let’s now look at logical operators, i.e., the operators for AND, OR, and
NOT logical functions:
Logical Operators
‘AND,’ ‘OR,’ and ‘NOT’ are three operators that refer to their respective
logical operations. ‘AND’ checks whether both values (or the Boolean
results of some comparison statement) is true and returns true, ‘OR’ checks
for either value of the previous case and returns true, and ‘NOT’ returns the
opposite Boolean state of the value provided. Examples of these in action are
provided below:
Casting
The cast operator changes the datatype of a variable to a different one,
allowing it to be used where there’s a restriction of datatypes, like for arrays
and arithmetic operations. Values converted via this operation are truncated
to the relative decimal instead of being properly rounded up or down. For
example, 8.7 being truncated to 8 instead of being rounded to 9. Thus, it is
good to cast integers to float values instead of the other way around.
Casting is done by adding parentheses before the variable to be casted and
writing the required datatype in it. An example:
int x = 5;
float y = 3.14;
float z = (float)x +
y;
We need our program to make logical decisions as there’s not a lot one can
do without some sort of logic behind it. Since we’ve learned how to compare
values and draw some logical conclusion, let’s move on to using these tools
and code in decision-making capabilities.
Decision Making
Decisions are often a matter of whether something will happen or not. Most
programming languages, Arduino included, include an ‘if’ statement to that
end. This function will check a statement inside a pair of parentheses, and if it
is true(i.e., the Boolean statement returns a ‘TRUE’ Boolean value), it will
run code placed inside curly brackets, as follows:
if (condition) {
// Code to
execute
}
We can also use an ‘else’ statement when the conditional statement being
checked returns false. The syntax is as follows:
if (condition) {
// Code to execute if condition is
true
} else {
// Code to execute if condition is
false
}
The else statement can also check a new statement and run if it returns a
‘TRUE’ Boolean value. Note that only the first block of code for which the
respective statement returns true will execute, and the rest of the else
statements will be ignored. The following code compares two variables, and
the results of that comparison allows the ’if-else’ statements to function:
if (varA == varB) {
Serial.println("varA is equal to varB");
} else if (varA > varB) {
Serial.println("varA is greater than
varB");
} else {
Serial.println("varB is greater than
varA");
}
‘If-else' statements can get messy and expansive fairly fast, relative to how
many statements we’d need to check. We use ‘switch/case' statements when
we have multiple conditions (more than two or three).
‘switch/case’ statements take in a value inside parentheses (here ‘var’) and go
down the list of cases, comparing the cases' value. If it finds a match, the
statement inside the case runs. After its execution, we use ‘break’ to break the
switch loop. If there is no match, a default case runs and then uses ‘break’ to
end execution. The syntax for it is as follows:
switch (var) {
case match1:
// Code to execute if condition matches
case
break;
case match2:
// Code to execute if condition matches
case
break;
case match3:
// Code to execute if condition matches
case
break;
default:
// Code to execute if condition matches
case
}
Looping
There are three kinds of loops: ‘for,’ ‘while’ and ‘do/while.’ These work in
slightly different ways. Let’s start by looking at ‘for’ loops.
The ‘for’ loop continuously repeats a block of code a specific number of
times. This number is assigned to a variable that continuously changes per
iteration of the loop which can also be used to access particular indexes of
matrices.
There are three parts of a ‘for‘ loop’s statement: initialization, condition, and
increment.
The ‘while’ loop checks whether a statement is true or not and continues
running while it returns a Boolean true. Care must be taken with this
statement that the condition doesn’t infinitely return true, implying an
infinitely repeating loop. The syntax for this loop is as follows:
while (condition)
{
// code to execute
}
int x = 0;
while (x < 200)
{
// code to
execute
x++;
}
The ‘while’ loop checks the condition before execution. If we want it to be
executed at least once, we’ll use a ‘do/while’ loop. This means that in the
loop the condition is checked after the block of code is run. The syntax to
follow is like so:
do {
// code to execute
} while
(condition);
int x = 0;
do {
// code to
execute
x++;
} while (x <
200);
Functions
Functions are blocks of code that perform a specific task. They are given
unique names to identify them and called when needed. Programming
libraries often have hundreds if not thousands of pre-defined functions, and
we can create our own if we need to, as follows:
void myFunction() {
// Function code
}
void myFunction(int param)
{
// Function code
}
int myFunction() {
// Function code
}
int myFunction(int param) {
// Function Code
}
To return a value from a function, we use the keyword ‘return.’ Let’s look at
a simple example of a function:
int myFunction()
{
var x = 1;
var y = 2;
return x + y;
}
Any variables that are initialized in the function are only usable in that
domain, and cannot be called by anything outside of it (this also means that
variables with the same names can exist uniquely inside different functions,
outside of each other’s reach). The following code block demonstrates this:
int g = 1;
void function myFunction1()
{
int x1 = 2;
}
void function myFunction2()
{
int x2 = 3;
}
The variable ‘g’ is accessible globally, i.e., by both functions, but ‘x1’ and
‘x2’ can only be accessed by their respective functions, not outside of these
domains.
Chapter 3
Let’s now take the fundamental structures and syntaxes we’ve learned in the
previous chapter and apply them to make some more complex Arduino-
specific code structures. Do not be disheartened if coding doesn’t come to
you immediately; practice does make perfect, and you still have plenty of
chapters to go through still.
This chapter will go through the following topics:
Setting the pin mode of an Arduino digital pin.
Sending and receiving values to and from an Arduino digital pin.
Sending and receiving values to and from an Arduino digital pin.
Structures, unions, and how to use them.
Adding tabs to the IDE Client/Web Editor
Classes, objects, and how to use those structures.
Digital Write
The function ‘digitalWrite()’ allows us to send a digital value onto the micro-
controller’s digital pin, which then can be read by some other LED or sensor
or electrical device. The syntax for it is as follows:
digitalWrite(pin,
value);
The ‘pin’ parameter defines the pin to be used, while the ‘value’ parameter is
used to assign what value the pin should put out. This can be either HIGH or
LOW (or Boolean and binary equivalents), such as follows:
digitalWrite(LED_ONE,
HIGH);
delay(500);
digitalWrite(LED_ONE,
LOW);
delay(500);
This code makes the pin (defined by the variable LED_ONE) put out a high
voltage, wait a period of 500 milliseconds, change the pin so that it produces
a low voltage, and waits a period of 500 milliseconds again (using the
‘delay()’ function). Let’s look at a fuller version of this code block:
#define LED_ONE 11
void setup() {
pinMode(LED_ONE,
OUTPUT);
}
void loop() {
digitalWrite(LED_ONE,
HIGH);
delay(500);
digitalWrite(LED_ONE,
LOW);
delay(500);
}
This sets up pin 11 to send voltage from the board’s pin, as defined by the
constant’s value and then continues looping the rest of the functionality
discussed above.
Digital Read
The function ‘digitalRead()’ allows us to read what binary value is being
provided to a particular digital pin. This function's syntax consists of only one
parameter - the ‘pin,’ to define what pin to look at. Take heed of the fact that
this function returns an integer value, instead of a Boolean one, though these
values (0 and 1) are mutually interchangeable:
digitalRead(pin);
//a fuller example:
int val =
digitalRead(BUTTON_ONE);
Let’s again look at a more practical example of this function in use, that reads
the status of a button:
#define BUTTON_ONE 12
void setup() {
Serial.begin(9600);
pinMode(BUTTON_ONE, INPUT);
}
void loop() {
int val =
digitalRead(BUTTON_ONE);
if (val == HIGH) {
Serial.println("Button HIGH");
} else {
Serial.println("Button LOW");
}
}
analogWrite(pin,
value);
‘pin’ specifies what pin the analog value should be written on, and ‘value’
tells it the value that it is supposed to write. This value ranges from 0 to 255
(dividing the maximum value into 255 steps between the low and high states)
The following code describes how we’d use analogWrite() to make an LED
glow gradually from being off to being brightly lit:
#define LED_ONE 11
int val = 0;
int change = 5;
void setup()
{
pinMode(LED_ONE,
OUTPUT);
}
void loop()
{
val += change;
if (val > 250 || val < 5) {
change *= -1;
}
analogWrite(LED_ONE, val);
delay(100);
}
The ‘#define’ constant specifies the number 11, which is used to identify
what pin is to be written on (and whether it’s to be written on) in
‘pinMode().’ Two variables are also declared globally, which are ‘val’ and
‘change.’ This stores the current value being sent to the pin and whether it
should be changed to increment in the opposite direction according to the
conditional in the sketch’s loop. A short delay is added before the loop is to
repeat.
Analog Read
The function ‘analogRead()’ allows us to read a voltage in an analog way,
such that every step between zero and five volts is accounted for in some
manner. The value that this function returns is an integer between 0 and 1023,
meaning 1023 steps divide 5V into increments of 0.0049V. Similar to the
syntax of digitalRead(),’ ‘analogRead()’ only needs to be provided the
number of the pin it’s supposed to read. The syntax for this function is as
follows:
analogRead(pin);
#define TEMP_PIN 5
void setup() {
Serial.begin(9600);
}
void loop() {
int pinValue =
analogRead(TEMP_PIN);
double voltage = pinValue * 0.0049;
double tempC = (voltage - .5) * 100.0;
double tempF = (tempC * 1.8) + 32;
Serial.print(tempC);
Serial.print(" - ");
Serial.println(tempF);
delay(2000);
}
After pin 5 is defined as the pin to be used and read, the loop reads the
current value the pin is receiving. It converts it to the temperature being
measured via arithmetic operations (in both Celsius and Fahrenheit), and
prints this to the Serial Monitor. A two-second delay is added between loop
iterations.
These functions will be mainstays in our coding examples and practice. Let’s
now look at code constructs to store multiple objects in a defined way. We
call these constructs Structures.
Structures
A structure is a composite, user-defined datatype that can store multiple
variables of varying datatypes. The syntax for defining this construction is as
follows:
struct name
{
variable list
.
.
};
The ‘struct’ keyword precedes the name of the structure. A pair of curly
brackets stores the list of variables that we’ll keep in the structure.
In the previous section’s sketch, we used three different variables (of the
same datatype ‘double’) to define different things. Let’s try grouping them
together using a structure, and name it ‘temp_reading.’ Note again that these
datatypes do not need to be the same:
struct temp_reading
{
double voltage;
double tempC;
double tempF;
};
struct tmp36_reading
temp;
Let’s now modify our original code so that it uses a structure and define a
function that takes this function as an argument parameter:
#define TEMP_PIN 5
struct tmp36_reading {
double voltage;
double tempC;
double tempF;
};
void setup() {
Serial.begin(9600);
}
void loop() {
struct tmp36_reading temp;
int pinValue = analogRead(TEMP_PIN);
temp.voltage = pinValue * 0.0049;
temp.tempC = (temp.voltage - .5) * 100.0;
temp.tempF = (temp.tempC * 1.8) + 32;
showTemp(temp);
delay(2000);
}
void showTemp(struct tmp36_reading
temp) {
Serial.print(temp.tempC);
Serial.print(" - ");
Serial.println(temp.tempF);
}
Note the inclusion of the structure globally and a function at the end that
prints the variables inside the structure passed to it.
A structure is a good way to cut down clutter and group data, and it is a good
idea to use them to store a group of variables that contribute to closely related
actions. Another example of these groupings is as follows: the difference
between these being that only one of its variables can store a value at any
given time. These are called Unions.
Unions
This datatype allows us to store different variables of different datatypes,
similar to how structures function. However, where they diverge is in the fact
that only one of these variables is allowed to store data at a given instance.
The syntax for this construction is as follows. The only difference between
the structure’s syntax and union is the keyword:
union name
{
variable list
.
.
};
Let’s look at an example of a union. We’ll create a new union (with the name
‘some_data’) with a list of variables it can store:
union some_data
{
int i;
double d;
char s[20];
};
union some_data {
int i;
double d;
char s[20];
};
void setup() {
Serial.begin(9600);
union some_data myData;
myData.i = 42;
myData.d = 3.14;
strcpy( myData.s,
"Arduino");
Serial.println(myData.s);
Serial.println(myData.d);
Serial.println(myData.i);
}
This code creates a union (the same as before) and initializes an object,
named myData. It passes data into its variables, though printing these out
onto the Serial Monitor yields the realization that only the last variable in the
union declared is allowed to show its actual value.
‘some_data’ will only store one value at a time, shifting from the 20 of int ‘i,’
to the 3.14 of the double ‘d,’ to finally the character array storing the value
‘Arduino’ (and its null terminator).
Before we proceed, it would be prudent to familiarize ourselves with a useful
feature of the IDE Client/Web Editor; tabs.
Adding Tabs
Tabs allow you to structure your workplace into different sections, allowing
you to divide and conquer the task at hand and also reducing your frame of
focus. Let's look at how we might add tabs:
Click on the button at the IDE's top-right, with an upside-down triangle icon,
like so:
In the drop-down menu that appears, press the New Tab option, and an
orange bar will show up allowing you to name this new tab. Press the OK key
to continue with this name and creating the tab.
After you press OK, the new tab appears:
Adding new tabs in the Web Editor is pretty much the same procedure. Click
the upside-down triangle to get a drop-down menu, click New Tab, put your
preferred name for the tab into the space in the yellow bar, press OK, and
Voila! Your tab has been created.
A short note about how one might actually divide the code to distribute them
into tabs. For large programs, keep the main ‘setup()’ and ‘loop()’ functions
in one tab, and have related functions and objects grouped into one tab’s
worth of functional table-space. Add constants globally, allowing them to be
used by multiple tabs at the same time, by including them in a header file,
which contains declarations and definitions to be used outside it. Let’s
continue.
#ifndef LED_H
#define LED_H
#define LED_ONE 3
#define LED_TWO
11
#endif
This code defines ‘LED_ONE’ and ‘LED_TWO,’ and ensures this data is
transferred to each tab only once. This is done via ‘#ifndef’ and ‘#endif’. The
former looks at whether ‘LED_H’ is defined and allows the rest of the code
(before ‘#endif’) to run if it is not.
Once we are done dealing with the preprocessors, we can now proceed to
insert actual instructions to be executed by the compiler. These lines of code
are to be inserted in the tab named ‘led.’
If we analyze this small portion of code, we will see that the ‘void’ function
includes a series of parameters that control the LED’s blinking by defining
the intervals (each interval has a 500ms delay).
In the main tab, write the following to include the header file that we defined
into the sketch, using ‘#include’. Trying to refer to our constants without
using this line produces an error: “the constant was not declared in this
scope”, meaning that the compiler could not found the constant.
#include
"led.h"
Header files that we write from the sketch are surrounded by double-quotes,
while header files from some other library are surrounded by less-than and
greater-than signs. This will become useful later.
Finally, we use the function that we defined in the ‘led’ tab previously and
use it in our program’s loop. Also, you will see that in this demonstration, we
did not use the ‘#include’ preprocessor, this is because the tab we are using
does not have any header in the first place.
#include "led.h"
void setup() {
// put your setup code here, to run once:
pinMode(LED_ONE, OUTPUT);
pinMode(LED_TWO, OUTPUT);
}
void loop() {
// put your main code here, to run
repeatedly:
blink_led(LED_ONE);
delay(1000);
blink_led(LED_TWO);
}
At this point, we are now ready to take this program and execute it on our
Arduino project and see the results.
Object-Oriented Programming
Object-Oriented Programming, or OOP for short, is a methodology of coding
practices that aims to break down a program into modular component objects
that interact with one another to create its functionality. An example would
be an LED object, containing variables and such to define how we want it to
work. But we need a structure or blueprint of sorts to add these variables to,
which is where classes come in.
Create two tabs and name them ‘led.cpp’ and ‘led.h.’ The former will contain
the main body of code, while the latter will contain definitions and
initializations, but also importantly the definition of our class. Add the
following to ‘led.h’:
#ifndef LED_H
#define LED_H
#define LED_ONE 3
#define LED_TWO 11
class Led{
int ledPin;
long onTime;
long offTime;
public:
Led(int pin, long on, long
off);
void blinkLed();
void turnOn();
void turnOff();
};
#endif
This code is similar to what we used in the previous section’s header file. The
key difference is the addition of a class definition, containing three variables
(or ‘properties’) inside it. In order of appearance, these variables define what
pin to send data to, how long to keep the LED on, and how long it should stay
off.
Next, we use a constructor to make a class instance, and after that three
functions (or methods) are initialized.
Now, add the following block of code to ‘led.cpp,’ to give it functionality:
#include "led.h"
#include "Arduino.h"
Led::Led(int pin, long on, long
off) {
ledPin = pin;
pinMode(ledPin, OUTPUT);
onTime = on;
offTime = off;
}
void Led::turnOn() {
digitalWrite(ledPin, HIGH);
}
void Led::turnOff(){
digitalWrite(ledPin, LOW);
}
void Led::blinkLed() {
this->turnOn();
delay(onTime);
this->turnOff();
delay(offTime);
}
We import two header files: ‘Arduino.h’ and our own ‘led.h’ into the code's
main body. ‘Arduino.h’ contains all the libraries and their functions that
Arduino has. It is usually automatically called, but this is not the case for
different tabs, and we need to re-initialize this header file for our new
environment.
Next up is the class constructor which is required to create a method for
initializing a class. The syntax for it is to, one, name the constructor the same
as the class, and two, separate these names via a pair of colons ( :: ). This
class contains the pin and a call to the pinMode function.
Led::turnOn() and Led::turnOff() turn the LED on or off using digitalWrite(),
and we’ll use these to define how blink_Led() works. Note that we call
functions and methods of a class using ‘->’ operators, and use the keyword
‘this’ to specify the current instance.
Let’s now go back to the main tab and put all of this together:
Add the ‘#include’ line to include our header’s functionality, after which you
should create a globally accessible ‘Led’ class object, whose variables we’re
passing into the class constructor:
#include "led.h"
Led led(LED_ONE, 1000,
500);
Use the class method to blink the LED (syntaxed as ‘Led.blinkLed()’ ) in the
main tab as follows:
#include "led.h"
Led led(LED_ONE, 1000,
500);
void setup() {
}
void loop() {
led.blinkLed();
}
Uploading this code onto our previous prototype will make our LED blink.
Let’s now discuss strings, objects made of character arrays, and Arduino’s
libraries for using them:
String Library
One of Arduino’s basic libraries, this library allows us to work with character
arrays in an extremely user-friendly manner. Strings are more flexible than
these arrays, and allow us to work with text in a much easier and more
intuitive fashion, though it does take more memory than them.
We can create a string object in a variety of ways:
The first and second lines simply create strings that contain the word
‘Arduino.’ The third line creates a string with one character ‘B,’ and uses a
pair of single colons to do so. The fourth line concatenates two strings,
combining them at their ends into one new string.
We can also create strings from numbers, which is allowed for by pre-built
constructors. A few examples of this are as follows:
Strings can be used in place of character arrays when needed, but be mindful
of the fact that it requires more memory and time to execute. More often than
not, this constraint is the only reason why character arrays are used for
storing text instead of strings.
Introduction
Most common motion sensors will use infrared light to track whether
something’s passed in their vicinity. These sensors, termed Passive Infrared
Sensors (PIR Sensors), detect motion in a small range around them (usually
up to two meters for simpler sensors, but industrial and military models with
a larger range and higher accuracy exist). These are made of pyroelectric
sensors which can read radiation (emitted by every object with a temperature
higher than absolute zero) in the infrared range passively. This means that it
can only read this information and not generate anything that other devices
can work off of.
The pyroelectric sensor is divided into two halves. If there is no motion, both
halves report the same amount of radiation and nothing happens, but if there
is motion (within the sensor’s range) the halves detect different amounts of
radiation, and this dissonance causes the sensor to go off.
These sensors are available in a wide variety of constructions, shapes, sizes,
and purpose-built configurations, due to their small size and power draw, and
inexpensive nature. A few examples of products that use PIR sensors include
automatic lights, holiday decorations, pest control setups, burglar alarms, and
tripwires.
As we previously mentioned, we shall be using a motion sensor IC called
HC-SR501. The following image shows the various adjustment screws and
connectors on the body of the IC.
We’ll explain what these screws and pins do, briefly. Screws act as analog
switches, able to change values in a continuous range manually from the IC
body itself, and different screws change different function variables. Pins
allow current to flow to and from the IC, allowing communication with the
Arduino motherboard. Let’s elaborate on the labeled screws and pins and
what they do.
Sensitivity: Changes the range at which the sensor is effective,
from 3 meters to 7 meters. This value goes down with the
clockwise rotation of the screw.
Output Timing: Changes the delay or period wherein the sensor
puts out a Boolean true state (a ‘high’ or ‘1’ state), from 5
seconds to 300 seconds (5 minutes). This value goes up from the
lower end with the clockwise rotation of the screw.
Ground: Connect to the Ground of your connection (breadboard
ground rail, Arduino Ground pin, source ground, etc.)
5V: Connect to the Live of your power source, preferably a 5V
voltage (breadboard power rail, Arduino 5V pin, source power,
etc.)
Output: Connect this to the relevant Arduino pin of your
choosing. This sends out the IC output to the other ends of the
wire (i.e., the micro-controller) for the period specified via the
Output Timing screw.
Circuit Diagram
The Fritzing diagram for our build-to-be is as follows:
Notice the connections with the HC-SR501 IC’s power pins. The Ground pin
is connected to the breadboard’s ground rail, the 5V ping is connected to the
power rail, and the output pin is connected to a digital input pin on the
Arduino, whose respective Ground and 5V pins are also connected to the
breadboard as described. The circuit schematic for this setup is as follows:
Code
Using the HC-SR501 sensor with Arduino is fairly simple; we only need to
read its digital state. A HIGH state indicates the sensor has ‘seen’ something
(this signal, again, lasts for however long we specified via the analog screw,
which we’ll usually keep within the range of a few seconds), and a LOW
state indicates that it hasn’t seen anything yet. We’ll send forth this status to
the serial console, as follows:
#define MOTION_SENSOR 3
void setup() {
pinMode(MOTION_SENSOR, INPUT);
Serial.begin(9600);
}
void loop() {
int sensorValue =
digitalRead(MOTION_SENSOR);
if (sensorValue == HIGH) {
Serial.println("Motion Detected");
}
delay(500);
}
Challenge
Try adding an LED that lights up when the sensor goes HIGH. Remember to
add a resistor to the circuit. The following code lights up an LED connected
to pin 5 when the condition is met:
#define MOTION_SENSOR 3
#define LED 5
void setup() {
pinMode(MOTION_SENSOR, INPUT);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
Serial.begin(9600);
}
void loop() {
int sensorValue =
digitalRead(MOTION_SENSOR);
if (sensorValue == HIGH) {
Serial.println("Motion Detected");
}
digitalWrite(LED, sensorValue);
delay(500);
}
Circuit Diagrams
The diagram shown below demonstrates the circuit diagram needed for this
topic’s project:
Instead of the 5V that we have used in the prior projects, the Nokia 5110
LCD should utilize the Arduino's 3.3V power. The 3.3V input lines on the
LCD are protected by utilizing the inline resistors. A 1K Ω (ohm) resistor is
utilized by the CE lines and the 10K Ω resistor by the rest.
The table below tells that what pins on the Nokia 5110 LCD module are
joined to what pins on Arduino:
The Above mentioned libraries are installed because we need them and the
SPI library. To do this, the below-written include statements are added at the
start of the sketch:
#include <SPI.h>
#include < Adafruit_GFX.h>
#include < Adafruit_PCD8544.h>
We won’t wish to begin an instance of the type i.e., the Adafruit_PCD8544
by utilizing the code written below:
Adafruit_PCD8544 display = Adafruit_PCD8544(13, 11, 5, 4, 3);
The CLK, DIN, DC, CE, and RST pins respectively are connected to the
Arduino pin numbers that are basically the parameters.
To set up the Adafruit_PCD8544 instance, we should add the below-written
code in the setup ( ) function:
Serial.begin(9600);
display.begin();
display.setContrast(40);
Now the remaining piece of code can be written in the setup ( ) function or in
the loop ( ) for the test purposes. Let us begin with lighting up only one pixel
on the display. We can do this by using the function drawPixel ( ) as shown
in the piece of code below:
display.clearDisplay();
display.drawPixel(10, 10, BLACK);
display.display();
We need to clear the buffer and the display before we draw something on the
screen. This is done by using the function clearDisplay ( ). After this, to light
up only one pixel that is located at X coordinate 10 and Y coordinate 10, we
use the function drawPixel ( ). As mentioned in the previous code we should
run the display ( ) function before anything is shown on the LCD. This is
very important to keep in mind to run the function clearDisplay ( ) prior to
drawing anything on the LCD, and once we are done drawing everything on
the LCD screen to display it, we should run the display ( ) function.
Drawing a line
Instead of calling the drawPixel ( ) function several times to draw a line, it
would be much simpler to call the function drawLine ( ) as shown in the code
below:
// draw a line
display.drawLine(3,3,30,30, BLACK);
display.display();
The function drawLine ( ) accepts 5 parameters. The first and second
parameters are the X and Y coordinates for the beginning point of the line.
The third and fourth parameters are the X and Y coordinates for the ending
point of the line. The last and fifth parameter shows the color with which the
line will be drawn. In this case, only two colors i.e., Black and White are
available as the display of Nokia 5110 LCD is monochromatic.
Displaying Text
The Adafruit library additionally makes it a lot simpler to show the text on
Nokia 5110 LCD. We can display the text by using the following code:
// Display text
display.setTextSize(1);
display.setTextColor(BLACK);
display.setCursor(0,0);
display.println("Hello, world!");
// Display Reverse Text
display.setTextColor(WHITE, BLACK);
display.println(3.14);
// Display Larger Text
display.setTextSize(2);
display.setTextColor(BLACK);
display.print("This is larger text");
display.display();
To set the size of the text, the function setTextSize ( ) is used. We can see in
the first example that the size of the text is set to ‘1.’ The color of the text is
set by using the setTextColor ( ) function. As we know that the display of
Nokia 5110 LCD has a monochromatic so only two colors i.e., Black and
White are available. To write the text on the screen, the position of the cursor
is set to the position on the screen by using the setCursor ( ) function. For this
example, the position of the cursor is set to the upper left corner of the screen.
At last, the message i.e., Hello World! is displayed on the screen by using the
function println ( ).
In the next example of the above code, the foreground color is set to WHITE
and the background color is set to BLACK to reverse the text by using the
setTextColor ( ) function. Afterward, to display the value of PI on the screen
the println ( ) function is used. As the setTextSize ( ) function is not called so
the text size stays the same i.e., ‘1.’
In the third example of the code above, the text's size is set to ‘2’ and the
color is set to ‘BLACK.’
Rotating Text
The text can also be rotated. This can be done by the following code:
display.setRotation(1);
display.setTextSize(1);
display.setTextColor(BLACK);
display.setCursor(0,0);
display.println("Hello, world!");
display.display();
The text can be rotated counterclockwise using the function setRotation ( ).
To rotate the text 90 degrees counterclockwise we can use the value ‘1.’
Similarly, to rotate the text to 180 and 270 degrees counterclockwise we can
use the values ‘2’ and ‘3,’ respectively. The following image display the text
when the code written above is run:
Note that if the text's length is longer than the limit of what can be displayed
on a single line of the screen, the text will move to the next line.
Basic Shapes
The Adafruit library additionally makes it possible for us to make basic
shapes on the LCD. These shapes are rectangles, rounded rectangles, and
circles. There also exist different functions that allow us to make and fill
these shapes. The below-written code and images tell us the best way to
utilize the functions of a circle:
display.drawCircle(display.width()/2, display.height()/2, 6, BLACK);
Filled Shape
display.fillCircle(display.width()/2, display.height()/2, 6, BLACK);
Four parameters are required in the circle function. The first and second
parameters, the X and Y coordinates, are for the circle's center. In the above-
written codes, the center of the screen is considered as the center of the circle.
The radius of the circle is the third parameter. And the last and the fourth
parameter of the circle function is the color of the circle. This parameter is
also considered as the color to fill the circle for the function fillCircle ( ).
Rectangle
In this section, we will look at codes that correspond to displaying different
types of rectangles. For instance, we will see how to display a rectangle that
is internally filled with pixels, a rectangle whose corners are smoothly
rounded off instead of being sharp and pointed, and finally, a rounded corner
rectangle that is internally filled with pixels.
To display a standard rectangle, we use the following code
display.drawRect(15,15,30,15,BLACK);
Filled Rectangle
To display a rectangle that is filled on the inside, we use the following code.
display.fillRect(15,15,30,15,BLACK);
Rounded Rectangle
We use the ‘drawRoundRect()’ function from the ‘display’ class and pass it a
total of five parameters for drawing a rounded rectangle. The first and second
parameters are the X and Y coordinates of the rectangle's upper left corner.
The third and fourth parameters are the X and Y coordinates of the rectangle's
lower right corner. The fifth parameter shows the color to draw the rectangle.
This last parameter is also used to fill the rectangle with the respective color
by using the fillRect ( ) function.
To display a rectangle that has rounded corners, we use the following code.
display.drawRoundRect(15,15,30,15,4,BLACK);
Filled Rounded Rectangles
display.fillRoundRect(15,15,30,15,8,BLACK);
In this +case, there are a few minor changes, we just need to include an extra
parameter to tell the code to fill in the internals of the rounded rectangle and
use the ‘fillRoundRect()’ function instead of the ‘drawRoundRect()’
function. The initial four parameters are similar to those of the normal
rectangle functions, the two of which are the upper left corner coordinates.
The other two are the coordinates of the lower right corners of the rectangle.
The fifth parameter tells how much to round the rectangle’s corners and the
last and sixth parameter shows the color to draw and fill the rounded
rectangle.
The examples of this chapter show that with the Nokia 5110 LCD we can do
much more than text. And the Arduino library makes it simple to utilize.
We learned to add the monochromatic display of the Nokia 5110 LCD to put
projects in this topic. These displays can extraordinarily improve the client
experience of practically any project since we can mention to the clients
what’s going on with the project and tell them if there is an issue.
Chapter 4
This chapter will focus a bit more on Arduino programming and structuring
the sketches we build.
Problem
You want a piece of code to run until a given condition is true.
Solution
Until a condition is true, a while loops execute the code repeatedly.
while(analogRead(sensorPin) > 100)
{
flashLED(); // call a function to turn an LED on and off
}
The above code is written within the parenthesis of while the loop will
execute until the given condition is true i.e., value of analogRead is greater
than 100. When a value surpasses a threshold, it could blink a LED as an
obvious warning. When the analogRead is greater than 100, the led blinks
continuously. Otherwise, the LED is off if the value is less or equal to 100.
Parentheses fix the limit of a code block that is to be executed within a loop.
Only the first line of the code in executed repeatedly if the parenthesis are not
used.
while(analogRead(sensorPin) > 100)
flashLED(); // line immediately following the loop expression is
executed Serial.print(analogRead(sensorPin)); // this is not executed
until after
// the while loop finishes!!!
The ‘do… while’ loop is just like the while loop, however, the statements of
the code are run once before checking the condition. You can use do… while
loop when you want at least a single execution of the code, regardless of
whether the condition is false:
do
{
flashLED(); // call a function to turn an LED on and off
}
while (analogRead(sensorPin) > 100);
The above code will cause the LED to blink at least a single time even if the
condition is false. And the LED will keep blinking until the value from
analogRead is greater than 100. The LED will blink only once if the value is
not greater than 100. A battery – circuit could be made using this code. The
LED's persistent blinking will show that the battery is fully charged and if it
blinks every other second, this will show that the circuit is active.
You need to execute at least one statement a specific number of times. The
‘while’ loop and ‘for’ loop are almost the same. However, in the ‘for’ loop,
you have more command over the beginning and terminating conditions.
In the code lines demonstrated below, the program tells the user the ‘i’
variable’s value as it went through the ‘for’ loop.
/*
ForLoop sketch
demonstrates for loop
*/
void setup() {
Serial.begin(9600);}
void loop(){
Serial.println("for(int i=0; i < 4; i++)");
for(int i=0; i < 4; i++)
{
Serial.println(i);
}
}
We get the following result from the above sketch:
for(int i=0; i < 4; i++)
0
1
2
3
Discussion
Generally, the ‘for’ loop consists of three portions. First is the initialization,
second is the conditional test and third is iteration i.e., an expression that is
executed toward the finish of each pass through the loop. A semicolon
distinguishes all these three parts. In the above solution's code, variable i is
initialized to ‘0’ i.e., int i = 0. The condition i.e., i < 4 checks if the variable i
is less than 4. And the iteration i.e., i ++ increments the value of the variable i
by 1 after a single iteration.
A for loop can either create a new variable that is restricted within the for
loop or it can use an existing variable. The following sketch shows the use of
an already created variable:
int j;
Serial.println("for(j=0; j < 4; j++ )");
for(j=0; j < 4; j++ )
{
Serial.println(j);
}
This code is nearly similar to the previous code. However, the only difference
is in the initialization part i.e., the variable j does not have int keyword
written before it, because it is already defined outside the loop. Bothe these
codes get the same outputs as shown below:
for(j=0; i < 4; i++)
0
1
2
3
If you want to eliminate the initialization part totally you can just utilize a
variable defined before. The following code begins the loop where j has a
value equal to 1.
int j = 1;
Serial.println("for( ; j < 4; j++ )");
for( ; j < 4; j++ )
{
Serial.println(j);
}
The above code displays the following output:
for( ; j < 4; j++)
1
2
3
You control the loop termination in the conditional test. In the preceding
example, when the variable's value exceeds 4 the loop ends because the
condition is no longer true.
The code written below checks the value of the variable whether it is equal to
4 or less than 4. It displays the numbers from 0 to 4:
Serial.println("for(int i=0; i <= 4; i++)");
for(int i=0; i <= 4; i++)
{
Serial.println(i);
}
The iteration statement that is the third part of the for loop gets executed
toward the finish of each pass through the loop. This can be any legitimate
statement of C or C++. The below given code increments the value of
variable i by 2 after each iteration:
Serial.println("for(int i=0; i < 4; i+= 2)");
for(int i=0; i < 4; i+=2)
{
Serial.println(i);
}
This code prints only two values i.e., 0 and 2.
The iteration statement can be utilized to get the values from high to low, for
example in the following code, from 3 to 0:
Serial.println("for(int i=3; i > = 0 ; i--)");
for(int i=3; i > = 0 ; i--)
{
Serial.println(i);
}
Just like the other parts, the iteration statement can also be left empty. But in
mind to put the semicolons in between to separate the three parts of a ‘for’
loop.
The following piece of code shows that the for loop does not increment or
decrement the value of variable i until an input pin is high and this is dine in
the if statement after Serial.print:
Serial.println("for(int i=0; i < 4; )");
for(int i=0; i < 4; )
{
Serial.println(i);
if(digitalRead(inPin) == HIGH);
i++; // only increment the value if the input is high
}
Problem
Based on some conditions that you are testing you need to end a loop early.
You will use the code written below:
while(analogRead(sensorPin) > 100)
{
if(digitalRead(switchPin) == HIGH)
{
break; //exit the loop if the switch is pressed
}
flashLED(); // call a function to turn an LED on and off
}
Discussion
This code is like the one that uses while loops, however, this code uses a
break statement if the loop needs to be terminated if the digital pin is high.
For instance, the LED will stop blinking and the loop will terminate
regardless of whether the condition in the while loop is true, if the switch is
connected to the pins.
Chapter 5
This chapter will discuss how to use libraries, create our own, and even
modify existing libraries. In the latter half, we will cover different memory
handling techniques to make sketch programs more efficient without relying
heavily on RAM.
Modifying Libraries
Users have the option to make changes to libraries as well if they want to add
certain functionalities needed for their projects. For instance, if we download
a library named ‘TimeAlarms,’ we can use its methods and classes to
program an alarm on the Arduino board. However, this library has a
limitation: it only allows a total of 6 alarms to be set at any time. Let’s say
that we need more than six alarms for our project. In such a scenario, it is
much better and easier to modify the library itself rather than looking for one
that supports more than 6 alarms.
The following sketch program is using the ‘TimeAlarms’ library. In this
demonstration, we are specifying 7 alarms instead of 6 to show the error it
will trigger.
/*
multiple_alarms sketch
has more timer repeats than the library supports out of the box -
you will need to edit the header file to enable more than 6 alarms
*/
#include <Time.h>
#include <TimeAlarms.h>
int currentSeconds = 0;
void setup()
{
Serial.begin(9600);
// create 7 alarm tasks
Alarm.timerRepeat(1, repeatTask1);
Alarm.timerRepeat(2, repeatTask2);
Alarm.timerRepeat(3, repeatTask3);
Alarm.timerRepeat(4, repeatTask4);
Alarm.timerRepeat(5, repeatTask5);
Alarm.timerRepeat(6, repeatTask6);
Alarm.timerRepeat(7, repeatTask7); //7th timer repeat
}
void repeatTask1()
{
Serial.print("task 1 ");
}
void repeatTask2()
{
Serial.print("task 2 ");
}
void repeatTask3()
{
Serial.print("task 3 ");
}
void repeatTask4()
{
Serial.print("task 4 ");
}
void repeatTask5()
{
Serial.print("task 5 ");
}
void repeatTask6()
{
Serial.print("task 6 ");
}
void repeatTask7()
{
Serial.print("task 7 ");
}
void loop()
{
if(second() != currentSeconds)
{
// print the time for each new second
// the task numbers will be printed when the alarm for that task is
triggered
Serial.println();
Serial.print(second());
Serial.print("->");
currentSeconds = second();
Alarm.delay(1); //Alarm.delay must be called to service the alarms
}
}
Once this sketch program is uploaded to the Arduino board, it will start
executing. But we won’t do that just yet because we know it will not work.
Upon compiling and running the sketch program, the Serial Monitor will
display each task's output for a total of 9 seconds. Each second, different
tasks will be performed. The result is as shown below;
1->task 1
2->task 1 task 2
3->task 1 task 3
4->task 1 task 2 task 4
5->task 1 task 5
6->task 1 task 2 task 3 task 6
7->task 1
8->task 1 task 2 task 4
9->task 1 task 3
If we carefully analyze this result, then we can see that the task scheduled at
the 7th second did not execute. This is because we used a 7th timer object even
though the library only has 6 timer objects. To make this sketch work, we
will have to open the library to modify it. To do this, we simply open the
library we want to modify using a text editor. There’s no specific text editor
application which is mandatory to install, even the default text editors that
come with the Operating System are more than enough. Find the library you
want to modify in the ‘libraries’ folder and then open it with the text editor.
If you are running Windows, you can use ‘Notepad’ and if you are using
Mac, you can use the ‘TextEdit’ application. Once in the libraries folder, we
need to find the ‘TimeAlarms.h’ file and open it using the desired text
editor.
Once we open the header file using the text editor, the very first lines will be
like this;
#ifndef TimeAlarms_h
#define TimeAlarms_h
#include <inttypes.h>
#include "Time.h"
#define dtNBR_ALARMS 6
If we look at the very last line, we will see the number of timer objects
defined. To add support for 7 alarms instead of 6, we simply need to change
the value assigned to ‘dtNBR_ALARMS’ accordingly. Since we only want 7
alarms, we will assign it a value of ‘7.’
#define dtNMBR_ALARMS 7
Once the modifications are done, we need to save the file to make the
changes permanent and close it. Now, we run the lines of code in the Arduino
IDE again and this time, instead of the 7th-second task being missed, it will be
properly executed this time.
1->task 1
2->task 1 task 2
3->task 1 task 3
4->task 1 task 2 task 4
5->task 1 task 5
6->task 1 task 2 task 3 task 6
7->task 1 task 7
8->task 1 task 2 task 4
9->task 1 task 3
The result displayed by the Serial Output Monitor this time clearly shows us
that the task scheduled at the 7th second succeeded this time whereas it failed
when we used the original library.
However, modifications made to the library are not for free, on the contrary,
they come at a cost that can be sometimes quite hefty to pay for the board’s
resources. For instance, the type of change we made to this library will
ultimately consume more system resources and this consumption will affect
the resources available for the rest of the program. But not everything is
doom and gloom. In fact, we can use this to our advantage as well. By
carefully structuring the sketch program, we can identify the portion that
needs more system memory (RAM) and the portion that does not need it.
Since the requirement is imbalanced, we can modify certain elements of the
sketch program accordingly. For instance, we can selectively decrease the
memory allocated to the ‘serial library’ being used in the program, this will
increase the memory resource available to the rest of the program. Similarly,
we can increase the memory resource available to a library being used in the
program if the other code lines don’t require as much RAM. Hence, when
creating a sketch program, one should always be wary of system
requirements to take appropriate measures. Otherwise, the code execution
will have problems.
Creating a Library
Generally, the reason why users would want even to create libraries is not to
invent new functions and capabilities within the programming language,
instead, this method is a pretty convenient way of sharing a block of code or
reusing it in other programs.
This section will create a library from a sketch program example, which will
be done without using any classes.
The sketch we will be using for this demonstration is given below;
/*
* blinkLibTest
*/
const int firstLedPin = 3; // choose the pin for each of the LEDs
const int secondLedPin = 5;
const int thirdLedPin = 6;
void setup()
{
pinMode(firstLedPin, OUTPUT); // declare LED pins as output
pinMode(secondLedPin, OUTPUT); // declare LED pins as output
pinMode(thirdLedPin, OUTPUT); // declare LED pins as output
}
void loop()
{
// flash each of the LEDs for 1000 milliseconds (1 second)
blinkLED(firstLedPin, 1000);
blinkLED(secondLedPin, 1000);
blinkLED(thirdLedPin, 1000);
}
We will now take out the ‘blinkLED()’ function from the sketch program
and copy it over to a different file and name it ‘blinkLED.cpp.’
/* blinkLED.cpp
* simple library to light an LED for a duration given in milliseconds
*/
#include <WProgram.h> // Arduino includes
#include "blinkLED.h"
// blink the LED on the given pin for the duration in milliseconds
void blinkLED(int pin, int duration)
{
digitalWrite(pin, HIGH); // turn LED on
delay(duration);
digitalWrite(pin, LOW); // turn LED off
delay(duration);
}
All that’s left to do is create a header file with the same name as the .’cpp’
file, in this case, the name of the header file would be ‘blinkLED.h.’ The
contents of this header file are shown below;
/*
* blinkLED.h
* Library header file for BlinkLED library
*/
void blinkLED(int pin, int duration); // function prototype
Once done, we put the ‘blinkLED.ccp’ file and the ‘blinkLED.h’ into a folder
of the same name and place it in the ‘libraries’ folder. Now we are ready to
use the functions defined within this code for any sketch programs.
We can even modify a library that we create to extend its functionalities
further as well. In this case, as soon as we use the library in a blank sketch
program, all three of the LEDs on the Arduino board will start flickering. But
by adding in a few things, we can change how the library works as well. For
instance, we can add a quality of life improvement in this library by including
constants that define each blink's delays. This will allow users to refer to the
constant value when changing the delay between each blink of the LED light
instead of having to work with values in milliseconds. The first option is
more convenient and easy to deal with. To make this modification, we first
need to open the header file and inside the header file, we need to add the
following lines;
/*
* blinkLED.h
* Library header file for BlinkLED library
*/
void blinkLED(int pin, int duration); // function prototype
After that, we open the ‘blinkLED.ccp’ file and change the lines of code
present in the ‘void loop()’ section as shown below;
void loop()
{
blinkLED(firstLedPin, BLINK_SHORT);
blinkLED(secondLedPin, BLINK_MEDIUM);
blinkLED(thirdLedPin, BLINK_LONG);
}
In this way, we assigned the constant values a variable that effectively
describes the effect of the value upon the delay in the LED's blinking lights.
When we export the sketch file to the Arduino board, we will see that the
light will blink really fast at the start, then the intervals between each blink
will be longer than before and in the final blink, the delay between the on and
off intervals will be the longest.
We can also add different functions to this library as well which were not
previously present. For instance, we can specify the number of times an LED
should blink when the code is executed. This has been demonstrated in the
following lines of code;
void loop()
{
blinkLED(firstLedPin,BLINK_SHORT,5 ); // blink 5 times
blinkLED(secondLedPin,BLINK_MEDIUM,3 ); // blink 3 times
blinkLED(thirdLedPin, BLINK_LONG); // blink once
}
If we want the library to include such functionality, we will have to make
changes to both the ‘blinkLED.h’ and ‘blinkLED.cpp’ files. First things first,
we open the header file using a text editor and include the function prototype
in it;
/*
* BlinkLED.h
* Header file for BlinkLED library
*/
const int BLINK_SHORT = 250;
const int BLINK_MEDIUM = 500;
const int BLINK_LONG = 1000;
void blinkLED(int pin, int duration);
// new function for repeat count
void blinkLED(int pin, int duration, int repeats);
Next, we open the ‘blinkLED.ccp’ file and include the function
corresponding to the prototype added in the header file.
/*
* BlinkLED.cpp
*/
#include <WProgram.h> // Arduino includes
#include "BlinkLED.h"
// blink the LED on the given pin for the duration in milliseconds
void blinkLED(int pin, int duration)
{
digitalWrite(pin, HIGH); // turn LED on
delay(duration);
digitalWrite(pin, LOW); // turn LED off
delay(duration);
}
/* function to repeat blinking
void blinkLED(int pin, int duration, int repeats)
{
while(repeats)
{
blinkLED(pin, duration);
repeats = repeats -1;
}
}
However, for this demonstration to work, we need two Arduino boards and
these boards must be connected to each other through an ‘I2C’ connection.
We will discuss I2C serial port connections some other time, for now, let’s
focus on the main concept, which is to use the wire library to create another
library (which will have a bit of salvaged code as well). We will be using
appropriate code lines for handling the I2C connection and include it in the
new library we will be creating.
Let’s name the folder where we will be placing the library as ‘i2cDebug’
(reminder, every library folder which has a header and .ccp files need to be
placed within the root directory of ‘libraries’). First, let’s build a header file
for the corresponding library;
/*
* i2cDebug.h
*/
#include <WProgram.h>
#include <Print.h> // the Arduino print class
class I2CDebugClass : public Print
{
private:
int I2CAddress;
byte count;
void write(byte c);
public:
I2CDebugClass();
boolean begin(int id);
};
extern I2CDebugClass i2cDebug; // the i2c debug object
Now that we have a header file, we now need a .’ccp’ file to place it
alongside the header file in the ‘libraries’ directory inside the ‘i2cDebug’
folder. The contents of the .’ccp’ file will be as follows;
/*
* i2cDebug.cpp
*/
#include <i2cDebug.h>
#include <Wire.h> // the Arduino I2C library
I2CDebugClass::I2CDebugClass()
{
}
boolean I2CDebugClass::begin(int id)
{
I2CAddress = id; // save the slave's address
Wire.begin(); // join I2C bus (address optional for master)
return true;
}
void I2CDebugClass::write(byte c)
{
if( count == 0)
{
// here if the first char in the transmission
Wire.beginTransmission(I2CAddress); // transmit to device
}
Wire.send(c);
// if the I2C buffer is full or an end of line is reached, send the data
// BUFFER_LENGTH is defined in the Wire library
if(++count >= BUFFER_LENGTH || c == '\n')
{
// send data if buffer full or newline character
Wire.endTransmission();
count = 0;
}
}
I2CDebugClass i2cDebug; // Create an I2C debug object
Once we have created both the .’h’ and .’ccp’ files, we simply place them in
their appropriate folder inside the ‘libraries’ directory. We now have created
an entirely new library from the ‘Wire library’ and some lines of code (to
handle I2C connections). Let’s now load the following sketch program which
will be using the ‘i2cDebug library’ to perform its core functions.
/*
* i2cDebug
* example sketch for i2cDebug library
*/
#include <Wire.h> // the Arduino I2C library
#include <i2cDebug.h>
const int address = 4; //the address to be used by the communicating
devices
const int sensorPin = 0; // select the analog input pin for the sensor
int val; // variable to store the sensor value
void setup()
{
Serial.begin(9600);
i2cDebug.begin(address);
}
void loop()
{
// read the voltage on the pot(val ranges from 0 to 1023)
val = analogRead(sensorPin);
Serial.println(val);
i2cDebug.println(val);
}
Memory Handling
This section will discuss how to implement memory handling techniques to
ensure that our sketch program will never have to work with insufficient
RAM and sacrifice performance. Before we can even determine how much
memory we have to handle carefully, we first need to know how much
memory is even allocated to the sketch program in the first place. This can be
done by using the ‘memoryFree()’ function as shown in the following
demonstration;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(memoryFree()); // print the free memory
Serial.print(' '); // print a space
delay(1000);
}
// variables created by the build process when compiling the sketch
extern int __bss_end;
extern void *__brkval;
// function to return the amount of free RAM
int memoryFree()
{
int freeValue;
if((int)__brkval == 0)
freeValue = ((int)&freeValue) - ((int)&__bss_end);
else
freeValue = ((int)&freeValue) - ((int)__brkval);
return freeValue;
}
This program uses the function ‘memoryFree()’ to validate the total system
memory available for use. In turn, the function performs this task by utilizing
a special type of variable known as ‘system variables.’ System variables are
not generally used in programs because the purpose of these variables is to
facilitate the IDE’s compiler in managing the internal resources. As the
program is undergoing the execution process, the number of bytes it stores in
the system memory constantly changes. Thus, it is important to make sure
that the program only uses as much memory as is available and not more than
that.
The most common elements that drain memory have been listed below;
During the initialization of constants. For example;
#define ERROR_MESSAGE "an error has occurred"
During the declaration of global variables. For example;
*/
#include <avr/pgmspace.h> // needed for PROGMEM
// table of exponential values
// generated for values of i from 0 to 255 -> x=round( pow( 2.0, i/32.0) -
1);
const byte table[]PROGMEM = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5,
5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7,
7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10,
10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 14, 14, 14, 15,
15, 15, 16, 16, 16, 17, 17, 18, 18, 18, 19, 19, 20, 20, 21, 21,
22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 28, 28, 29, 30, 30,
31, 32, 32, 33, 34, 35, 35, 36, 37, 38, 39, 40, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 58, 59, 60, 62,
63, 64, 66, 67, 69, 70, 72, 73, 75, 77, 78, 80, 82, 84, 86, 88,
90, 91, 94, 96, 98, 100, 102, 104, 107, 109, 111, 114, 116, 119, 122,
124,
127, 130, 133, 136, 139, 142, 145, 148, 151, 155, 158, 161, 165, 169,
172, 176,
180, 184, 188, 192, 196, 201, 205, 210, 214, 219, 224, 229, 234, 239,
244, 250
};
const int rawLedPin = 3; // this LED is fed with raw values
const int adjustedLedPin = 5; // this LED is driven from table
int brightness = 0;
int increment = 1;
void setup()
{
// pins driven by analogWrite do not need to be declared as outputs
}
void loop()
{
if(brightness > 255)
{
increment = -1; // count down after reaching 255
}
else if(brightness < 1)
{
increment = 1; // count up after dropping back down to 0
}
brightness = brightness + increment; // increment (or decrement sign is
minus)
// write the brightness value to the LEDs
analogWrite(rawLedPin, brightness); // this is the raw value
int adjustedBrightness = pgm_read_byte(&table[brightness]); // adjusted
value
analogWrite(adjustedLedPin, adjustedBrightness);
delay(10); // 10ms for each step change means 2.55 secs to fade up or
down
}
When working with a large expression of values that iterate over a regular
interval, it is better to simply calculate these values before-hand and store
them in the form of an array. In this way, when the code is executed, it
doesn’t have to calculate each value repeatedly. This is not only time-
efficient, making the program to run faster, but also memory efficient as well
because if the values were to be calculated multiple times, then the result
would be stored in the system’s RAM. Instead of doing that, we calculated
the values before-hand and stored the resulting array in the program memory,
hence saving Arduino’s RAM resource from being completely drained by
this program. At the beginning of the sketch program, we first and foremost
define the table used to store the values. This table is created through the
following line;
const byte table[ ]PROGMEM = {
0, . . .
The ‘PROGMEM’ expression is used to inform the compiler that the values
written henceforth are to be saved in the board’s program memory rather than
the board’s system memory. The values are then defined in the form of an
array. To use the ‘PROGMEM’ argument, the sketch program needs the
corresponding definitions as well, otherwise, the compiler won’t be able to
understand this instruction. For this purpose, we include a header file with the
name of ‘pgmspace.h’ in the libraries folder and then import it into the
program using the ‘#include’ argument.
The overall brightness of the LED light is controlled using the following lines
of code in the sketch program shown above to ensure a smooth fading
transition;
int adjustedBrightness = pgm_read_byte(&table[brightness]);
analogWrite(adjustedLedPin, adjustedBrightness);
This entire expression can also be written in the following way as well;
pgm_read_byte(table + brightness);
Let’s see another demonstration as well.
/* ir-distance_Progmem sketch
* prints distance & changes LED flash rate depending on distance from
IR sensor
* uses progmem for table
*/
#include <avr/pgmspace.h> // needed when using Progmem
// table entries are distances in steps of 250 millivolts
const int TABLE_ENTRIES = 12;
const int firstElement = 250; // first entry is 250 mV
const int interval = 250; // millivolts between each element
// the following is the definition of the table in Program Memory
const int distanceP[TABLE_ENTRIES] PROGMEM = {
150,140,130,100,60,50,
40,35,30,25,20,15 };
// This function reads from Program Memory at the given index
int getTableEntry(int index)
{
int value = pgm_read_word(&distanceP[index]);
return value;
}
If you recall the beginning of this book, you’ll find that we discussed a
similar experiment by using the LDR sensor instead of an Infrared Sensor.
However, the difference is that instead of measuring the light intensity being
emitted by the LED, we measure the distance of the light coming from the
LED and reaching the Infrared sensor. In the case of the LDR experiment, we
assigned different values that correspond to the different intensities of the
LED light. Similarly, we will assign values in this program as well but these
values will be stored in the board’s flash memory instead of RAM because all
of these values are constant (meaning, the values themselves won’t change).
To do this, we use the function ‘PROGMEM.’
The distance is measured and interpreted by using the function
‘getDistance()’ and the ‘getTableEntry() function is used by the program to
fetch the corresponding values from the program memory and not from the
RAM.
int getDistance(int mV)
{
if( mV > interval * TABLE_ENTRIES )
return getTableEntry(TABLE_ENTRIES-1); // the minimum distance
else
{
int index = mV / interval;
float frac = (mV % 250) / (float)interval;
return getTableEntry(index) - ((getTableEntry(index) -
getTableEntry(index+1)) * frac);
}
}