0% found this document useful (0 votes)
62 views157 pages

Zlib - Pub Arduino Programming Tip and Tricks To Learn Arduino Programming Efficiently

Uploaded by

yos
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
62 views157 pages

Zlib - Pub Arduino Programming Tip and Tricks To Learn Arduino Programming Efficiently

Uploaded by

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

Arduino Programming

Tip and Tricks to Learn Arduino


Programming Efficiently
© Copyright 2020 All rights reserved.
This document is geared towards providing exact and reliable information
in regards to the topic and issue covered. The publication is sold with the
idea that the publisher is not required to render accounting, officially
permitted or otherwise qualified services. If advice is necessary, legal or
professional, a practiced individual in the profession should be ordered.
From a Declaration of Principles which was accepted and approved equally
by a Committee of the American Bar Association and a Committee of
Publishers and Associations.
In no way is it legal to reproduce, duplicate, or transmit any part of this
document in either electronic means or in printed format. Recording of this
publication is strictly prohibited, and any storage of this document is not
allowed unless with written permission from the publisher. All rights
reserved.
The information provided herein is provinced to be truthful and consistent,
in that any liability, in terms of inattention or otherwise, by any usage or
abuse of any policies, processes, or directions contained within is the
solitary and utter responsibility of the recipient reader. Under no
circumstances will any legal responsibility or blame be held against the
publisher for any reparation, damages, or monetary loss due to the
information herein, either directly or indirectly.
Respective authors own all copyrights not held by the publisher.
The information herein is offered for informational purposes solely and is
universal as so. The presentation of the information is without a contract or
any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication
of the trademark is without permission or backing by the trademark owner.
All trademarks and brands within this book are for clarifying purposes only
and are owned by the owners themselves, not affiliated with this document.
Contents
Arduino Programming
Tip and Tricks to Learn Arduino Programming Efficiently
Introduction
Chapter One: Basic Concepts of Programming
Chapter Two: Input / Output Management
Chapter Three: Programming With Arduino
Chapter Four: Accessories for Arduino
Conclusion
References
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)
However, the true power of Arduino lies in a dedicated programming
language based on C / C ++. Starting the adventure with microcontrollers,
it's worth learning at least the basics about their construction and how they
work.
Fortunately, in the case of Arduino, to program your system, you do not
need to know the microcontroller registers. Everything is based on friendly
libraries, thanks to which the creation of even a complicated program is
within reach of a novice programmer.
In short, Arduino is modules with microcontrollers that can be easily
programmed using generally available libraries in a language similar to C /
C ++.
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.
Arduino - Choosing a Hardware Platform
Arduino is an Open Hardware platform. This means that all materials
needed to create your own development kit operating in this standard are
available. For this reason, you can find many different tiles compatible with
Arduino.
At the moment, Arduino officially talks about 20 available models on its
websites. In every good store, you will find at least a few different sets. For
the needs of the book, I decided to choose the most popular tile - Arduino
UNO R3.
Arduino is a project that is constantly growing - both in programming and
hardware. The UNO version 3 board is currently prompted by Arudino, like
the one on which the latest libraries and expansion boards can be used for a
long time.
Equipment Arduino UNO R3
The heart of the system is the popular 8-bit microcontroller from Atmel,
AVR ATmega328, operating at a frequency of 16 MHz .
Working at such a frequency in a simplified way means that the
microcontroller can perform 16 million operations per second. It's a lot.
Special connectors, placed characteristically on the sides of the board, are
the outputs of the most important signals. There we will find 14
programmable digital inputs/outputs. Six of them can be used as PWM
outputs (e.g., for motor control), and another six as analog inputs. We will
also find there a reset signal and power supply.
Arduino can be powered in several ways. The most popular methods are:

1. Power supply via USB cable


2. Powered by a plug-in power supply (optimally 7V - 12V) or
batteries
The most important elements are marked on the graphic below:

1. USB connector - used for power supply, programming, and


communication with a computer
2. Power connector (optimally 7V - 12V)
3. Voltage stabilizer - the input voltage from connector 2 is reduced
to 5V thanks to this system
4. Reset button - resets the Arduino board
5. Microcontroller responsible for communication with the
computer via USB
6. Programming connector for the microcontroller from step 5.
7. Signal connector *
8. Signal connector *
9. LED diode signaling connection of voltage to Arduino
10.
Programmer output for the microcontroller from
point 13.
11.
Signal connector *
12.
Power connector *
13.
Arduino heart, AVR ATmega328 main
microcontroller
14.
LEDs signaling transmission to/from the computer
15.
LED at the user's disposal
16.
Ceramic resonator clocking the microcontroller
(point 13) with a frequency of 16MHz
17.
A jumper that when cut off disables Arduino's
automatic reset.
18.
Solder pads with derived microcontroller signals
from point 5, used extremely rarely in very specific and non-
standard situations.
Clones, or Arduino (un) Original
As I mentioned, Arduino is an open-hardware platform. This means that
anyone can make their own Arduino or design a tile per this standard. Sets
from other companies operating, such as Arduino, are commonly called
clones.
Clones can be divided into two types:

Total fakes, imitating originals


The tiles comply with the Arduino standard
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.
Arduino IDE Installation
The appropriate environment must be installed before programming. The
latest Arduino IDE can be downloaded from the project's official website .
The installer takes about 53 MB .
Warning. Update (14.04.2015)
Due to the conflict, two versions of the environment appeared within the
Arduino team. Fortunately, this doesn't matter much to the end-user.
However, if you purchased the original board, check the address on its back
before installing the environment.
There you will find a reference to one of the following pages:

http://arduino.org/
http://arduino.cc/
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 .
What happens when you install the wrong IDE?
Note - You will only be notified that the tile you have does not come from
an authorized source. You can turn off this message with one click.
Everything will work without problems.
Download the latest version.
Installation is standard. In the beginning, we accept the product license:
Then click a few times Next, and we become happy users of the Arduino
IDE. Along the way, pay attention to the components installed:
If we choose to install the USB driver (which is recommended), we will see
a system warning at the end of the installation .
Click " Install this driver software anyway, " you don't have to worry about
anything. After the installation is complete, a new icon should appear on
your desktop:
If the software has been installed correctly, we will see the welcome screen
after starting it:
And after a while the editor:
If you already have Arduino
I wrote earlier that we would not program in this part. However, if you
already have Arduino, you can do something very simple to check if
everything works. First, start the Arduino IDE editor. Then from the menu
select:
File -> Examples -> 01. Basics -> Blink
A separate window will open with the program code (do not temporarily
penetrate its structure). It should look similar to the following:
Now connect your Arduino to the computer. Use a USB cable for this, and
you do not need to connect battery power. You only need this one cable.
Now the computer will detect new hardware and install drivers .
When the equipment is ready for use, check which COM port has been
assigned to your board. You can do this by going to the device manager:
Computer -> Properties -> Device Manager
Now we can go back to the Arduino IDE settings. Here we have to choose
two options. First of all, we tell the compiler which board we use. Then
indicate the previously checked COM port number.
The Arduino IDE only shows the available COM ports. For me it was
COM1 and COM21, you can have many more. The main thing is to choose
the right one.
Board connected and set up. Now we can proceed to upload the program.
To do this, we need to choose two options:

