Arduino Programming The Ultimate Beginners Guide To Learn Arduino Programming Step by Step PDF
Arduino Programming The Ultimate Beginners Guide To Learn Arduino Programming Step by Step PDF
com
Arduino programming
The Ultimate Beginner's Guide to Learn Arduino Programming Step by
Step
2020
1nd Edition
By John Bach
mEmlnc.com
"Programming isn't about what you know; it's about what you
can figure out.” - Chris Pine
This book will help you to develop working source code for the Arduino
microcontroller. In these pages, we will primarily concern ourselves with the
software aspect of physical computing—designing code to work with
physical objects that exhibit behavior or interactivity through software.
Starting with the basic context of the Arduino platform to getting up and
running with our first code, we will discuss the structure and syntax of
Arduino’s C-based programming language, looking at variables, control
structures, arrays, and memory. This book will then go into many of the
functions unique to Arduino development for controlling digital and analog
input and output, timing, randomness, writing functions, and using many of
the Arduino libraries for working with different kinds of hardware and
communication protocols. Arduino, like Processing before it, adopted the
idea of a code sketchbook. We will carry on this metaphor as we talk about
the process of sketching in code as an intuitive method for quickly testing out
new ideas in code. Most of this book is written around this idea of developing
programming skills through sketching. We will also provide some
suggestions for new projects and hardware, new languages to try out, and
ways to contribute back to the community. This book intentionally does not
dwell too long on electronics theory, circuit design, hacking, or other
specifically hardware-based practices, although we’ll revisit the hardware
side of things in our last chapter to provide a small foundation for physical
computing. This book in many ways picks up where the Arduino
Programming Notebook left off, with even more in-depth discussions about
the Arduino environment; simple, no-frills code samples; and clear, easy-to-
read schematics and illustrations.The Notebook, a little PDF booklet, was my
first experience writing about the Arduino and was never meant to be more
than a brief guide for my students when I first introduced a class of 15
college art and design majors to the Arduino in 2007. Best laid plans and all,
this little booklet has now been translated into Spanish, Russian, and Dutch
(that I know of), is hosted in so many different places that it is impossible to
keep track of, and it’s been used in workshops and classes around the world. I
haven't updated the Notebook over the last few years, and in all honesty I am
not entirely sure what to do with it now, so hopefully this new book will fill a
void and find a similar, widespread adoption that the little booklet has
enjoyed all these years.
Both beginners and experts have access to a wealth of free resources and
materials to support them. Users can look up information on how to set up
their board or even how to code on Arduino. The open source behind
Arduino has made it particularly friendly to new and experienced users.
There are thousands of Arduino code examples available online. In this book,
We will explain all the basic principles that a novice programmer needs to
enter the genius world, Arduino
Arduino Coding Environment and basic tools
Arduino IDE
The Arduino Integrated Development Environment (IDE) is the
main text editing program used for Arduino programming. It is
where you’ll be typing up your code before uploading it to the
board you want to program. Arduino code is referred to as
sketches.
Modulus%
Calculates the rest by dividing two numbers by each other.
Laboratories *
Calculates the product of multiplying two numbers together.
OPERATION +
Calculates the result of adding two numbers together.
-
Calculates the result of subtracting two numbers from one another.
Labs /
Calculates the result of dividing two numbers by one.
Parameter =
The attribution coefficient tells the controller to evaluate the expression or
value on the right side of the coefficient = whatever and store it in the
variable on the left side of that coefficient.
Budget transactions in Arduino
Parameter! =
Balance two values or two variables and return the true value if they are not
equal.
Parameter <
Balance two values or two variables and return the true value if the
coefficient on the left side is completely smaller than the coefficient on the
right side.
Parameter <=
Balances two or two values and returns true if the coefficient on the left side
is smaller than or equal to the coefficient on the right side.
Parameter ==
Balance two or two variables and returns true if the coefficient on the left side
is equal to the coefficient on the right side.
Parameter>
Balance two values or two variables and return the true value if the
coefficient on the left side is exactly larger than the coefficient on the right
side.
Parameter> =
Balance two or two values and returns true if the coefficient on the left side
is greater than or equal to the coefficient on the right side.
Boolean transactions in Arduino
!
The logical reflects the value or logical expression that precedes it by
applying the NOT logical operation to it;
&&
Applies the AND logical operation to two logical values or expressions and
returns the resulting logical value
||
Applies the logical OR operation to two logical values or expressions and
returns the resulting logical value
Index access transactions in Arduino
Pointer Access Operators (Pointer Access Operators) are transactions that are
used with cursors to provide cursor access to and references to variable
memory addresses, and variables to access values contained in memory
addresses referenced by cursors.
&
It is used to provide a reference to the referencing memory address of a
variable. A reference is an important feature used with pointers.
*
It is used to provide access to a value stored in a specific memory address
(Dereferencing) of an indicator. Access to data stored in memory addresses is
an important feature used with pointers.
Binary number coefficients in Arduino
Bitwise Operators performs all logical operations and offsets on number bits
and binary values and returns the resulting value.
&
In C ++, the AND operation is performed on each of the two corresponding
bits of the given numbers independently and gives the resulting numerical
value.
>>
The bits to its left to the left displace a specified number of digits equal to the
value to the right.
<<
The bits to the left of it to the right displace a specified number of digits equal
to the value on the right.
^
In C ++, the XOR operation is performed on each of the two corresponding
bits of the given numbers independently and gives the resulting numerical
value.
|
In C ++, the OR operates on each of the two corresponding bits of the two
given numbers independently and gives the resulting numerical value.
~
In C ++, the NOT operation is performed on each of the given bits
independently - unlike the & & coefficient | - and gives the resulting
numerical value.
Compound transactions in Arduino
Parameter = &
Usually used with a constant variable to zero a specific bit value (ie make a
value of 0 or LOW).
Modulus = *
It is a shorthand for multiplying the current value of one variable by a
constant or another variable and then storing the result in the same variable.
OPERATION ++
Increases the value of the variable used by 1.
Parameter = +
A shorthand is the process of combining the current value of a variable with a
constant or another variable and then storing the result in the same variable.
-
Decreases the value of the variable used by 1.
Modulus = -
A shorthand for a constant or another variable is subtracted from the current
value of a variable and the result is stored in the variable itself.
Modulus = /
A shorthand is a process of dividing the current value of one variable by a
constant or another variable and then storing the result in the same variable.
Modulus = ^
Usually used with a constant variable to invert (reverse) a specific bit value.
Parameter = |
It is usually used with a variable of constant to set a specific bit value (set to
1 or HIGH).
Chapter II
Data types
The String object in the Arduino
The String () function creates a copy of the String class. There are several
ways to create text strings of different types of data: call the String () function
with:
Static text string of characters within double quotation marks (i.e. an array of
characters), or
A single constant character within single quotation marks, or
Another copy of the String object, or
Integer constant or long constant number, or
A fixed integer or long fixed number using a specified base, or
Integer or long variable number, or
Integer or long number variable using a specified base, or
A decimal or a double decimal number using specified decimal places.
If you call the String () function with a number, it creates a text string
containing a representation of that number's numbers via ASCII characters.
The default basis used in this case is 10. The following example would be
given:
Which will give the text string "1101" which is the binary representation of
the decimal value of 13.
General structure
String (val)
String (val, base)
String (val, decimalPlaces)
Transactions
val
The variable or value to be formatted as a text string. The allowed data type
are: text string, typeface, byte, integer, pointless integer, long pointless
number, decimal number, and multiplier decimal.
base
Optional coefficient determines the basis of the numerical system in which
the numerical value will be formatted. The default value is: DEC.
decimalPlaces
Restricts the number of decimal places (numbers after the comma) to the
decimal or multiple of the decimal.
Returned values
A copy of the String class containing the value val is returned.
Examples
All of the following are valid examples of using the String () function:
String stringOne = "Hello String"; // Use a fixed text string
String stringOne = String ('a'); // Converts a fixed typeface to a text string
String stringTwo = String ("This is a string"); // String Converts a static text
string to an object of type
String stringOne = String (stringTwo + "with more"); // Combine two text
strings together
String stringOne = String (13); // Use a constant integer
String stringOne = String (analogRead (0), DEC); // Using an integer
specifying the basis used
String stringOne = String (45, HEX); // "Use integer with base set to" hex
String stringOne = String (255, BIN); // "Use an integer with the baseline set
to" binary
String stringOne = String (millis (), DEC); // Use a long number and specify
the basis used
String stringOne = String (5.698, 3); // Use a decimal number and specify the
number of decimal places
Minions
charAt ()
The function fetches a character with a specific index from the text string that
is called with it.
compareTo ()
The function balances two text strings and determines which is greater than
the other or if they are equal.
concat ()
The function adds the parameter passed to it to the text string that is called
with it.
c_str ()
The function converts the content of the text string with which it is called to
the ideal text string style in C (the text string ending in null).
endsWith ()
The function verifies whether the text string called with it ends with the same
characters that were passed to it.
equals ()
The function verifies if the text string you are calling is equal to the text
string you passed to.
equalsIgnoreCase ()
The function verifies if the string you are calling is equal to the string you
passed to, not taking into account the case.
getBytes ()
The function fetches a specified number of bytes of the text string that is
called with it and places it in a specific repository.
indexOf ()
The child index returns the first appearance of a particular character or text
string within the text string that is called with it.
lastIndexOf ()
The child index returns the last appearance of a particular character or text
string within the text string that was called with it.
length ()
The function returns the number of characters of the string that is called with
it.
remove ()
The function deletes a specified number of characters of the text string with
which it is called.
replace ()
The child substitutes a typeface or substring where a specific typeface or
substring exists in the string that is called with it.
reserve ()
The slave reserves part of the memory and allocates it to manipulate and
modify the text string that is called with it.
setCharAt ()
The function assigns the value of a character that is positioned in the text
string with which it is called.
startsWith ()
The function verifies whether the text string called with it begins with the
same characters that were passed to it.
substring ()
The child fetches a specific part of the text string that is called with it.
toCharArray ()
The function converts the whole or part of the text string that is called with it
into a string of characters.
toInt ()
The function converts the text string with which it is called into an integer.
toFloat ()
The function converts the text string with which it is called to a decimal.
toLowerCase ()
The function converts all the characters of the text string with which it is
called into lower-case letters.
toUpperCase ()
The function converts all the characters of the text string with which it is
called to upper-case.
trim ()
The function removes all white spaces from the beginning and end of the text
string called with it.
Transactions
[]
The operator provides access to and returns a specific character of the string
used.
+
The operator combines (merges) two text strings together into one new text
string and then returns them.
=+
The operand adds any type of data to the end of a particular text string.
==
The coefficient verifies that two text strings are equal to each other.
<
The operand checks if the text string to the left is exactly larger than the text
string to the right.
=<
The operand checks if the text string to the left is greater than or equal to the
text string to the right.
>
The operand checks if the text string on the left is smaller than the text string
on the right.
=>
The operand checks if the text string to the left is less than or equal to the text
string to the right.
=!
The parameter checks if the text string on the left is different from the text
string to the right.
Arrays in Arduino
Create an array
For this reason, you should be careful not to make this error when accessing
any element of an array. Accessing an element that falls after the last element
(indexed greater than the size of the array with a value of 1), or generally
outside the array, leads to reading from a portion of memory that is intended
for other purposes. Reading this part does not return valid values or data.
Conversely, writing on a piece of memory outside the reserved portion of an
array, when assigning a value to one of its elements, is bad and more
dangerous than reading that part, as it can lead to disastrous and unexpected
results such as program crashes and downtime. This error may be difficult to
track and refine.
The C language expense does not verify access to arrays defined in the
program, although an access exceeds the limits of one, unlike BASIC or
JAVA, to verify this.
The value of any array element can be fetched by the index of that element as
follows:
x = mySensVals [4];
Arrays are frequently used within loops to modify or fetch the values of their
elements. The loop counter is used as the index of each element of the array.
For example, to print all array elements on a serial interface, you can use
something similar to the following example:
int i;
for (i = 0; i <5, i = i + 1) {
Serial.println (myPins [i]);
}
Type bool in Arduino
The declared bool variable stores one of the following two logical values:
true, or false, by reserving only one byte of memory.
General structure
bool var = val;
Var represents the name of the variable to declare, and val is the value to
assign to this variable, which is either true or false.
Examples
The following example illustrates how to use the bool type to make the light
attached to the leg 5 flash each time the cutter connected to the leg 13 is
pressed:
int LEDpin = 5; // LED light connected to leg 5
int switchPin = 13; // An instantaneous cutter connected to the 13th leg, and
the other leg connected to the ground
void setup ()
{
pinMode (LEDpin, OUTPUT);
pinMode (switchPin, INPUT);
digitalWrite (switchPin, HIGH); // Activating the internal lifting resistance
}
void loop ()
{
if (digitalRead (switchPin) == LOW)
{// Was the cutter pressed? Patches resistance keeps voltage always high
delay (100); // Delay in order to neglect the cutter bounce
running =! running; // Switch the value of the variable
digitalWrite (LEDpin, running); // Indicating the state of the variable through light
}
}
byte in Arduino
General structure
byte var_name;
byte var_name = Number; // 0 - 255
Examples
Example of defining a byte variable:
Note that the numbers after the comma in the second case will be neglected if
the division (or any calculation) result in a decimal.
Type char in Arduino
The char type reserves one byte of memory and stores a typeface value.
Characters are written in single quotes like 'A' (for several characters
[[[Arduino / string | text string]]], use an even quotation mark like 'ABC').
Numbers are stored in the bytes reserved for the char type representing the
value of the corresponding character. These numbers are referred to as
coding, and the coding used here is ASCII coding. Go to the ASCII
Documentation Documentation to see all the characters and the
corresponding numerical value for each. This means that it is possible to
perform some calculations on the characters in which the ASCII value is used
(such as carrying out the operation A '+ 1' which will give the value 66
corresponding to the letter 'B', since the numerical value of the letter 'A' in the
ASCII symbol is 65). Take a look at the Serial.println () function
documentation for more information on how to switch characters and their
numerical value.
Char is a type with a signal; this means that the numerical values it can take
ranges between 128 and 127. If you want one byte without a signal to store
data in it, use the type byte.
General structure
Var represents the name of the variable to declare, and the character
represents the character to be attributed to that variable. The corresponding
character number can be used in ASCII encoding instead of the same
character.
Examples
In Due panels, the size of the double type is 8 bytes (64 bits), which is twice
the float.
General structure
double var;
double var = val;
Var represents the name of the variable to declare, and val represents the
decimal value to assign to this variable.
Examples
An example of defining a double variable:
The type float is used with decimal numbers, which are fractional numbers
that are used as a decimal separator. Decimal numbers are often used to
approximate similar continuous values because they have greater accuracy
than integers. Decimal numbers can be large with the number 38.028235E +
38 and small with the number 38-4282835E +. The float type reserves four
bytes (32 bits) of memory to store a float.
Float decimal numbers have a small precision of 6-7 decimal places after the
comma. In Arduino Uno and other ATMEGA control boards, there is no
higher resolution than this by using double (double float), as the size of this
type is exactly the same as float. In Due panels, the double type provides
double precision.
General structure
float var;
float var = val;
Var represents the name of the variable to declare, and val represents the
decimal value to assign to this variable.
Examples
An example of defining a float variable and performing a calculation on it:
float myfloat;
float sensorCalbrate = 1.117;
int x;
int y;
float z;
x = 1;
y = x / 2; // the value 0, because it cannot store the decimal parts y will
contain the variable
z = (float) x / 2.0; // (the value 0.5) pay attention to the number 2.0 and do
not use 2 only z will contain the variable
Type int in Arduino
Whole numbers are the primary data type used to store numbers.
On Arduino Uno boards (and ATMega based boards), the int type reserves a
16-bit (2-byte) size of memory in which numbers between 32768- (the
smallest value equal to 15 ^ 2) can be stored and 32767 (the largest and equal
value 1 - 15 ^ 2). In Arduino boards and SAMD-based boards (such as
MKR1000 and Zero), the type reserves a 32-bit (4-byte) amount of memory
to store numbers from 2,147,483,648- (31 ^ 2-) to 2,147,483,647 (1-31) ^ 2).
Arduino has the task of dealing with negative numbers, so the calculations
are performed on them transparently and in the expected way. However, there
may be some complexity in dealing with the displacement coefficient <<.
General structure
Var represents the name of the variable to declare, and val represents the
correct numerical value to be assigned to that variable.
Examples
The following example will create a variable called countUp and assign an
initial value to it; this variable will be used as an ascending counter, as its
value will be increased during the loop and will appear on the serial
communication interface:
int countUp = 0; // Declare a variable with integers
void setup () {
Serial.begin (9600); // Configure and start the serial port
}
void loop () {
countUp ++; // countUp Add the value 1 to the variable
Serial.println (countUp); // Print the value of the current variable on the serial port
delay (1000);
}
If the signal variables exceed the maximum or minimum value of the type in
which they are defined, then they will have reached an "overflow" state, and
their value cannot be predicted at that time. Consequently, care must be taken
to make a variable reach the condition of rash (unless this is desirable). One
of the indicators of the variable's arrival to the state of rash is the transfer of
the variable from its maximum value to its minimum value or vice versa.
Note that we said "one of the indicators" and not the only evidence that a rash
occurred, so be careful. If you define a variable and do not intend to use it to
store a negative value in it, then the unsigned int of this type, which is an
unsigned int, should be used to reduce the possibility of reaching the
overflow.
Strings In Arduino
Strings can be represented in two ways. Either the text strings are used as one
of the data types in Arduino which became part of the kernel starting in
version 0019, or a text string can be created from an array of characters with
the null character in the end; the second method will be explained on this
page, as the first method is explained in detail in documentation The string
object provides many functions and tools for manipulating text strings but at
the expense of memory.
General structure
All of the following examples are valid strings for declarations:
This means that any text string must have additional space for an extra
character in addition to the content that you want to store in the string. This is
the reason why Str2 and Str5 need a size of 8, even though the phrase
“arduino” is only 7, because in the last available position the typeface will be
added null automatically. For Str4, its size will be set to 8 characters
automatically, taking the termination character into account. In matrix Str3,
we added the null null of the expression ('0 \') manually.
Note that it is possible that there is a text string that does not have a terminate
character (such as setting Str2 to 7 instead of 8). This will malfunction in
most of the functions dealing with strings, so you should avoid doing this
inadvertently. If you notice that the behavior of the program has become
somewhat strange (especially when dealing with characters and not with
strings), then the termination character is likely to be the cause of the
problem.
In the following example, the presence of the parameter * after defining the
type of data that is char as "* char" indicates that the matrix to be declared is
an array of pointers. Really, all arrays are pointers, so using this parameter *
in this way is important to create an array of arrays. The indicators in C are a
little complicated and not understood by many novice programmers, but it is
enough to understand the indicators only superficially to deal with them in
our case.
Examples
An example of defining an array by using a parameter * and printing the
contents of this array on the serial interface:
char * myStrings [] = {"This is string 1", "This is string 2", "This is string 3",
"This is string 4", "This is string 5", "This is string 6"};
void setup () {
Serial.begin (9600);
}
void loop () {
for (int i = 0; i <6; i ++) {
Serial.println (myStrings [i]);
delay (500);
}
}
Type word in Arduino
General structure
Var represents the name of the variable to declare, and val represents the
value to be attributed to that variable.
Examples
word w = 10000;
The keyword void in Arduino
The keyword void is used with functions defined by the programmer in the
code to indicate that this function is not expected to return any data to
whoever called it after its execution. Based on this definition, the return
keyword is not assumed to be used within the function declared with the
keyword void.
General structure
void function ()
{
// The code block that the code will execute
}
Examples
The following code explains how to use void with the setup () function and
loop () to indicate that they will not return anything after their
implementation is complete:
// But "loop" and "setup" will not be executed for all tasks within the two functions
// Neither of them returns any data back to the higher program that called them
void setup ()
{
// ...
}
void loop ()
{
// ...
}
Chapter III
Constants and variables
Fixed integers are numbers used directly in the code such as 123. By default,
these numbers are treated as integers but can be converted to other types of
numbers using a modifiers such as U or L.
Integers are treated as integers based on the number 10 always (ie represented
by decimal by default). However, other formulas can be used to write
numbers, since the basis of the number will vary.
Decimal system (base 10)
This system is the common counting system among humans that they always
use in calculations. Numbers written in the code that are not preceded by any
coordinator (prefix determining the number formula) are considered as
numbers written in decimal (base 10).
Eight (Basis 8)
The numbers used to represent the values in this system are from 0 to 7. The
values to be written and represented in this system begin with the
coordinator 0 (zero).
n = 0101; // ((1 * 8 ^ 2) + (0 * 8 ^ 1) + 1) == 65 in decimal
A logical error that is difficult to find in the code is likely to result from an
unintentional zero constant; this leads the interpreter to interpret this constant
as a value of eight during code discharge.
'u' or 'U': This switch is used at the end of the numerical constant to convert it
to an unsigned type such as 33u.
'l' or 'L': This switch is used at the end of the numerical constant to convert it
to a 'long number' type such as 100000L.
'ul' or 'UL': The two switches are used together at the end of the numerical
constant to convert it to a 'long number without signal' type such as 32767ul.
Constants in Arduino
Be aware that true and false are lowercase, unlike other constants such as
HIGH, LOW, INPUT, etc.
The voltage applied to the leg is greater than 3.0V on panels with a voltage of
5V, or
The voltage applied to the leg is greater than 2.0V in 3.3V panels.
The man can also be set to an input man by passing the INPUT constant to
the pinMode () function and then typing the HIGH value on it using the
digitalWrite () function. This will activate the internal lifting resistance
associated with that man. Activating this resistance will raise the man's effort
to HIGH unless it is reduced to LOW by connecting it to an external circuit.
This is very similar to what the INPUT_PULLUP constant does when passed
to the pinMode () function, which we will address later.
When a man is set to an output man by passing the OUTPUT constant to the
pinMode () function, and then typing the HIGH value on it using the
digitalWrite () function, that man's effort will be:
5 volts in 5V, or
3.3V in 3.3V panels.
When a man is in this state, then a current can be drawn to light a LED light,
for example by connecting one of its poles to it and connecting the other pole
with resistance on the sequence to the ground pole.
Hard LOW
The meaning of the fixed LOW value also varies depending on the position
of the man; If the man is set to an input man by passing the INPUT value to
the pinMode () function and is read using the digitalRead () function, the
ATmega controller will report the LOW value if:
The voltage applied to the leg is smaller than 1.5V in panels with a voltage of
5V, or
The voltage applied to the leg is smaller than approximately 1.0V in 3.3V
panels.
When a man's position is set to an output man by passing the OUTPUT
constant to the pinMode () function, and then typing the LOW value on it
using the digitalWrite () function, that man's voltage is 0 volts (in both 5V
and 3.3V panels). When the man is in this situation, a current can be
discharged, such as one light pole connected to it and the other pole with
resistance on the sequence with a 5V + (or 3.3V +) pole to light it.
Hard INPUT
The legs of the Arduino board set as input legs using the INPUT constant
with the pinMode () function are said to be in high-impedance state. The legs
set to the INPUT legs make the burdens on the circuit you are examining
very small, equivalent to a 100-ohm sequence resistance in front of the man.
This makes the legs very useful in reading sensor values.
If one of the legs is set as an input man and used to read a switch, the man's
condition will be “floating” when the cutter is open; this will produce
unexpected results. To ensure that the leg condition is read correctly when the
cutter is open, use an external pull-up or pull-down resistance with this leg.
The goal of connecting the resistance to this man is to adjust its effort to a
known state when the cutter is open. A resistance of 10 k أومis usually used,
which is small enough to prevent the input leg from floating, and large
enough to not pull a large amount of current when the cutter is closed. See
this tutorial for more information.
If an external pull-down resistor is used, the input leg voltage will be low
when the cutter is opened, and HIGH when the cutter is closed.
If an external pull-up resistor is used, the input leg voltage will be HIGH
when the cutter is opened, and LOW when the cutter is closed.
Hard OUTPUT
It is said that the legs of the Arduino board set as the output legs by using the
OUTPUT constant with the pinMode () function are in a high-impedance
state. This means that they can provide enough current to other devices and
circuits connected to them. Any man with ATmega legs can give or discharge
other devices and circuits up to 40 mA. Exceeding this value of current
damages the controller, so resistors or similar electronic elements must be
used to determine current when connecting electronic parts that require large
amounts of current such as motors.
Constants defined using the const keyword comply with variable scoping
rules that set the rest of the variables. Taking the risks of define # into
consideration, this makes the keyword const the best way to define constants,
and preferably use them instead of define #.
General structure
The dataType represents the type of variable to be defined, var the name of
the variable, and val the value to be assigned to this constant variable. Note
that once val is assigned to a variable, it can no longer be changed, and the
variable will be read-only.
Examples
Use the word const to define the constant π used in mathematical operations:
const float pi = 3.14;
float x;
// ....
General variables can be seen by all functions in the program. On the other
hand, local variables are only visible in the function within which they are
defined and not available to other functions. In the IDE environment, any
variable declared outside a function (such as setup (), loop (), etc.) is a global
variable.
When a program becomes larger and more complex, local variables are more
useful than general ones to ensure that only one function reaches the
variables defined within them. This prevents errors from one function from
modifying variables that another function inadvertently uses.
It is useful to declare variables and assign them value within iterative loops
such as for. This prevents anything outside the loop from accessing and
modifying this variable.
Examples
int gPWMval; // Any function can see and access this variable
void setup ()
{
// ...
}
void loop ()
{
int i; // loop is only visible within the variable "i" loop
float f; // Only the loop is also visible within the variable "f" loop
// ...
}
The static keyword in Arduino
The static keyword is used when creating visual variables for only one
function in order to preserve its content after the execution of that invoked
function and until the next call to it, unlike the local variables that are created
and destroyed each time the function is called.
The static variables declared within the function will be created and
initialized with the static keyword only the first time that function is called.
General structure
The dataType represents the type of variable to be defined, var the name of
the variable, and val the value to be assigned to this static variable. Be aware
that once the var variable is created when the function is first called, it will
not be destroyed when the function is executed and the value stored within it
will be preserved until the next call to the function.
Examples
The following program generates random steps that are limited to a specific
domain and also limits the size of the steps through the stepsize variable
passed to the randomWalk () function:
/ * RandomWalk
* Paul Badger 2007
* RandomWalk wanders up and down randomly between two
* Endpoints. The maximum move in one loop is governed by
* the parameter "stepsize".
* A static variable is moved up and down a random amount.
* This technique is also known as "pink noise" and "drunken walk".
int thisTime;
int total;
void setup ()
{
Serial.begin (9600);
}
void loop ()
{// randomWalk test function
stepsize = 5;
thisTime = randomWalk (stepsize);
Serial.println (thisTime);
delay (10);
}
return place;
}
The key word volatile, when used to define a variable, is a directive for the
banker itself. The banker is a program that converts the C / C ++ code into an
executable code that the hardware understands; this code contains actual
commands for the controller on the Arduino board telling him what to do.
What the volatile keyword does with the variable is to direct the banker to
load the variable from RAM and not from the flash memory records where all
program variables are stored. In some cases, the value stored in the recorders
for a variable may be inaccurate.
The variable must be defined with the keyword volatile whenever its value
can be changed by anything beyond the control of the code fragment within
which this variable appears (such as simultaneously executing a string). In
Arduino, the only place where this is likely to happen is the district-related
code fragments called the ISR programs.
Volatile or long volatile integers?
If you use the word volatile with a variable that is larger than one byte (2
bytes as an integer, 4 bytes as a long number, etc.), the controller will not be
able to read it in one step because the controller architecture is often 8 bits
(make sure the architecture is Control panel). This means that while the first
eight bits of the variable are read in a part of the code (such as the loop), the
interrupt may have already changed the other eight bits (if the variable size is
16 bits). This will get a random value for the variable.
Examples
Switch the state of the connected foot with LED light when an interrupt
occurs on foot 2:
void setup ()
{
pinMode (pin, OUTPUT);
attachInterrupt (digitalPinToInterrupt (2), blink, CHANGE);
}
void loop ()
{
digitalWrite (pin, state);
}
void blink ()
{
state =! state;
}
Chapter IV
Control structures
Keyword break in Arduino
The break keyword is used to get out of loops for, while, or do ... while
iterative, bypassing the next code and the specified loop conditions and
exiting them. Also used to exit the programmatic switch ... case expression.
General structure
break;
Examples
In the following code, the controller exits the for loop when the measured
sensor value exceeds a certain threshold:
for (x = 0; x <255; x ++)
{
analogWrite (PWMpin, x);
sens = analogRead (sensorPin);
if (sens> threshold) {// Ensure that the measured value does not exceed
the threshold
x = 0;
break;
}
delay (50);
}
Continue keyword in Arduino
The continue key passes the next code in the iteration loop (such as for,
while, or do ... while iterations) to check the conditional expression of that
loop and then the loop loop is resumed normally. Making this statement is
similar to making a jump in the loop to skip execution when a certain
condition is met.
General structure
continue;
Examples
In the following code, the value 0 to 255 will be written on the foot PWMpin
with skipping the values in the range 41 to 119:
The iterative do ... while loop works the same as the while loop except that
the condition is checked at the end of the loop, not at the beginning. This
means that the loop will be executed at least once.
General structure
do
{
// The code block to be executed
} while (condition);
Examples
An example of using the do ... while loop to read a value from a sensor and
waiting for it to reach a certain limit:
do
{
delay (50); // Wait for the sensor value to stabilize
x = readSensors (); // Read the value of the sensor
} while (x <100);
Keyword else in Arduino
The conditional if ... else expression allows more control over the sequence
of validating several specific conditions when executing the code rather than
verifying a single condition when using the if expression. The else statement
(if any) will be executed if the condition given in the if statement is not met.
You can also use the else statement with the if statement as else if to add
another condition to verify, so that several consecutive checks can be
performed at the same time.
If there are several conditions to be verified, it will be met from the first
condition and then from the next condition if it returns false and so on until
one of the conditions is met (ie returns true). When the condition is met, the
associated block will be executed and the program will skip the entire if / else
structure to the next line. If no condition is met, the default else block will be
executed if it eventually occurs.
Note that the else if block may be used with or without the else block at the
end and vice versa. The number of times the use of the else if block in any
conditional expression is unlimited.
General structure
If (Condition 1)
{
// Do the thing a
}
else if (Condition 2)
{
// Do the thing b
}
else
{
// Do the thing c
}
Examples
The following code is part of the temperature sensing system code:
if (temperature> = 70)
{
// Danger! Stop the system
}
else if (temperature> = 60 && temperature <70)
{
// Warning! You must send signals to alert the user
}
else
{
// Safety! Complete the normal tasks
}
The for loop is used to duplicate a specific block of code a specified number
of times. In this loop, a counter is usually used to track the number of times
the code is duplicated and interrupted when a specified number is reached.
The for loop can be used with any iteration, and is frequently used with
arrays to perform a particular operation on elements that may be normal data
or specific legs.
General structure
for (step; condition; initial configuration) {
// code block to be replicated;
}
Examples
void setup ()
{
// This example does not require any configuration
}
void loop ()
{
for (int i = 0; i <= 255; i ++) {
analogWrite (PWMpin, i);
delay (10);
}
}
The for loop in C is more flexible than for loops in some languages such as
BASIC. One or all of the three main elements can be removed from the loop,
keeping the semicolon intact. In addition, the initialization, condition, and
step expressions can be any valid C language expressions with unrelated
variables, and can use any of the data types in C, including decimals. Using
these unusual types of expressions with the for loop provides a solution to
some rare software problems.
For example, using the multiplication in the expression step will generate a
logarithmic progression such as:
for (int x = 2; x <100; x = x * 1.5) {
println (x);
}
2,3,4,6,9,13,19,28,42,63,94
Another example of lighting up and gradually turning off LED light with just
one ring:
void loop ()
{
int x = 1;
for (int i = 0; i> -1; i = i + x) {
analogWrite (PWMpin, i);
if (i == 255) x = -1; // Switch the direction of the step when the peak is reached
delay (10);
}
}
Goto keyword in arduino
The keyword goto moves the program to a specific position within the code.
Examples
bailout:
On the other hand, there are situations where the use of the word goto is
useful and greatly simplifies the code. One of these cases is a fork loop
fragmentation or a conditional if block at certain conditions.
Expression if conditional in Arduino
The conditional if expression verifies a given condition and executes the code
block written within it if it is true (ie its value is true).
General structure
if (condition)
{
// The block of code to execute when the condition is met
}
Examples
if (x> 120)
digitalWrite (LEDpin, HIGH);
if (x> 120) {
digitalWrite (LEDpin1, HIGH);
digitalWrite (LEDpin2, HIGH);
}
Notes and warnings
The given terms may require the use of one of the following parameters.
Budget transactions
x == y (y is equal to x)
x! = y (y is not equal to x)
x <y (y is exactly smaller than x)
x> y (y is exactly greater than x)
x <= y (y is smaller or equal to x)
x> = y (y is greater than or equal to x)
Be careful not to use only one equal sign (e.g. if (x = 10)). Equals (such as if
(x == 10)), which in this case is a equilibrium coefficient and checks if the
value of the variable x is equal to or not. The value of the last expression will
be true if the value of the variable x is 10, while the value of the previous
reference expression is always true.
The explanation of how C evaluates the expression if (x = 10) with true is
always that C assigns the value 10 to the variable x (remember that a single
equal sign is an attribution operator and has been used in error). The
conditional if expression then evaluates the value 10 - which becomes the
value of the variable x - as always true because the logical evaluation of any
non-zero number is always true. Consequently, the conditional if (x = 10)
expression will be assessed as verified and the result will be contrary to the
expectations expected at that time. In addition, the variable x will be set to
10, which is also not desirable
Keyword return in Arduino
The return keyword intersects the execution of any function and returns a
value from the function to the one who called it if specified.
General structure
return;
Examples
int checkSensor () {
if (analogRead (0)> 400) {
return 1;
}
else {
return 0;
}
}
The following example shows how to use the return keyword to examine a
portion of the code without resorting to the comment method:
void loop () {
return;
The switch ... case, as in if, verifies a specified value in a way that allows the
programmer to specify several codes, one of which is executed based on that
value. In more detail, the switch ... case balances the value of a variable with
the values specified within it; when the value of that variable matches one of
the values or expressions within it, the block associated with that value or
expression will be executed.
The break keyword is usually used at the end of each state of the switch ...
case to exit it after matching the state and executing the associated block. If
the key break is not used in that case, the switch ... case will continue to
examine the conditions and execute the associated blocks until the break is
reached or at the end.
General structure
switch (var) {
case label1:
// The first code that will be executed when the first case is matched
break;
case label2:
// The second code will be executed when the second case is matched
break;
default:
// The default code that will be executed when no case matches
// This case is optional
}
Transactions
var
The variable to balance its value with multiple values (states). Allowed data
types are: Integer, typeface.
lable1
The first constant that will be balanced with var. Allowed data types are:
Integer, typeface.
lable2
The second constant that will be balanced with var. Allowed data types are:
Integer, typeface.
Examples
An example of using the switch ... case expression to balance a variable value
and execute a code as appropriate:
switch (var) {
case 1:
// Value 1 var Do something when it equals
break;
case 2:
// Value 2 var Do something when it equals
break;
default:
// with any of the previous values var do something if it doesn't match
break;
}
While iterative episode in Arduino
The loop repeats while executing the code block within it continuously and infinitely as long as the
value of the logical condition in parentheses is true (see the general evidence); once the value of the
logical condition becomes false, the loop stops and exits. Any change in the value of the condition must
occur otherwise the loop will never come out, so the value of the variable that is checked within the
logical condition must be increased or decreased, or an external condition such as checking a sensitive
value or the like must be used.
General structure
while (condition) {
// block to be duplicated
}
Transactions
condition
A logical expression whose value is either true or false.
Examples
An example of using the while expression to repeat the execution of a code a certain number of times:
var = 0;
while (var <200) {
// The code written here will be repeated 200 times
var ++;
}
Chapter V
Functions
The digitalRead () function reads the value of a numeric foot that is either
HIGH or LOW.
General structure
digitalRead (pin)
Transactions
pin
A number indicating the digital man whose value is to be read.
Returned values
Returns the HIGH or LOW value representing the numeric pin foot value.
Examples
Set the value of foot 13 to the same value of foot 7 defined as input foot:
int ledPin = 13; // There is a LED light connected to the 13 foot digital
int inPin = 7; // Push button connected to 7 digital foot
int val = 0; // Changer to store the read value
void setup ()
{
pinMode (ledPin, OUTPUT); // 13 digital foot set as the output foot
pinMode (inPin, INPUT); // Set the 7 foot digital as the entered foot
}
void loop ()
{
val = digitalRead (inPin); // Read the income blood
digitalWrite (ledPin, val); // Adjust the light status to the value of the button
}
If you don't connect the foot with anything, the digitalRead () function can
return either HIGH or LOW (this may change randomly).
Similar input feet can also be used as digital feet, then referred to as A0, A1,
etc.
The digitalWrite () function in the Arduino
The digitalWrite () function writes either the HIGH value or the LOW value
on a specific numeric leg.
If you do not configure a man to OUTPUT via the pinMode () function and
connect a LED light with it, the LED light may appear dim when calling
digitalWrite (HIGH) with this guy. Without explicitly configuring the man
via the pinMode () function, digitalWrite () will activate the internal lifting
resistance that will regulate the large current flowing then.
General structure
Transactions
pin
A number indicating the numeric man on which to write the value.
value
The HIGH or LOW value to be written to the pin man.
Returned values
Nothing is returned.
Examples
Set the digital 13 man mode to the output man and then invert its value from
HIGH to LOW and vice versa every one second:
void setup ()
{
pinMode (13, OUTPUT); // 13 digital man set it as a man came out
}
void loop ()
{
digitalWrite (13, HIGH); // HIGH Adjust the value of 13 digital man to
delay (1000); // Waiting for one second to pass
digitalWrite (13, LOW); // LOW Adjust the value of the 13 digital man
to
delay (1000); // Waiting for one second to pass
}
Notes and warnings
Similar input legs can also be used as digital legs, then referred to as A0, A1,
etc.
The pinMode () function in the Arduino
Starting with the Arduino version 1.0.1, it became possible to activate the
internal lifting resistance by using the mode INPUT_PULLUP. In addition,
the INPUT mode automatically disables internal lifting resistors.
General structure
pinMode (pin, mode)
Transactions
pin
A number indicating the digital man to be configured to mode.
mode
The mode that determines the pin's behavior is either INPUT, OUTPUT, or
INPUT_PULLUP. A full explanation of the behavior and functions of digital
legs can be found on this page.
Returned values
Nothing is returned.
Examples
Set the digital 13 man mode to the output man and then invert its value from
HIGH to LOW and vice versa every one second:
void setup ()
{
pinMode (13, OUTPUT); // 13 digital man set it as a man came out
}
void loop ()
{
digitalWrite (13, HIGH); // HIGH Adjust the value of 13 digital man to
delay (1000); // Waiting for one second to pass
digitalWrite (13, LOW); // LOW Adjust the value of the 13 digital man to
delay (1000); // Waiting for one second to pass
}
Notes and warnings
Similar input legs can also be used as digital legs, then referred to as A0, A1,
etc.
Time functions in Arduino
The functions in this section deal with times and times, for example, to create
time delays with a certain value that some tasks require, or to perform a
specific process when a specific time period has passed since the board
started.
The delay () function pauses program execution for a specified period of time
(in milliseconds).
General structure
delay (ms)
Transactions
ms
Returned values
Nothing is returned.
Examples
Use the delay () function to pause the program from working for one second
before reversing the output case connected to LED light:
int ledPin = 13; // LED light connected to the man 13
void setup ()
{
pinMode (ledPin, OUTPUT); // As a man led out ledPin initialize the
man
}
void loop ()
{
digitalWrite (ledPin, HIGH); // turning the light on
delay (1000); // Wait for one second
digitalWrite (ledPin, LOW); // Turn off the light
delay (1000); // Wait for one second
}
Although it is very easy to create a flashing LED light with the delay ()
function and many codes use this function to create time delays required by
some tasks - such as using them to avoid the problem of button bounce when
pressed (button debouncing) - but using the delay () function In the code is
accompanied by a lot of disadvantages. During the execution of the delay
process when calling the function, the sensors' values will not be read, the
calculations will not be performed, and the condition of any man will not be
modified or controlled ... etc., so calling this function will interrupt the rest of
the tasks and operations and stop them for a period of time. Instead, look at
the millis () function and the example below to handle time delays and
control timing effectively. Experienced and knowledgeable programmers
usually avoid using the delay () function to delay events and control their
timing when the delay period exceeds a few tens of milliseconds unless the
written code is very simple.
General structure
delayMicroseconds (us)
Transactions
us
An unsigned int integer represents the time in the microsecond to which the
program is paused.
Returned values
Nothing is returned.
Examples
The following code prepares the 8th man to act as an outgoing man. The man
then transmits a series of pulses of approximately 100 microseconds in
length. You should focus on the word "almost" because the time is absolutely
inaccurate and this is due to the loss of some time in the implementation of
other commands and instructions in the code:
void setup ()
{
pinMode (outPin, OUTPUT); // As a man came out outPin create the man
}
void loop ()
{
digitalWrite (outPin, HIGH); // Make the man's condition high
delayMicroseconds (50); // Pause for 50 microseconds
digitalWrite (outPin, LOW); // Make the man's condition low
delayMicroseconds (50); // Pause for 50 microseconds
}
The micros () function returns the Arduino board runtime of the current
program in microseconds.
The value calculated by this function will reach the state of rash (i.e. it will
return to zero) after about 70 minutes have passed. On Arduino 16MHz
boards (such as Duemilanove, and Nano), the accuracy of this function is 4
microseconds (that is, the value that the function returns is always a multiple
of 4). On Arduino boards running at 8 MHz (such as LilyPad), the accuracy
of this function is 8 microseconds.
General structure
time = micros ()
Returned values
Returns an unsigned long number representing the startup time of the current
program's Arduino board to the moment the micros () function is called.
Examples
Use the micros () function to find out how long the Arduino board started:
unsigned long time;
void setup () {
Serial.begin (9600);
}
void loop () {
Serial.print ("Time:");
time = micros ();
The millis () function returns the Arduino board runtime for the current
program in milliseconds.
The value that this function calculates will reach the overflow state (i.e., it
will return to zero) after approximately 50 days.
General structure
time = millis ()
Returned values
An unsigned long number representing the start time of the current program's
Arduino board is returned to the moment the millis () function is called in
milliseconds.
Examples
Use the millis () function to find out since when the Arduino board started
working:
unsigned long time;
void setup () {
Serial.begin (9600);
}
void loop () {
Serial.print ("Time:");
time = millis ();
Please note that the type of value returned by the millis () function is an
unsigned long number, so logical errors may occur if the programmer tries to
perform math operations with smaller types of numbers, such as int. Even
calculations with a signed long number can result in errors because its
maximum capacity is half that of the corresponding non-reference number.
Mathematical Functions in Arduino
() Abs
The abs () function calculates the absolute value of the number passed to it.
Constrain ()
The constrain () function limits a number within a specified field.
() Cos
The cos () function calculates the angle passed to it.
() Map
The map () function repositiones a number from the domain in which it is to
another domain.
() Max
The max () function returns the largest value passed to it.
() Min
Min () returns the smallest value passed to it.
() Pow
The pow () function calculates the value yx, that is, raises the base y to the
power x of the two values that are passed to it.
Random ()
The random () function generates and returns a pseudo-random number.
() Randomseed
The randomSeed () function creates the seed that the pseudo-random
numbers generator uses in the generation process.
() Sin
The sin () function calculates the sine of the angle passed to.
() Sq
The sq () function calculates the number of squared (multiplied by the
number itself) and returns it.
Sqrt ()
The sqrt () function calculates the square root of the number passed to it.
() Tan
The tan () function calculates the tangent of the angle passed to.
Handling and verifying typefaces in Arduino
isAlpha ()
The isAlpha () function checks if the passed character is an alphabetical
character.
isAlphaNumeric ()
The isAlphaNumeric () function checks if the character passed to it is an
alphabetical character or a number.
isAscii ()
The isAscii () function checks if the character passed to it is one of the Ascii
characters.
isControl ()
The isControl () function checks if the passed character is a control character.
isDigit ()
The isDigit () function checks if the passed character is a number.
isGraph ()
The isGraph () function checks to see if the typeface passed to it is printable
and contains some visible content (the blank is printable but does not have
visual content).
isHexadecimalDigit ()
IsHexadecimalDigit () verifies if the character passed is a hexadecimal digit
(hexadecimal digit); that is, it is between A-F or 9-0.
isLowerCase ()
The isLowerCase () function checks if the character passed to it is passed a
lower case alphabetical character.
isPrintable ()
IsPrintable () checks to see if the passed character is printable (i.e. one of the
characters that produces any output even if it is blank).
isPunct ()
The isPunct () function checks if the typeface passed to it is a punctuation
mark (i.e. is the typeface comma, semicolon, exclamation mark, etc.)?
isSpace ()
The isSpace () function checks if the character passed to it is a space.
isUpperCase ()
The isUpperCase () function checks if the character passed to it is a lower
case alphabetical character.
isWhitespace ()
The isWhitespace () function checks if the character passed to it is a white
space.
Arduino conversion functions
byte ()
The byte () function converts the value passed to it byte type.
char ()
The char () function converts the passed value to the char type.
float ()
The float () function converts the value passed to it (float).
int ()
The int () function converts the passed value to the integer type.
long ()
The long () function converts the value passed to the type “long”.
word ()
The word () function converts the passed value to the word type.
Provincial control functions in Arduino
Attachinterrupt ()
The attachInterrupt () function activates a specific external interrupt on one of
the legs in the arduino board.
() Detachinterrupt
The detachInterrupt () function disables a specific external interruption
associated with one of the legs of the Arduino board.
() Interrupts
The interrupts () function deactivates interrupts after stopping it by calling the
nointerrupts () function.
() Nointerrupts
The noInterrupts () function disables all interrupts in the Arduino board.
Chapter VI
Additional tools
The keyword programm in Arduino
The keyword PROGMEM is used with variables when its data is to be stored
in program memory (flash memory) rather than in SRAM. For more
information about the types of memory available in Arduino, see this page.
General structure
DataType represents any type of data, and variableName is the name of the
array of data to be stored in flash memory. Be aware that since the key word
PROGMEM is constrained to a variable, there is no rule that requires it to be
in a specific place while declaring a variable; However, some tests have
suggested that PROGMEM, in different versions of Arduino (which uses the
Gulf banker), may work in a specific location only when declaring a variable.
The second example is tried in the examples section in the Arduino 13
version; the example might work better in earlier versions if PROGMEM is
placed after the variable name.
Examples
The following code shows how to write data to flash memory and then read it
again:
// Memorize some integerless numbers
const PROGMEM uint16_t charSet [] = {65000, 32796, 16843, 10, 11234};
void setup () {
Serial.begin (9600);
while (! Serial); // Waiting for serial port connection
Serial.println ();
}
void loop () {
// Write here your program to execute it frequently
}
When working with a large amount of text, such as having a project on the
LCD, it is a good idea to create and configure an array of text strings to store
them. Since text strings themselves are arrays, a 2D matrix must be used. The
following example illustrates the idea of placing large data in program
memory:
/*
PROGMEM string demo
How to store a table of strings in program memory (flash),
and retrieve them.
char buffer [30]; // Make sure that this matrix is large enough to
accommodate the largest text string
void setup ()
{
Serial.begin (9600);
while (! Serial); // Wait for the serial port to connect
Serial.println ("OK");
}
void loop ()
{
/ * Requires the use of a strings table in memory
Use special functions to retrieve data
A text string from the strcpy_P program memory copies the function
(In our case buffer is the variable memory)
Big enough RAM Make sure that the portion is reserved in memory
To recover data from program memory
*/
The following example will not work when placed into a variable:
const char long_str [] PROGMEM = "Hi, I would like to tell you a bit about
myself. \ n";
const static char long_str [] PROGMEM = "Hi, I would like to tell you a bit
about myself. \ n"
Extended call F ()
The text string to be printed normally stored in RAM. If your code prints a lot
of scripts on the serial port, it will fill memory. If you have flash space, you
can easily invest it by storing these texts in it by using the following formula:
Chapter VII
Proteus
In this chapter, we will carry out the first experiment, which is lighting and
extinguishing the LED repeatedly. To ensure that all concepts and steps are
linked to each other, we will explain all the steps starting from how to create
a project on Proteus to extracting a Hex file that will be used to program
Arduino in addition to running the experiment and observing the results.
Also, the step-by-step explanation will be covered.
2. Type the project name and filing location, then click Next.
3. Choose Create schematic from templates, then choose template (default).
. Choose do not create pcb as shown then choose Next.
6. This is the project summary, we will create only schematic. After pressing
Finish we will be ready to place the devices and connect them together.
Arduino UNO
220 ohm resistance
RED LED
The following steps explain how to choose the UNO and place it on the list of
devices that will be used in the design. In the same way, choose RED LED
and 220ohm resistance.
9. The following example shows how to place the Arduino on the schematic
space. In the same way, follow the following steps and put the resistance and
the LED.
10. After placing all the devices on the asmatic and connecting the ends, we
will have the following shape.
. What is missing now until the circle is complete? There is no doubt that it is
the Ground. To choose the Ground, follow the steps illustrated below. Thus,
we have completed the connection settings for the circuit on the protein
program.
Note:
Arduino board does not need to be connected to the power or even ground,
because Proteus does this process implicitly for you.
1. Open the Arduino program, open a new project, write the following code,
then save the project with the name E1_LED_Blinking
void loop () {
// put your main code here, to run repeatedly:
digitalWrite (LED_Pin, HIGH);
delay (1000);
digitalWrite (LED_Pin, LOW);
delay (1000);
}
Code explanation:
The code begins by announcing the variables that are used within more than
one scope of the program. The "Scope" is the term enclosed in parentheses of
type {}. So we started by announcing the LED_Pin variable which was used
inside the setup and loop. The const command is used to ensure the value of
the variable is not changed again, and since the LED_Pin variable retains the
value of the port number, it must not be changed again. We note that the
value 13 has been assigned to the LED_Pin variable, because we have
connected the LED to port number 13. Inside the setup, the port type (port)
will be defined if it is output or input via the PinMode function. Inside the
loop, the code that is repeated continuously will be written non-stop. The
code inside the loop starts with the line (digitalWrite (LED_Pin, HIGH),
which means output 5 volts to the port called LED_Pin, after that we notice
the delay (1000) line, which means that the code will remain the same for a
period of 1 second, then we notice the presence of the line (digitalWrite)
LED_Pin, LOW through which 5 volts will be prevented from passing to port
13 and to ensure the continuity of the LED stops lighting for a period of 1
second had to put (delay) 1000 at the end of the loop also. If through the code
inside the loop it will light LED for one second and it will turn off for one
second and so it will continue without stopping.
2. Make a verification of the code by pressing the button shown in the figure
to make sure that the code does not contain any errors.
3. If the code is correct, you will see a message similar to the following
message under the Arduino program.
4. After making sure that the code is free from any errors, go to the sketch
menu and choose Export compiled Binary. This is to extract the hex file.
Which is used to program the microcontrollers.
. Going to the folder in which the project was saved, you will find a .hx file.
With the same name as the project.
6. Return to the circle in Proteus, press Arduino to add the script file as
shown in the following steps.
7. Turn on the circuit and notice how the LED lights up and then turns off
repeatedly.
8. Try to change the delay time to 500 instead of 1000, perform steps 2
through 7, and note the difference.
Debate
Suppose you write the code in the following image and ignore the delay delay
after the digitalWrite (LED_Pin, LOW). What do you expect to happen in
this case?
void setup () {
// put your setup code here, to run once:
pinMode (LED_Pin, OUTPUT);
}
void loop () {
// put your main code here, to run repeatedly:
digitalWrite (LED_Pin, HIGH);
delay (1000);
digitalWrite (LED_Pin, LOW);
}
So let us do the implementation process, we will start from the loop and then
we will put 5 volts on the port called LED_Pin which is originally port
number 13. Then we will go to the second line to implement it and we find
delay by 1000 and since the delay function deals with the values in
milliseconds then this This means that the delay will continue for a period of
1 second, and this delay will remain on the last state the micro was on, so the
LED will be lit for a period of 1 second, that is, until the delay command
ends. Now we are going to execute the third line which contains the
command (digitalWrite (LED_Pin, LOW) in which the LED will be turned
off. Well the LED has turned off now but then what? Focus on me well here
we are inside the loop function and therefore the code will start executing
again from the first A line inside the loop in which the command that will
output 5 volts to the LED and it will illuminate again! Here lies the problem
where the last line will be executed and immediately after it the first line will
be executed and on it the eye will not be able to notice that the LED has gone
out because the implementation of the code is calculated in microseconds for
that The delay had to be put after the command that required the LED to be
turned off.
Chapter VIII
In this lesson we will control four LED lights, each lamp will be controlled
by push button. What we will learn here is how to put the ports connected
with the LEDs in one variable is an Array, and the same for the switches will
also be placed in one array. In this way the code will be shorthand and more
professional. The lesson also discusses how to use the for loops to access the
elements of an array and the values saved in them. Also, it will explain how
to execute an order based on the fulfillment of a specific condition.
Open Proteus and design the circle as shown in the following figure
Explanation of the circuit
Four push buttons were connected with the Arduino ports from port number 1 to port number 4, the
ports were set to internally contain a pull-up resistance so there would be no need to connect resistors
or voltage sources with the push buttons and therefore it will work through the inverse logic When a
specific button is pressed, that port will read the logic LOW, and when a button is not pressed, that port
will read the logic HIGH and this is what should be considered in the code (you can review Lesson Six,
there is a complete experiment to understand this method). For LEDs, they are connected to ports 9
through 12 via a resistance of 220 ohms used to reduce current. In the code we will make each button
illuminate only one LED.
Write the following code on the Arduino program then extract the Hex file and program the Arduino as
described in Lesson 4.
int pushButtons [4] = {1,2,3,4};
int ledPins [4] = {9,10,11,12};
void setup () {
// put your setup code here, to run once:
for (int i = 0; i <4; i ++)
{
pinMode (pushButtons [i], INPUT);
pinMode (ledPins [i], OUTPUT);
digitalWrite (pushButtons [i], HIGH); // activate pullup resistor
}
}
void loop () {
// put your main code here, to run repeatedly:
for (int i = 0; i <4; i ++)
{
int val = digitalRead (pushButtons [i]);
if (val == 0)
digitalWrite (ledPins [i], HIGH);
else
digitalWrite (ledPins [i], LOW);
}
}
Code explanation
The code begins with defining global variables that will work within the setup and loop fields. We
defined two matrices of the integer type, each matrix consists of four elements. In the first matrix,
which is called pushButtons, the port numbers connected with the pushButtons are assigned, and they
are ports 1 through 4. Likewise, for the second matrix, which is called ledPins, the port numbers
connected to the LEDs were placed inside The array, which is ports 9 through 12. We have to note that
after the name of the array, the number of elements of the array is enclosed in parentheses such as [4].
As for the code inside the setup area, as we previously learned, it is often used to set the position of
ports so that they are either in the input or output state. But before explaining the code in the setup
field, we will first discuss some of the basic concepts related to matrices.
The numbering of the elements inside the matrices begins with the number 0, for example the first
element in the ledPins array is [0] ledPins which contains the value 9 and from this we conclude that
the second element in the array is element number 1 and so on. So [0] ledPins is a variable that contains
the value 9, and if we call it at any time, it means that we called the value inside of it which is 9 unless
it is changed. Since port number 9 is connected to an LED, it must be set to function as an output port,
the following code explains this step:
Notice that the number 0 is inside the ledPins matrix, which indicates element zero, which has a value
of 9. Now we want to set all ports from 9 through 12 in order to work as output ports because they are
connected with LEDs. We can do this through the following code inside the setup function.
void setup () {
pinMode (ledPins [0], OUTPUT);
pinMode (ledPins [1], OUTPUT);
pinMode (ledPins [2], OUTPUT);
pinMode (ledPins [3], OUTPUT);
}
In the above code we have called the pinMode function on each line to set the ports to work either in
the case of the output or the input, the input (Arguments) that will be passed to the function is the port
number and the state that must work on it (input / output), and since we deal with the connected ports
With LEDs, the status will always be the output. As for port numbers, they were previously defined
inside the ledPins array, so on each line the name of the array along with the element number will be
placed inside the pinMode function. This code is true one hundred percent, but it lacks professionalism
and explains that its writer is a little weak with programming, but why? Imagine if the number of ports
inside the array is 10, this means that we will write 10 lines to define the port type to act as the output
port. But what is the professional way? It is best to use iterative loops to shrink the code and make it
more professional and flexible. We will be using the for loop as shown in the following code.
In the above code, we used the for loop and inside the definition of for, we defined the variable i, which
is of the integer type, and we assigned the initial value to it 0 because the first element in the array
starts with zero. Now let's implement for loop together. In the first cycle, the value of i will be equal to
0. This value will be compensated inside the code inside the for loop field, so the code will be as
follows (pinMode (ledPins [0], OUTPUT), after executing all the code inside the field of for loop The
for will implement the partial code that will affect the value of i and in this code is ++ i, which means
that the variable i will become its value equal to one, now the for will test the condition i <4 and
certainly the condition will be met because the value of i now is one and it is actually less Of 4. And
since the condition is met, we can now execute what is inside the for loop, and this time do not forget
that the value of i has become one, so the variable will be compensated To enter pin to become the
pinMode (ledPins [1], OUTPUT code, and by executing port number ten, it will be set in the output
state. the work.
In the same way, we can set the matrix of the input ports that extend from port number 1 to 4, and the
code for them can be added to the for loop inside the tuning of the output ports. It is very important to
note that port numbers 1 through 4 are numbers inside the array while the array itself starts from
element 0 and will end with element 3 because it has four elements.
void setup () {
for (int i = 0; i <4; i ++)
{
pinMode (pushButtons [i], INPUT);
pinMode (ledPins [i], OUTPUT);
}
}
Finally, we will add a partial code that will make the input ports linked to the internal pull up resistance
to the iterative loop where it will operate with the same previous concept.
void setup () {
for (int i = 0; i <4; i ++)
{
pinMode (pushButtons [i], INPUT);
pinMode (ledPins [i], OUTPUT);
digitalWrite (pushButtons [i], HIGH); // activate pullup resistor
}
}
So far we have finished the code for setting the port mode, but what about the code inside the loop
function? As you know, the code in the loop is the code responsible for implementing the basic idea.
The code inside the loop function is a code that is executed continuously to infinity. When you reach
the last line of the function, the function starts to work again starting from the first line. It is worth
noting here that the microcontroller on the Arduino Uno board is ATMEGA328P connected to a clock
source operating at 16 MHz and almost the microcontroller performs one operation per clock pulse, that
is, we can say that the microcontroller can implement 16 million instructions per second! I deliberately
mentioned this information now because the code in the loop in this lesson depends on this feature and
you will not be able to understand it until you feel the speed with which the microcontroller works.
void loop () {
// put your main code here, to run repeatedly:
for (int i = 0; i <4; i ++)
{
int val = digitalRead (pushButtons [i]);
if (val == 0)
digitalWrite (ledPins [i], HIGH);
else
digitalWrite (ledPins [i], LOW);
}
}
The code starts with a for loop that runs from 0 to 3, you will start by placing the value 0 in the variable
i and the code inside the loop will be executed. In the first line inside the loop, we defined the variable
val of the integer type, in which the value in port 1 will be read, i.e. [push button [0], if the push button
is pressed, the digitalRead function will read the value 0 and in the opposite case it will read the value 1
then this will be put The value in the variable val. Then the microcontroller will implement the if else
condition function and will test the condition if the val variable contains the value 0 or LOW then if the
condition is met the value of HIGH will be placed on the port associated with the variable [ledPins [0
and if the condition is not met the value LOW will be placed on the port associated with the variable [
ledPins [0 So we ran the first iterative loop in which the value of the variable i was equal to zero. The
function will continue to work and each time you increase the value of i by one and then execute the
code with the new value of i until it becomes i equal to 3, the code is executed based on this value and
then the value of i returns again to 0.
Now suppose that you have implemented the code and loaded it into the Arduino and then pressed the
button connected to port number 3 located in [pushbutton [2. Actually, the code in the loop function
will test all pushbuttons from [pushbutton [0 to reach [pushbutton] 3 but this will be done very quickly
and each time when it passes the test of the condition related to [pushbutton [2] which will light the
LED connected to port number 11.