Zlib - Pub Arduino Programming Tip and Tricks To Learn Arduino Programming Efficiently
Zlib - Pub Arduino Programming Tip and Tricks To Learn Arduino Programming Efficiently
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:
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:
void loop() {
int i = 10;
int j = 44;
int k;
void loop() {
int i = 2;
int j = 3;
int k;
In part between the braces, we now introduce the setup information. In this
case, "an output pin 13 is supposed to be."
void set up() // Here the setup starts
{ // Here a program section starts.
pinMode(13, OUTPUT); // Pin 13 is what the output should be.
} // Here, a program segment ends.
Finished. The sketch should now look exactly as it appears on the screen is
shown on the right. It has to be now uploaded to the board. This works
with the red circled button (top left of the software).
1.4 Now we can create variation to the program. For example, the LED
will blink rapidly. To do this, we reduce waiting times (from 1000ms to
200ms)
void set up() // Here the setup starts
{ // Here a program section starts.
pinMode(13, OUTPUT); // pin 13 to be an output.
} // Here, a program segment ends. void loop() // Here the
main program begins
{ // Program section begins.
digitalWrite(13, HIGH); // Turn the the voltage at pin 13 a
(LED on). delay(200); // Wait 200 milliseconds
digitalWrite(13, LOW); // Turn the the voltage at pin 13 from (LED
off). delay(200); // Wait 200 milliseconds
} // Program section completed .
The new Sketch must now again be uploaded to the board. If all goes well,
the LED is now flashing faster.
The Change Indicators
Material: Arduino / two light-emitting diodes (blue) / two resistors 100
ohms / Breadboard / cable
Sketch:
void set up()
void loop()
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").
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.
void loop()
} // 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.
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.
{
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()
{ // 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 "
else
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()
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"
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),
// 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()
{
void loop()
else //otherwise..
{
int piezo = 5; // The word piezo is now the number 5 void set
up()
{
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,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 loop()
{
digitalWrite(Trigger, LOW); delay(5); digitalWrite(Trigger, HIGH);
delay(10); digitalWrite(Trigger, LOW); duration =pulseIn(echo,
HIGH); Distance = (time / 2) / 29.1;
else
{
Serial.print(distance); Serial.println(" Cm");
}
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.
Serial.begin(9600);
void loop() {
}
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.
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() {
}
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() {
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 / /
}
void loop()
{ // This brace is the Loop section opened.
void loop()
else //…otherwise…
}
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 loop()
{ // This brace is the Loop section opened.
void loop()
if (Reading > 400) // Here the query begins: When the sensor
value is les s
// is called "400,” then...
else //…otherwise…
}
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:
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
return; // go on...
return; // go on...
{
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
}
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 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.
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
void loop()
{
if (. Mfrc522.PICC_IsNewCardPresent ())
{
return;
}
if (. Mfrc522.PICC_ReadCardSerial ())
{
return;
}
long code = 0;
{ // 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
} 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
}
}
}
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
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.begin();
void loop()
}
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
Wire.beginTransmission (i);
if (Wire.endTransmission () == 0)
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:
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."
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 loop()
{
Tasterstatus1 = digital read(Taster1);// Status of Taster1 read (HIGH
or LOW)
Tasterstatus2 = digital read(Button2); // Status of button2 read (HIGH
or LOW)
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 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."
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 loop()
{
delay(Time);
temperature = (temp [0] + temp [1] + temp [2] + temp [3] + temp [4]
+ temp [5] + temp [6] + temp [7] + temp temp [8] + [ 9]) / 10;
int piezo = 5; // The word "piezo" is now the number five, so five of
the piezo is connected to the port.
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");
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() {
void loop() {
}
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