Verify
Load
The first one is the equivalent of "Compiles" found in other environments.
This process is responsible for checking the correctness of the code and its
compilation, or conversion into a language understandable for programmed
electronic devices.
The second command is responsible for sending the program to the Arduino
UNO board. After clicking the Load button, the LEDs labeled TX and RX
should flash on the board. This means that the data is transferred from/to
the computer.
When the process is done correctly, you'll find the appropriate message at
the bottom of the Arduino IDE. There will be information that the program
has been sent and how much space has taken up in the memory of our
microcontroller - in this case, it was 1 084 bytes.
The fact that the program has been sent correctly can also be seen on
Arduino. As I mentioned earlier, we have 1 LED on the board. After
uploading the program, it should flash.
The effect is not thrilling, but we know that everything works. Next, we'll
start writing programs ourselves. In the meantime, you can try to edit the
code we have downloaded and test how the system will behave.
Now here it’s enough "long introduction" to the book. I hope that it explains
the basic issues and encourages you to follow the next chapter.
Chapter One: Basic Concepts of Programming
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.
Decimal <-> Binary
To convert a decimal number (in base 10) to a binary number (in base 2,
you follow that's good.), You need to know how to divide by 2. Will it be
okay? Take your number, then divide it by 2. Then divide the quotient
obtained by 2, then so on until you have a zero quotient. Then you have to
read the remains from bottom to top to get your binary number.
Binary <-> Hexadecimal
Converting from binary to hexadecimal is the easiest to do .
First, start grouping the bits in blocks of four starting at the right. If there
are not enough bits left to make the last group of four, we add zeros.
Take the number 42, which is written in binary, as we have seen, 101010,
and we will get two groups of 4 bits, which will be 0010 1010. Then,
calculate block by block to obtain a hexadecimal digit taking into account
the value of each bit. The first bit of low weight (far right) will be worth,
for example, A (: A in hexadecimal). Then the other block will simply be
worth 2 (). So 42 in the decimal base is worth 2A in the hexadecimal base,
which is also written to pass from hexadecimal to binary, it suffices to do
the reverse operation with the help of the decimal base from time to time.
The procedure to follow is as follows:
- I separate the numbers one by one (we get 2 and A)
- I "convert" their values to decimal (which makes us 2 and 10)
- I put these values in binary (and we, therefore, have 0010 1010)
Decimal <-> Hexadecimal
This case is more delicate to treat because it requires to know the
multiplication table by 16. As you have followed the previous explanations,
you understand how to do it here. As I am bad at math, I would advise you
to go through the binary base to do the conversions.
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 .
Approach and Use of the Software
Let's take a more serious look at the use of the software. The menu bar is
surrounded in red and numbered by number 1.
The File Menu
It is mainly this menu that we will use the most. He has several things that
are going to be very useful to us:
New: will allow you to create a new program. When this button is pressed,
a new window, identical to this one, appears on the screen.
Open: with this command, we will be able to open an existing program
Save / Save as: save the current document/request where to save the current
document
Examples: this is important; a whole list is scrolled to display the names of
examples of existing programs; here, you can help you create your own
programs.
The rest of the menus are not interesting for the moment, we will come
back to this later, before starting to program.
Buttons
Now let's see what the buttons are for, framed in red and numbered by the
number 2.
Button 1: This button allows you to check the program, it activates a
module that searches for errors in your program
Button 2: Create a new fil e
Button 3: Save the current program Button 4: We do not touch it for the
moment Button 5: Stop the verification
Button 6: Load an existing program
Button 7: Compile and send the program to the card
Finally, we will be able to take care of the equipment that you should all
have right now: the Arduino board.
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.
Presentation of the Card
To start our discovery of the Arduino board, I will present the board itself.
We will see how to use it and with what. I have represented in red on this
photo the important points of the map.
Constitution of the Card
Let's see what these important points are and what they are used for.
The micro-controller - This is the brain of our map (in 1). It will receive the
program you have created and store it in the memory and then execute it.
Thanks to this program, it will know how to do things suchs as: flashing an
LED, displaying characters on a screen, sending data to a computer, etc .
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.
Test your Equipment
Before starting to program the head down, it is first of all necessary to test
the correct functioning of the card. Because it would be silly to program the
card and look for errors in the program when the problem comes from the
card. > <We will test our hardware by loading a program that works on the
card. But we haven't made any programs yet?
Barely. But the Arduino software contains sample programs. Well, these are
the examples that we will use to test the card.
1st step: Open a Program
We are going to choose a very simple example that consists of making a
LED flash. His name is Blink, and you will find him in the Basics category
.
Last Step
Now, we will have to send the program to the card. To do this, click on the
Upload button.
At the bottom of the image, you see the text: "Uploading to I / O Board...,”
this means that the software is sending the program to the card.
The message display: "Done uploading" indicates that the program has been
loaded onto the card. If your hardware is working, you should have a
flashing LED on the board:
If you do not get this message but rather something in red, do not worry, the
equipment is not necessarily defective.
Indeed, several errors are possible:
- IDE recompiles before sending code, check for error
- The serial channel may be badly chosen, check the connections and the
choice of the serial channel
- the IDE is coded in JAVA, it can be capricious and bug from time to time
(especially with the serial channel...): try the sending again.
The Arduino Language (1/2)
To be able to program our card, we need three things:

A computer
Arduino board
And know the Arduino language
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 .
The Minimum Code
With Arduino, we have to use minimal code when creating a program. This
code allows dividing the program that we are going to create into two big
parts.
Code: C
void setup ()
{
// card initialization function
// content of initialization
}
void loop () // main function, it repeats (runs) endlessly
{
// content of your program
}
So you have before you the minimum code to insert into your program. But
what can it mean for someone who has never programmed?
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 1
0
1 1 1 1 1 1 1 1 1 2
1 2 3 4 5 6 7 8 9 0
2 2 2 2 2 2 2 2 2 3
1 2 3 4 5 6 7 8 9 0
3 3 3 3 3 3 3 3 3 4
1 2 3 4 5 6 7 8 9 0
4 4 4 4 4 4 4 4 4 5
1 2 3 4 5 6 7 8 9 0
5 5 5 5 5 5 5 5 5 6
1 2 3 4 5 6 7 8 9 0

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... "
The Name of a Variable
The variable name accepts almost all characters except:
. (point)
, (the comma)
é, à, ç, è (the accents)
Well I will not give them all, it only accepts the alphanumeric alphabet ([a-
z], [A-Z], [0-9]) and _ (underscore)
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 byt e
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
One of the peculiarities of the Arduino language is that it accepts a larger
number of types of variables.
Type what number does it store? Maximum values of the stored number,
Number on X bits Number of bytes like below:

byte non-negative integer 0 to 255 8 bits 1 byte


non-negative integer word 0 to 65535 16 bit 2 byte
non-negative integer boolean 0 to 1 1 bit 1 byte
The Arduino Language (2/2)
I have a question. If I want to make the code I wrote repeat itself, do I have
to copy it as many times as I want? Or is there a solution?
This is an excellent question because it is precisely the object of this
chapter. We will see how to make a piece of code repeat itself. Then we will
see, next, how to organize our code so that it becomes more readable and
easy to debug. Finally, we will learn to use the tables that will be very
useful.
Here is the program waiting for you.
import processing.video.*;
Movie movie;
void setup()
{
size(640,360);
background(0);
//load and play the video in a loop
movie = new Movie(this,"transit.mov");
movie.loop();
}
void movieEvent(Movie m)
{
m.read();
}
void draw()
{
//if (movie.available() == true)
//{
// movie.read();
//}
image(movie,0,0,width,height);
}
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.
The while loop
Problem: I want the electric shutter of my window to close automatically
when night falls. We will not take care of making the system that closes the
shutter at the arrival of the night. The Arduino board has a sensor which
indicates the position of the flap (open or closed). What we are trying to do
is create a piece of code that brings the shutter down until it is closed.
To solve the problem, we will have to use a loop.
/ * HERE, a bit of program allows you to do the following things :
_ a sensor detects nightfall and daybreak o If it is night, then we must close
the shutter
o Otherwise, if it is the day, we must open the shutter
_ the program reads the state of the sensor which indicates whether the
shutter is open or closed
_ recording of this state in the String variable: position_volet
o If the shutter is open, then: position_volet = "open";
o Otherwise, if the shutter is closed: position_volet = "closed";
*/
while (position_volet == "open")
{
// instructions that lower the shutter
}
The do... while loop
This loop is similar to the previous one. But there is a difference that
matters. In fact, if we pay attention to the condition in the while loop, we
will notice that it is tested before entering the loop. While loop, the
condition is tested only when the program has entered the loop:
Code: C
do
{
the instructions between these braces are repeated as long as the condition
is false } while (/ * condition to test * /) ;
The word does come from English and translates as do. So the do while
loop means "do the instructions, as long as the condition tested is false."
While in a while loop, you could say, "as long as the condition is false, do
the following."
What Does it Change?
Well, in a while loop, if the condition is true from the start, we will never
enter this loop. Conversely, with a loop do while we enter the loop, then we
test the condition. Let's take our counter:
let i = 5;
do {
alert( i );
i++;
} while (i > 5);
In this code, the counter value is defined from the start at 5. However, the
program will enter the loop when the condition is false. So the loop is
executed at least once. And whatever the veracity of the condition. In the
test it gives:
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.
I did not really understand what it is for
The usefulness of a function lies in its ability to simplify the code and
separate it into "little bits" that we will assemble to create the final program.
If you want, it's a bit like plastic building sets: each piece has its own
mechanism and performs a function.
For example, a wheel makes it possible to roll; a block makes it possible to
join several other blocks together; a motor will move the created object
forward. Well, all these elements will be assembled to form an object (car,
house, etc.). like, the functions will be joined together to form a program.
For example, we will have the function: "squaring a number"; the function:
"add a + b"; etc. Which, in the end, will give the desired result.
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.
But what is "Void"?
I arrive there. Remember, a little above, I explained to you that a function
could return a value, the famous output value, I will now explain how it
works.
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 "Typed" Functions
Indeed, if we want to create a function that calculates the result of an
addition of two numbers (or a more complex calculation), it would be good
to be able to return the result directly rather than to store it in a variable
which has a global scope and access that variable in another function.
Clearly, calling the function gives us the result directly. We can then do
"what we want" with this result (store it in a variable, use it in a function,
make it undergo an operation,...)
How to Create a Typed Function
In itself, this is not complicated, and you have to replace the void with the
chosen type (int, long, etc.) Here is an example:
void setup(){
Serial. begin(9600);
}

void loop() {
int i = 10;
int j = 44;
int k;

k = myMultiplyFunction(i, j); // k now contains 440


Serial.println(k);
delay(500);
}

int myMultiplyFunction(int x, int y){


int result;
result = x * y;
return result;
}
Note that I have not put the two main functions, namely setup () and loop (),
but they are mandatory.
In the loop () function, we do a calculation with the value returned by the
function myFunction (). In other words, the calculation is: calculation = 10
* 44; Which gives us: calculation = 440.
Well, this is a very simple example to show you how it works. Later, when
you are ready, you will certainly use this combination in a more complex
way .
As this example is very simple, I did not write the value returned by the
function myFunction () in a variable, but it is better to do so. At least, when
it is useful, which is not the case here?
Functions with Parameters
It's all very nice, but now you're going to see something much more
interesting. Here is a code; we will see what it does after:
void loop(){
int i = 2;
int j = 3;
int k;

k = myMultiplyFunction(i, j); // k now contains 6


}
What is going on?
I defined three variables: sum, x, and y. The function of my Function () is
"typed" and accepts parameters. Let's read the code at the beginning:
void setup(){
Serial.begin(9600);
}

void loop() {
int i = 2;
int j = 3;
int k;

k = myMultiplyFunction(i, j); // k now contains 6


Serial.println(k);
delay(500);
}

int myMultiplyFunction(int x, int y){


int result;
result = x * y;
return result;
}
We Declare our Variables
The loop () function calls the myFunction () function that we created
It is on this last point that we will look. We gave the parameters function.
We use these parameters to "feed" the function. To put it simply, we say to
the function: "These are two parameters, I want you to use them to do the
calculation I want."
Then comes the signing of the function
The signature... what are you talking about?
The signature is the "full title" of the function. Thanks to it, we know the
name of the function, the type of the returned value, and the type of the
different parameters.
The function retrieves the variables sent to it from variables. In other words,
in the variable param1, we find the variable x. In the variable param2, we
find the variable y.
Either: param1 = x = 64 and param2 = y = 192 .
Finally, we use these two variables created "on the fly" in the function's
signature to perform the desired calculation (a sum in our case).
What's the point of doing all this? Why don't we use the variables x and y
in the function?
This will help us to simplify our code. For example, you want to do several
operations (addition, subtraction, etc.), and instead of creating several
functions, we will only create one that does them all. But, to tell it which
operation to do, you will give it a parameter telling it: "Multiply these two
numbers" or else "add these two numbers."
What it would do:
So if the operation variable is 0, we add the variables x and y; otherwise, if
the operation is 1, we subtract y from x. Simple to understand, isn't it?
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.
What's the Point?
We will mainly use arrays when we need to store information without
creating a variable for each information.
The Maximum Score
As the title indicates, we will look for the maximum grade (the best student
in the class). The function will receive in parameter the array of float, the
number of elements in this array, and will return the best note.
Code: C
float bestNote (float array [], int highNumber)
{
int i = 0;
int max = 0; // variables containing the highest grade
for (i = 0; i <highNumber, i ++)
{
if (table [i]> max) // if the grade read is better than the best current
{
max = array [i]; // then we save it
}
}
return max; // we return the best grade
}
What you do to read an array is exactly the same as when you initialize it
with a loop.
It is quite possible to put the value of the searched box in a variable:
Code: C
int value = array [5]; // we save the value of the box
6 of the array in a variable
Well, it was not that hard; you can do the same to find the minimum value
To practice.
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 grade s
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 Two: Input / Output Management
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.
Our First Program
You have finally arrived at the fateful moment when you will have to
program. But before that, I will show you what will serve us for this
chapter. In this case, learn to use an LED and the reference, present on the
Arduino.cc site, which will be very useful when you need to make a
program using a concept that is not covered in this book .
The LED / LED Light-Emitting Diode
The question is not to know which abbreviation to choose, but to know
what it is.
A LED / LED: Light-Emitting Diode, or "Light Emitting Diode”. It is an
electronic component that creates light when an electric current flows
through it. I made you buy different colors. You can, for this chapter, use
whatever you want. You see, a photo of a red LED. The size is not real, its
"head" (in red) is only 5mm in diameter. It is this component that we will
try to light with our Arduino board. But before, let's see how it works.
I will call the light-emitting diode, throughout the book, an LED. An LED
is a diode that emits light. So I will talk to you about how LEDs work at the
same time as LEDs. There is very little difference between the two. The
LED is simply a diode that emits light, hence the arrows on its symbol.
Direct Polarization
We speak of polarization when an electronic component is used in an
electronic circuit in the "right way." In fact, when it is polarized, it is
because we use it in the desired way.
To polarize the diode, we ensure that the current must flow from the anode
to the cathode. In other words, the voltage must be higher at the anode than
at the cathode.
Reverse Polarization
The reverse bias of a diode is the opposite of forwarding bias. To create this
type of assembly, it is simply enough, in our case, to "turn over" the diode
finally to connect it "upside down." In this case, the current does not pass.
Note: a reverse-biased diode will not burn out if used in the right
conditions. In fact, it works "the same way" for the positive and negative
current.
If you do not want to make your first diode go up in smoke, I advise you to
read the next lines carefully. In electronics, we must take two parameters
into account: current and voltage. For a diode, two voltages are important.
These are the maximum voltage in forwarding polarization, and the
maximum voltage in reverse polarization. Then, for the LEDs to work
properly, the current is also important.
Maximum Direct Voltage
When using a component, we must get into the habit of using the
"datasheet" ("technical documentation”), which gives us all the
characteristics of the component. In this datasheet, we will find something
called "Forward Voltage” for the diode. This indicator represents the
voltage drop across the diode when current flows directly through it. For a
conventional diode (type 1N4148), this voltage will be around 1V. For a
led, we will rather consider a voltage of 1.2 to 1.6V.
Well, to make our small assemblies, we will not quibble, but it is the
approach to do when we design an electrical diagram and that we
dimension its components.
Maximum Reverse Voltage
This voltage represents the maximum admissible difference between the
anode and the cathode when the latter is connected "upside-down." In fact,
if you put too much voltage on these terminals, the junction will not be able
to support it and will go up in smoke. We find this voltage under the name
of "Reverse Voltage" (or even "Breakdown Voltage"). If we take the diode
1N4148, it will be between 75 and 100V. Beyond this voltage, the junction
breaks, and the diode becomes unusable. In this case, the diode becomes
either a short circuit or an open circuit. Sometimes this can cause significant
damage to our electronic appliances. Anyway, we will never handle 75V.
The Flowing Current
For an LED, the current flowing through it is important. If you connect the
led directly to a battery, it will light up, then sooner or later, will eventually
go out.
If we do not limit the current flowing through the LED, it will take the
maximum current, and that is not good because it is not the maximum
current that it can support. To limit the current, a resistor is placed before
(or after) the LED. This resistance, expertly calculated, will allow it to
ensure optimal operation.
But how do you calculate this resistance?
Simply with the basic formula, ohm's law. Little reminder:
Then, we will take for the example a supply voltage of 5V (at the output of
the Arduino, for example) and a voltage at the terminals of the LED of 1.2V
in normal operation. We can, therefore, calculate the voltage which will be
at the terminals of the resistor:
Finally, we can calculate the resistance value to use :
And voila, you know the value of the resistance to use to be sure not to burn
LEDs out of the arm. Is it better to use a higher value or lower value
resistor?
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.
Create A New Project
To be able to program our card, we must create a new program. Open your
Arduino software. Go to the File menu and choose the Save as... option:
What is it?
Arduino is a project in which the community is very active, offers us on its
website a reference. But what is it? Well, it is simply the "user manual" of
the Arduino language.
More precisely, an internet page on their site is dedicated to referencing
each code that can be used to make a program.
How to use it?
To use it go to the page of their site. What we see when we get to the page
is three columns, each with an element that makes up the Arduino
languages.
Structure: this column references the elements of the Arduino language
structure. It contains conditions, operations, etc.
Variables: As its name suggests, it brings together the different variables
that can be used, and certain specified operations
Functions: Here it is everything else, but especially the read / write
functions of the pins of the microcontroller (and other very useful
functions)
It is very important to know how to use the documentation that Arduino
offers us. Because knowing this, you can make programs without having
previously learned to use one function or another .
Turn on our LED
1st Step
First of all, we must define the pins of the microcontroller. This step itself
makes up two sub-steps. The first being to create a variable defining the pin
used, then define if the pin used should be an input of the microcontroller or
an output.
The term const means that we define the variable as being constant. We
change the nature of the variable which then becomes constant.
The term int corresponds to a type of variable. By defining a variable of this
type, it can store a number ranging from - 2149531648 to +2197438647.
That is enough for us.
We are, therefore, in the presence of a variable named led_red, which is a
constant which can take a value ranging from -2147483648 to
+2147483647. In our case, we assign this variable to 2.
When your code is compiled, the microcontroller will know that on its pin
number 2, there is a connecting element.
Well, that is not enough to define the pin used. We must now say whether
this pin is an input or an output. Yes, because the microcontroller can use
some of its pins for input or output. It is fabulous. It suffices simply to
interchange ONE line of code to say that it is necessary to use a pin as input
(retrieval of data) or as output (sending of data).
This line of code precisely, let’s talk about it. It must be in the setup ()
function. In the reference, what we need is in the Functions category, then
in Digital I/o. I/o for Input / Output, which means: Input / Output .
The function is pinMode (). To use this function, you must send it two
parameters: The name of the variable that you defined on the pin.
2nd Step
This second step is to create the content for our program. Whoever is going
to replace the comment in the loop () function, achieving our aim: turn on
the LED.
Again, we do not snap our fingers to have the program ready. You have to
go back to the Arduino reference to find what you need.
Yes, but now we don't know what we want?
We are looking for a function that will allow us to light this LED, so we
have to find it. Let's be a bit logical if you don't mind. We know it's a
function we need (I said it a moment ago), so we look in the Functions
category of the reference.
If we keep our logical mind, we will take care of lighting an LED, so to say
what is the output state of pin number 2 where which is connected to our
LED. So it's a safe bet that it's in Digital I/o. Well, there is a suspicious
function called digitalWrite (). In French, this means "digital writing." It is,
therefore, the writing of a logical state (0 or 1).
What is the first sentence in the description of this function? This one:
"Write a HIGH or a LOW value to a digital pin." According to our bilingual
level, we can translate by Writing a HIGH value or a LOW value on a
digital output. Bingo. This is what we were looking for .
What does "HIGH Value or LOW Value" Mean?
In digital electronics, a high level will correspond to a voltage of + 5V, and
a so-called low level will be a voltage of 0V (generally ground). Except that
we have connected the LED to the positive pole of the power supply so that
it lights up, we must connect it to 0V. Therefore, a low state must be set on
the pin of the microcontroller. Thus, the potential difference across the
LEDs will allow it to light up.
Let's take a look at how digitalWrite () works by looking at its syntax. It
requires two parameters. The name of the spindle that we want to put in a
logical state and the value of this logical state.
We will therefore write the following code, using this syntax:
Code: C
digitalWrite (led_red, LOW); // write output (pin 2) of a LOW state
If we test the whole code:
Code: C
const int led_red = 2; // definition of pin 2 of the card as a variable
void setup ()
// card initialization function
{
pinMode (led_red, OUTPUT); // initialization of pin 2 as an output
}
void loop () // main function, it repeats (runs) endlessly
{
digitalWrite (led_red, LOW); // write output (pin 2) of a LOW state
}
We see the LED light up... It's fantastic .
Now you know how to use the outputs of the microcontroller, so we can get
down to business and make our LED flash.
Enter time
It is fine to light an LED, but if it does nothing else, it is not very useful.
You might as well plug it directly into a battery (with resistance all the
same.). So let's see how to make this LED interesting by making it flash.
For this, we will have to introduce the concept of time. Well, guess what?
There is a ready-made function there again. Let's go to practice.
How to do this?
Have a look for yourself; it will help you learn
I let you search a little by yourself, and it will train you.
For those who have attempted to search and have not found the function,
here it is: delay ()
A short description of the function will be used to pause the program for a
predetermined time.
Use the Command
The function accepts a parameter, which is the time during which we want
to pause the program. We must give this time in milliseconds. If you want
to stop the program for 1 second, you will have to give the function at the
same time, written in milliseconds, or 1000ms .
Practice: Flash an LED
So, if we want to make our LED flash, we will have to use this function.
The LED lights up. Then, we use the delay () function, which will pause the
program for a certain time. Then we turn off the LED. We pause the
program. Then we return to the start of the program. We start again, and so
on. It is this command sum, which forms the process that causes the LED to
flash.
Henceforth, get into the habit of making this kind of diagram when you
make a program.
Now we need to translate this diagram, bearing the name of the
organization chart, into code. You have to replace the sentences in each
frame with a line of code.
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.
Limits of the Delay () Function
You have probably noticed that when you use the "delay ()" function, our
whole program stops waiting for you to wait. Sometimes, this is not a
problem, but in some cases, it can be more troublesome.
Imagine, you are moving a robot forward. You put your motors at medium
speed, quiet, until a small button on the front is pressed (it clicks when you
touch a wall, for example). During this time, you decide to make signals by
flashing your LEDs. To make a nice flash, you turn on a red LED for one
second and then turned it off for another second. This is, for example, what
we could do as code:
Code: C
void setup ()
{
pinMode (motor, OUTPUT); pinMode (led, OUTPUT); pinMode
(button, INPUT);
digitalWrite (motor, HIGH); // we start the engine
digitalWrite (led, LOW); // we turn off the LED
}
void loop ()
{
if (digitalRead (button) == HIGH) // if the button is clicked (we enter
a wall)
{
digitalWrite (engine, LOW); // we stop the engine
}
else // otherwise we blink
{
digitalWrite (led, HIGH); delay (1000); digitalWrite (led, LOW);
delay (1000);
}
Please note this code is not at all rigorous or even false in its writing; it
serves to understand the principle.
Now imagine you drive, test the button that is not pressed, so blink the
LEDs (case of else). The time you do, the entire display runs out two long
seconds. The robot has been able to take the wall in the middle of this pearl
for eternity, and the motors continue to advance head down until smoking.
It is not good at all.
Chapter Three: Programming With Arduino
This chapter starts much theory, we begin directly with programming.
"Learning by doing" is the magic word here. While the left side of the so-
called "sketches" are printed and are located in the right pane Reviewing the
code.
Anyone who works through the programs under this system will be able to
see through the program code in a short time and apply yourself. Later even
become familiar with other functions you then. This guide is only an
introduction to the Arduino platform. All possible program functions or
Program code is on the website "www.arduino.cc " under the point called
"reference."
Before we start a piece of brief information on possible errors that might
arise while working with the Arduino software. The most common are the
following two:

1. The board is not installed properly or selected the wrong board.


When Upload, it displays the sketch an error message at the
bottom of the software that roughly looks like as shown at right.
In error, the text is then a Noted "not in sync."
2. There is an error in the sketch. For example, a word is
misspelled, or it lacks only a clamp or a semicolon. In the
example, the left brace that introduces the loop part is missing.
The error message then begins often with "expected...” This
means that the program expects something that does not yet
exist.
The Basic Structure of a Sketch
We may divide a sketch into three areas.
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.
2. Setup (essential in the program)
The setup is performed by the Board only once. Here, dividing the program
with, for example, which pin is (slot for cable) on the microcontroller
board, an output or an input.
Here, a voltage at the output Board shall: defined as the output. Example:
This pin an LED to be illuminated.
Defined as input: Here, a voltage to be read by the Board. Example: a
switch is pressed, and the Board noted the fact that he recognizes this input
pin voltage .
3. Loop (essential in the program)
The loop portion is repeated continuously by Board. It processes the sketch
once completely to the end and then starts again at the beginning of the loop
part.
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.
1.2 Program Section 2: Setup
We have only one exit - to pin 13 to a voltage output (the LED will light up
eventually.) .
We write in the middle of the white box the Arduino software:
void set up() // Here the setup starts

{ // brace on - Here begins a program section.

} // curly bracket - Here ends a program section.

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.

1.3 Program section 3: Loop (main body)


void set up() // Here the setup starts
{ // Here a program section starts. pinMode(13,
OUTPUT); // pin 13 is to be a starting
} // Here a program segment ends. void loop() // Here the
main program begins
{ // Here a program section starts.
} // Here a program segment ends.
Now the contents of the loop part, ie, the main program is introduced: THIS
IS THE COMPLETE SKETCH:
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(1000); // wait 1000 milliseconds (one
second)
digitalWrite(13, LOW); // Turn the the voltage at pin 13 from (LED
off). delay(1000); // wait 1000 milliseconds (one second).
} // Program section completed.

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.
The Change Indicators
Material: Arduino / two light-emitting diodes (blue) / two resistors 100
ohms / Breadboard / cable
Sketch:
void set up()

{ // // We start with the Setup

pinMode(7, OUTPUT); // pin 7 is an output. pinMode(8th,


OUTPUT); // pin 8 is an output.
}

void loop()

{ // The main program starts.

digitalWrite(7, HIGH); to Pin7 // Turn on the LED.


delay(1000); // wait 1000 milliseconds. digitalWrite(7,
LOW); // Turn the LED off at Pin7. digitalWrite(8th,
HIGH); // Turn the LED on a Pin8.
delay(1000); // wait 1000 milliseconds. digitalWrite(8th,
LOW); // Turn the LED off at Pin8.
} // Here at the end of the program jumps to the start of the loop
part. So…
//... turn the LED on pin 7.
//... etc... etc... etc.. .
An LED Pulsing Leave
Task: An LED to be pulsed light and dark. (Also referred to as English.
"Thread")
Material: Arduino / an LED (blue) / A resistor 100 Ohm / Breadboard /
cable assembly:
The Arduino is a digital microcontroller. We know it outputs only "5 volts"
or "5V off". To vary the brightness of an LED, you would need, but the
voltage may vary. For example, 5V when the LED light illuminates. 4 volts
when darker lit something so GOING TO DIGITAL PINS BUT NOT.
There is an alternative, however. It is called pulse width modulation (PWM
called).
The PWM pulsates the 5V voltage. The voltage is thus a millisecond on and
off. At a high PWM, the 5V signal is almost continuously on the respective
pin. At a low PWM, the 5V signal is virtually non-existent (since this is a
very compact summary, you should look on the Internet for further
explanation).
This PWM, you can achieve a similar effect with LEDs as if you were the
voltage varies. Not all digital pins on the board have the PWM function.
The pins on which the PWM works are specially marked, e.g. through a
small wave of the number with the pin number. Here we go.
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 pulsatio n
// 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 .


Simultaneous Lighting and Sound
Task: An LED and a piezo speaker will continuously flash or beep.
Material: Arduino / a LED / A resistor 200 Ohm / A piezo speaker /
Breadboard / cable
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 o n
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.
Activate a LED Touch of a Button
Task: An LED to be lit for 5 seconds when a button has been operated.
Material: Arduino / an LED (blue) / A resistor 100 Ohm / A resistor 1K
ohms (1000 ohms) / Breadboard / cable / probe
The microcontroller can output to its digital pins, not only tensions but also
read out. We want to try this program. In the structure, however, there is a
special feature. If you simply connect the switch only to the
microcontroller, then up to the pin of the microcontroller to a voltage as
soon as the button is pressed.
You can think of it that way as if many electrons are floating around the
said pin. If we then release the button, no new electrons are more being
added to the pin on the microcontroller. Now the rub comes. The electrons
that have made it before relaxing on the pin, then still there and escape only
very slowly over small leakage currents.
The microcontroller then so thinks that the button is not pressed only
briefly, but that it is pressed very long. Namely, until no electrons spend
more on the pin, this problem can be correct in that one grounding pin via a
resistor to about 1000 ohms (1K ohms). The electrons can thus very quickly
drain away from the pin, and the microcontroller detects that the button has
been "touched" only briefly.
Since the resistance, the voltage at the input pin to 0V always "pulling
down,” it is also referred to as a "pull-down" resistor. NOTE: If you use it
too small, resistance can cause a short circuit to the microcontroller when
the button is pressed that one grounding pin via a resistor to about 1000
ohms (1K ohms).
The electrons can thus very quickly drain away from the pin, and the
microcontroller detects that the button has been "touched" only briefly.
Since the resistance, the voltage at the input pin to 0V always "pulling
down,” it is also referred to as a "pull-down" resistor. NOTE: If you use it
too small, resistance can cause a short circuit to the microcontroller when
the button is pressed that one grounding pin via a resistor to about 1000
ohms (1K ohms).
The electrons can thus very quickly drain away from the pin, and the
microcontroller detects that the button has been "touched" only briefly.
Since the resistance, the voltage at the input pin to 0V always "pulling
down,” it is also referred to as a "pull-down" resistor. NOTE: If you use it
too small, resistance can cause a short circuit to the microcontroller when
the button is pressed.
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.

An RGB LED Drive


Task: An RGB LED should light up in different colors
Material: Arduino board / RGB-LED / three resistors with 200 Ohm /
Breadboard / Cable
What is an RGB LED?
An RGB LED is an LED that can light up in different colors. After the
name of the RGB Color Bet "Red,” "Green" and hide
"Blue." The LED is in the interior of three individually addressable LEDs,
which shine in the three colors. Therefore, an RGB LED also has so many
legs, for example, 4/6/8 legs . The longest of the four legs depending on the
version of the common anode (+) or
Cathode (-). With the three shorter legs of the RGB LED, we can control
each color.
Version a "common cathode" - the longest leg of the LED is "-,," and the
three shorter legs are controlled by "+" (voltage).
Version b) "common anode" - the longest leg of the LED is "+," and the
three shorter legs are - controlled (GND). " "
Through a blend of colors, many other colors can be produced very. For
example, results from the control of the color "blue" and "green" color
"Turquoise."
Which version you own, you can find by simply repositioning of "+" and "-
" on the LED out (Info: An LED lights up only when properly mated)
The Arduino is a digital microcontroller. He knows his digital outputs only
"5 volts" or "5V off". So you can generate many different colors with an
RGB LED each color of the LED but must be controlled more accurately.
This can be done with pulse width modulation and the PWM (pulse width
modulation) can be used to the digital pins on the board at which it prints a
small shaft.
The PWM allows the voltage between + 5V and 0V pulsate. The voltage is
thus a millisecond on and off. At a high PWM, the 5V signal is almost
continuously on the respective pin. At a low PWM signal is the 5V virtually
non-existent (Since this is a very compact summary, you should look on the
Internet for further explanation).
This PWM can achieve a similar effect in LEDs, as would be the voltage
varies. The following codes work for both RGB versions alike. It needs
only one thing to be observed: In the LED version b (Common anode)
should be the value of the "Dark" is set to the 255th. This has the
consequence that then, not only a positive voltage at the common positive
terminal of the LED but also to the corresponding color. Then, the LED can
be no current flowing, and the respective color of the LED remains off
between the two contacts .
For this reason, that in this version of the LED, the color is brighter when
the value is smaller is also noted for the color mixture. Thus the color lights
blue to pin 3 in the sketch bright, if we choose the code for the blue color
like this:
int brightness1a = 0;
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 voltag e
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 Brightness Sensor
Now it's getting more complicated.
Task: An LED should light when it gets dark or when a photoresist is
covered.
Material: Arduino / a LED / resistor with a 200 Ohm / a resistor of 10K
ohms / Breadboard / cable / photoresistor
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).
The "Serial Monitor"
The "serial monitor" is an important part of the Arduino software. This
"serial monitor" you can display data on the PC, which the microcontroller
board to the PC sends (numbers or text). This is very useful because you do
not an LCD display that is always connected to the microcontroller, on
which one could read certain values.
In the sketch, the "serial monitor” is used to display the values that read the
board of the photoresistor. Why is this useful? Suppose the LED to begin
only at the onset of darkness to light. Then it must be in an area Sketch
gives, which has the function: "If the value of the photo resistance below
the value x, then the LED lights will." It would have to know how big the
value of x at the onset of twilight.
Solution: (. Eg dusk) I send the read value "x" of the voltage across the
photoresistor with appropriate brightness at the "serial monitor" and let him
see me there. With this knowledge, I can later modify the program in the
following form. "If the voltage output of the photoresistor has a value of" x
"below, then turn on the LED."
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 51 2
// 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
wit h
// "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),

temp [9] = map(analog 0 410 -50, 150);


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 the n
// 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

if (Distance> = 500 || distance <= 0) // If the measured distance


over
// is 500cm or 0cm...

Serial.println("No reading"); // then is to spend the serial monitor


"No
// reading "because readings are wrong or inaccurate in these areas.
}

else //otherwise..
{

Serial.print(distance); //... should the value of the distance to the


serial monitor
// output here.
Serial.println("cm");
}

delay(1000); // The delay of one second provides in about


every new second for
// a new measurement.
}
Expansion of the Program:
When a distance is measured 80cm, a piezo speaker to beep.
int trigger = 12; int echo = 13; long time = 0;
long distance = 0;

int piezo = 5; // The word piezo is now the number 5 void set
up()
{

Serial.begin (9600); pinMode(Trigger, OUTPUT); pinMode(echo,


INPUT);
pinMode(Piezo, OUTPUT); // The piezo speaker to pin 5 should
be a starting
// (logical because the yes from the microcontroller board yes a
voltage required to
beeping //

void loop()

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);
}
Enhancements: Reversing Warning
With this code, we can construct a reverse warning system, on pin 12
besides "measure distance" to the already connected ultrasonic sensor from
the Sketch 10 (connects an LED.

... you can wrap an image already follows construct the reverse warning
anyway?
int trigger = 7; int echo = 6; long time = 0; int LED = 12;
long distance = 0;

void set up()


{
Serial.begin (9600); pinMode(Trigger, OUTPUT); pinMode(echo,
INPUT); pinMode(12, OUTPUT);
}

void loop()
{
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 <= 40)


{
digitalWrite(LED, HIGH); delay(Distance * 3); digitalWrite(LED,
LOW); delay(Distance * 3);
}
}
Infrared Remote Control for Controlling Arduino Microcontrollers
Material: Arduino / Breadboard / cable / infrared sensor / infrared remote
control
With an infrared receiver that an Arduino board evaluates the commands of
an infrared remote control. The data is sent in the form of infrared light
from the remote control to the receiver. Since our eyes can not perceive this
light, we can’t see it.
With a little trick, however, you can test whether a remote control, for
example, sends an infrared signal. This involves taking a digital camera (for
example, by phone) and viewed via the display, the infrared diode. Now, if
we press the remote control, you can see the lights infrared diode because
the sensors of digital cameras perceive infrared light and can represent. The
light flickers easily, since the infrared diode toggle very quickly and
outgoing. Underlying this is a very specific rhythm that can test the basis of
which the infrared receiver later, which key was pressed on the remote
control.
This sketch is a slight modification of Sketches "IRrecvDemo," default in
the Arduino main program can not find which under the examples .
This sketch is very short and therefore lends itself very well for the first
experiments.
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 (Bes t
// 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 les s
// 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.
Read an RFID tag with Arduino and Process the Data
Material: UN or MEGA Arduino, RFID reader, at least one RFID tag,
display plate, display plate cable, LED, 200-ohm resistor.
Task: Using an Arduino microcontroller, an RFID tag to be read. Unless it
is the correct TAG, it is to light an LED for 5 seconds.
Wiring the Arduino board with the RFD-receiver:

Board: Arduino Uno Arduino Mega MFRC522 READER


Pin 10 53 SDA
code:
Pin 13 52 SCK
code:
Pin 11 51 MOSI
code:
Pin 12 50 MISO
code:
Pin unassigned unassigned IRQ
code:
Pin GND GND GND
code:
Pin 9 5 RST
code:
Pin 3.3V 3.3V 3.3 V
code:

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.
Preparation - the first sketch with the RFID READER
First, we will read the UID ( "Unique Identification Number"), i.e., the
individual name of an RFID tag. We use the following program (Attention,
the program only works if we added the library to the Arduino software).
The program is provided an R3 microcontroller for the UN. In MEGA2560
and other controllers, the pins have to be added accordingly.
#include <SPI.h> // SPI Bibliotheque Add #include <MFRC522.h> //
add RFID Bibliotheque #define SS_PIN 10 // SDA to pin 10 (MEGA
otherwise) #define RST_PIN 9 // RST to pin 9 (MEGA otherwise)
MFRC522 mfrc522 (SS_PIN, RST_PIN); // RFID receiver name

void set up() // start the setup:


{
Serial,begin(9600); // start serial connection (Monitor)
SPI,begin(); // build SPI connection mfrc522.PCD_Init (); //
initialization of the RFID receiver
}

void loop() // Here, the loop part begins

if (. Mfrc522.PICC_IsNewCardPresent ()) // If a card within reach


// is...
{

return; // go on...

if (. Mfrc522.PICC_ReadCardSerial ()) // When an RFID transmitter


was selected

return; // go on...

Serial,print("The ID of the RFID TAGS is:"); // "The ID of the RFID


TAGS
// reads: "is written to the Serial Monitor for (byte i = 0; i
<mfrc522.uid.size; i ++)

{
Serial,print(Mfrc522.uid.uidByte [i], HEX); // Then the UID is read,
// each of four blocks is and sequentially to the serial
// Monitor sent. The ending Hex means that the four blocks of the
UID

// is (including letters) output as a HEX number

Serial,print(""); // The "Serial.print (" ") command;" ensures tha t


// stands between the individual blocks read a space.

}
Serial,println(); // This line is on the Serial Monitor only
// line break made.

}
If all is well, the result of the Serial Monitor looks (Apart from the own
UID) like this:

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.print("The card number is ::"); // Finally, the number code (you


can not call him as a UID more) output .

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 Four: Accessories for Arduino
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 resul t

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

lcd.setCursor(0.1); // move to the begining of the second line lcd_key


= read_LCD_buttons (); // read the buttons

switch (Lcd_key) // DEPENDING ON whichButton was pushed, we


perform in action
{
case btnRIGHT:
{
lcd.print("RIGHT"); digitalWrite (2, LOW); break;
}
case btnLEFT:
{
lcd.print("LEFT"); break;
}
case btnUP:
{
lcd.print("UP"); break;
}
case btnDOWN:
{
lcd.print("DOWN"); break;
}
case btnSELECT:
{
lcd.print("SELECT"); break;
}
case btnNONE:
{
lcd.print("NONE"); break;

}
}
}
Instructions for LCD Display with I2C Port
The LCD module with a soldered I2C bus allows the use of an LCD module
with simple wiring. This is particularly advantageous in more complex
projects. Another difference from the normal LCD display is that a knob is
located on the back of the display, with the brightness of the LCD can be
added.
Note:
These instructions will only work with an I²C module on the back of the
display without three solder points labeled A0, A1, and A2.
Material: microcontroller (in this example, UN R3), LCD with I2C module,
cable
Wiring: The wiring is very simple. On the I2C LCD module, only four
contacts are available. GND is connected to the GND contact on the
microcontroller. VCC 5V with the contact on the microcontroller, SDA to
the analog input A4 and SCL with the analog input A5.
Attention: In the MEGA2560 R3, microcontrollers are available for the
SDA - and SCL contacts separate entrances on the board under 20 and 21.
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 indicat e

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);

}
Two I²C Displays
Use two I²C displays at the same time, Arduino.
Caution:
This structure and the associated change in the I²C address is only possible
with displays that have a jumper function. We can see this in the following
image to the red area. On the points A0, A1, and A2, we can solder a
contact bridge.
In addition, the NewliquidCrystal_1.3.4 Library is required for these
instructions which can be downloaded here:
https://bitbucket.org/fmalpartida/new- liquid crystal/downloads
The library needs to be added to the Arduino software (see previous
instructions I²C display).
Material: Arduino / 2 displays with I²C module / Breadboard / cabl e
Task: Two LCDs with I²C module to be driven simultaneously by an
Arduino microcontroller and display two different texts. For this, the I²C
addresses are the displays that are found earlier, and we can change the
address of display.
First, a Brief Explanation of the I²C Address
Each I²C module has a so-called "HEX address." Using this address, the I²C
module reacts to the data being sent from the Arduino on the data bus at
exactly that address. Many I²C LCDs also have the same HEX address.
That means it would react with the use of two displays, both displays to the
transmitted data from the Arduino board. One might, therefore, represent
two displays with no different data.
The HEX address can at the screen using the A0, A1, and A2 solder joints.
However, it changed. As established, all three solder joints are not
connected depending on the combination, which one of the bridged areas
with a solder joint, so eight different addresses are possible. Depending on
display type, this address may initially be 0x27 or 0x3F (we can find it with
the address "scanner,” more on that later).
Tables HEX addresses depending on the soldered points (I = connected: =
not connected):
A A1 A HEX address HEX address
0 2
: : : 0x27 0x3F
I : : 0x26 0x3E
: I : 0x25 0x3D
I I : 0x24 0x3C
: : I 0x23 0x3B
I : I 0x22 0x3A
: I I 0x21 0x39
I I I 0x20 0x38

We come to the I²C addresses "Scanner":


The "Scanner" is basically where the LCD module is connected; only one
code is uploaded to the Arduino and then displays the HEX address to the
serial monitor.
Step Guide to I²C addresses "Scanner":

1. The same LCD module with the Arduino connected:

I²C LCD module >> Arduino 5V VCC >>


GND GND SDA >> >> >> A4 SCL A5

2. Load following sketch to the microcontroller:


// 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):

Again, the actual instructions:


To be able to display on two I²C displays simultaneously two different texts,
the displays must have different HEX addresses. So we solder in our
example, at one of the displays the A1 contact, so that it now has the
address 0x3D (can be checked with the addresses scanner again). We call
this display from now on display 2 and the other display. 1
Code:
#include <Wire.h> integrate //Wire.h Library
#include <LiquidCrystal_I2C.h> integrate //LiquidCrystal_I2C.h
Bibliothel LiquidCrystal_I2C LCD1 (0x3F, 2, 1, 0, 4, 5, 6, 7, 3,
POSITIVE); // Here is
// display one named as LCD1, given the address "0x3F" and the
// Pinassignment through the I²C module specified
LiquidCrystal_I2C LCD2 (0x3D, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);//
Here is
// Display 2 named as LCD2, the address specified "0x3D" and the
// Pinassignment through the I²C module specified void set up()
{
LCD1.begin(16.2); // Display 1 is started and the size of the display
// is specified (16 characters, two lines) LCD1.backlight(); Switch //
Lighting Display 1
LCD2.begin(16.2); // Display 2 is started and the size of the display
// is specified (16 characters, two lines) LCD2.backlight(); Switch //
Lighting Display 2
}
void loop()
{
LCD1.setCursor(0,0); // text is the first character in the front row
// start at Display 1.. LCD2.setCursor(0,0); // display at 2 also..
LCD1.print("Display 1"); // Display 1 to the top "Display 1" Show
LCD2.print("Display 2"); // Display 2 should show up "display 2"
delay(1000); // wait a second
LCD1.setCursor(0.1); // text is the first character in the second row
// start at Display 1.. LCD2.setCursor(0.1); // display at 2 also..
LCD1.print("XYZ GmbH"); // Display 1 to bottom "XYZ GmbH"

LCD2.print("Www.xyz.com");// Display 2 "Www.xyz.com"


}
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}; // se t
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
/ cabl e
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.
Arduino Tilt Sensor SW-520D
Sketch: Reading With the Arduino a tilt sensor SW-520D
The Arduino can be in different inclinations measures. Very accurate
measurements you get, for example, with an acceleration sensor in which
one can almost measure any angle exactly. It is, however, also easy with the
tilt sensor (SensorTilt or Tiltswitch).
However, this sensor detects only two stages, namely "inclined" or "not
inclined." For this purpose, the sensor roll inside around two free-moving
metal balls. Once the sensor is tilted so that one of the balls inside against
the two contacts about these two contacts are interconnected. This is then as
if a button is pressed, and the electric current can flow from one contact to
another contact.
Therefore, the sketch and the structure is very similar to how the Stretch
with the button.
When the sensor is used as in the picture vertically, for example, if it is
simply plugged into the breadboard, the circuit between the two contacts is
closed, and the current can flow from one contact to another.
Once the sensor is inclined by more than 45 °, the balls of the two contacts
away and the connection is broken .
Task:
With a Tilt sensor to be turned on, an LED, when an inclination of more
than 45 ° is present
Material: Arduino / a LED / A resistor 100 Ohm / A resistor 1K ohms (1000
ohms) / Breadboard / cable / inclination sensor
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.
Temperature Measured with the LM35
Task:
With the temperature sensor, LM35 temperature is to be read and displayed
monitor serial-by.
Material:
Arduino / cable / LM35 temperature sensor/screw Shield or cable for
soldering to the sensor
The sensor has three connections. The red Contact 5V, the black GND, and
the yellow is the contact for the temperature signal. At this contact, the
sensor outputs a voltage between 0 and 1.5 volts. Wherein 0V 0 ° C and the
corresponding value of 1.5V corresponds to 150 ° C. The voltage of this pin
has to read from the microcontroller board and converted into a temperature
value.

The special at this temperature sensor is its waterproof feature.


Thus, the temperature can be measured by liquids with the
LM35.
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 this is it improves considerably the sensor accuracy
(9V AC adapter or 9V battery).
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.
Expansion of the Program:
Once the temperature has reached 30 ° C, to a warning sound (beep of a
piezo speaker).
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.


}
}
Measure the Voltage
With the Arduino microcontroller board and a voltage sensor, one can
measure the electrical voltage. We use a sensor that can lie to Measuring
voltage in a range between 0 and 25V DC (direct current).
Task:
A voltage with a voltage sensor (voltage sensor) measure and display on the
serial monitor.
Material :
Arduino / cable / voltage sensor
We want to measure a voltage of a voltage sensor and display them on the
serial monitor. For example, a voltage sensor makes sense if you want to
measure a voltage exceeding the maximum measurable voltage (5V) from
the Arduino.
For example, a voltage sensor can measure in the range of 0-25V voltages.
The module measures the voltage and converts them into measurable for the
Arduino values.
By mathematical formulas in the code, it is possible to specify a voltage
indicated on the serial monitor.
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 .
We now come to the code:
int value1;
float value2;

void set up()


{
Serial,begin(9600); // start serial connection
}

void loop()
{
float temp;
value1 =analog read(1); // read voltage value at analog input 1 temp =
value1 / 4,092; // value mathematically convert to the voltage value to
obtain in volts
value1 = (int) Temp; value2 = ((% value1 100) /10.0);
Serial,println(Value2); Show // Final voltage value in the serial
monitor
delay(1000); // wait a second
}
If you now open after successful upload of the code the serial monitor, you
can now see a voltage value every second. Since it still connects no power
source, this should be at 0.00.
To see if everything is working, you can test as to connect GND contact
from the sensor to the GND contact from the Arduino and the VCC contact
from the sensor to the 3.3V contact from the Arduino. Now a value should
show up to 3.3V on the serial monitor. The sensor is not quite exact. So it
was with us 3.2V .
Four-Digit 7-Segment Display
Task :
We want to display any number on the four-digit seven-segment display.
Material :
Arduino / cable / 4 digit 7-segment display / 1K ohm resistors
The 7-segment display has 12 pins at the back, six at the top, and six at the
bottom. Four of these pins correspond to each number. They can be
"common anode," "common cathode," or. On which screen you can try the
code, but we'll talk about that later. The other eight pins belong to each
segment and the dot next to the number.
On a 7-segment display with only one or two digits, the segments are
controlled by each digit separately. However, since this even greater
confusion on the cable will be four digits than it already is, these displays
work with "multiplexing." This means that if, for example, the four digits
have to be checked at the same time, they will be checked very quickly.
This happens so quickly that it seems to the human eye as if all four digits
are displayed at the same time.
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
represent s
// 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/DFR000
9_Web.pd f
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_S
hield
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/downl oads/
TCS230_COLOR_SENSOR.pdf
https://github.com/Nikaoto/Shamen/blob/master/lib/deep.lua
http://arduino-tutorials.eu/arduino-four-digit-seven-segment-display

You might also like