Professional Documents
Culture Documents
By
Ben C. Philips
TABLE OF CONTENTS
Introduction To Arduino
Arduino Arithmetic Operators
Arduino Loops
Arduino Functions
Time library in Arduino
Arduino Control Statements
Understanding Arrays in Arduino
How To Use Strings In Arduino
Arduino Project Sample
Conclusion
INTRODUCTION TO ARDUINO
A rduino is an open source prototyping platform built on easy-to-use
hardware and software. Arduino boards are able to read inputs - a light on a
sensor, a finger on a button, or a Twitter message - and turn it into an output
- activate the motor, turn on an LED, and post something online. You can
tell your board what to do by sending a set of instructions to the onboard
microcontroller. To do this, it uses the Arduino programming language
(based on Wiring), and the Arduino software (IDE), based on the
processing.
The Arduino board itself is a blue circuit board, the size of a credit card
(but also has other sized models). It contains two rows of connectors
("headers"), a power connector, and a USB connector. The mind board is
an Atmel microcontroller. It's like a very small, very low power
"computer". (It has only 32 KB of storage, 2 KB RAM, and the 8-bit
processor only runs at 16MHz.) However, for most applications, this is
more than enough. Processor pins attach to headers, and you can connect to
almost anything you can imagine. You just need to write some lines of code
to control it. The input / output (input / output) pins can be used as input
pins, for connecting buttons or knobs, temperature sensors, light sensors, or
even keyboards and mice, digital musical instruments ... or they can be used
as output pins, for connecting lamps, motors Disks, control the lights in
your home, connect to small screens or even connect to the internet, so you
can check your mail, post tweets ... through a USB connection, you can also
use it to control your computer, or use your computer to control In
Arduino.
Arduino Uno
Arduino Leonardo
Arduino Due
Arduino Yún
Arduino Tre
Arduino Micro
Arduino Robot
Arduino Esplora
Arduino Mega
Arduino Mini
LilyPad Arduino
Arduino Nano
Arduino Fio
Arduino Pro
Arduino Ethernet
SOFTWARE (IDE)
The software used for programming Arduino is called the Integrated
Development Environment (IDE). IDE is a Java application that works on
many different platforms, including PCs, Macs, and Linux systems. It was
developed for beginners who are not familiar with programming. Includes
a code editor, compiler, and uploader. Symbol libraries for use of
peripheral devices, such as serial ports and various types of displays, are
also included. Arduino programs are called "sketches" and are written in a
language very similar to C or C ++.
USB CABLE
Most Arduinos connect to a host computer via a USB cable. This
connection enables you to upload graphics to your Arduino as well as
provide power to the board.
PROGRAMMING
Programming Arduino is easy: you can use the IDE code editor to write
the program and then compile and load it with one click. The Arduino
software includes two main functions:
Setup ()
Loop ()
You can use the setup function () to configure the panel settings. This
function works only once when the board is powered on. The loop ()
function is executed after setup () has completed, and unlike the setup ()
function, it runs continuously.
PROGRAMMING FUNCTIONS
Here are some of the most used functions in Arduino programming:
ARDUINO LIBRARIES
Arduino libraries are sets of functions that allow you to control devices.
Here are some of the most used libraries:
GPS library
LCD library
Servo library
SD library
Robot_control library
Robot_motor library
Ethernet library
Wi-Fi library
Stepper library
SPI library
EEPROM library
Software Serial library
GSM library
First, install the IDE. You can download the IDE from the
Arduino website.
Install the program on your computer.
Now run the arduino IDE.exe file. It has the following layout:
Write your program using the code editor and upload it to the
Arduino. To do this, you need to connect the Arduino to your
computer using a USB cable.
In the IDE, select the type of Arduino you are using from Tools ->
Boards menu.
Now verify your code by clicking on the "hash" icon at the top of
the IDE window, then click the "right" arrow next to compile the
code and upload it to the Arduino.
Note: You may have to install drivers if your system does not detect the
Arduino.
A rduino shields
Arduino shields are a board that is attached to the Arduino to allow you to
connect peripherals, sensors, and actuators to the Arduino. Here are some
popular shields:
GSM Shield
Ethernet Shield
WiFi Shield
Motor Shield
Proto Shield
Joystick Shield
Bluetooth Shield
Xbee shield
COMPONENTS AND ACCESSORIES
Here is a list of all the components and accessories commonly used with
Arduino for project development:
Breadboard
USB cable
9V Battery
LEDs
Push Buttons
Capacitors
Voltage Regulators
Sensors (IR, temperature etc)
Jumper wires
Resistors
Potentiometer
Motors (DC, Servo, BLDC)
LCD
Hex keypad
Arduino shields
BYTE
1 byte = 8 bits.
It is considered as an unsigned number, which stores values from 0 to 255.
The formula is:
byte var = val;
where,
var = variable
value = the value assigned to the variable
For example,
byte c = 20 ;
WORD
It is considered as an unsigned number of 16 bits or 2 bytes, which stores
values from 0 to 65535.
The formula is:
word var = val;
where,
var = variable
val = The value assigned to the variable
For example,
word c = 2000 ;
ARDUINO ARITHMETIC OPERATORS
B elow, five math factors are described and then all of them are put into a
diagram to show how they work on an Arduino.
ADDITION
To add numbers on the Arduino, we use the addition operator (+).
The example below shows how to add two numbers together.
int a = 2;
int b = 7;
int sum;
sum = a + b;
In the above code, three variables are defined. Both variables A and B are
assigned a value when defined.
The sums variable is defined, but not initialized, so it contains any random
number. We'll use this variable to store the result of calculating the
addition, so the random value in the sum will be overwritten when we place
the result of the addition (or the sum) in it.
After executing the statement shown below, the sum will contain the value
9, that is, the result of adding the variable a and b.
sum = a + b;
We can also add two constant values and store the result in a variable as
shown below.
int sum;
sum = 2 + 10;
The result stored The result stored in the sum after executing the add
statement would be 12 in this example.
Static values and variables can also be added together and the result
stored in a variable as shown here.
int a = 3;
int sum;
sum = a + 24;
After performing the addition, the amount will contain 27.
The remaining arithmetic operators can also operate on constant values,
variables, and a combination of the two.
SUBTRACTION
The subtraction operator subtracts one number from another using the
minus sign (-) as the following example illustrates.
int result;
result = 10 - 2;
The result of this calculation will be 8 and it will be stored in the resulting
variable.
MULTIPLICATION
Multiplication is done using the multiplication operator (*).
int result;
result = 4 * 3;
The calculation result will be above 12 and it will be stored in the result
variable.
DIVSION
The division operator (/) is used to perform division in an Arduino.
int result;
result = 12 / 3;
The result of the above calculation is 4.
ARITHMETIC SKETCH
The following diagram called Computation illustrates all of the arithmetic
factors mentioned above.
Upload the drawing to the Arduino and have a try. Also add the above
examples that are not in the diagram, such as mixing values and static
variables.
void setup () {
int a = 2;
int b = 7;
int result;
float result_fl;
void loop () {
}
COMMENTS ON SKETCH
print () function
The diagram contains a mixture of print () and println () functions. Print
() is called when the invisible cursor must remain on the same line, so the
text printed in the next println () statement will be printed on the same line
as well.
Println () function
Println () is used when text must be printed and then the invisible cursor
moves to the next line so that the following print () statement prints the text
on a new line.
IntegerVariable
The result of the integer variable is reused many times while drawing.
The important thing is to display its result before putting the result of the
next calculation into it.
ARDUINO FOR-LOOP
Arduino for loop is one of the baking and butter functions that you will
use all the time in your code. Microcontrollers are good for repetitive tasks,
but instead of typing the same code multiple times, the for-loop repeats a
section of code a certain number of times.
WHERE ARE FOR-LOOPS USED
You can use for loops anywhere within a function, so you can use them in
the standard Arduino (), loop () setup functions, and in your own functions.
The following example shows a for-loop that is about printing numbers 0
through 9. It's put into the setup () function because you only want to
execute the for-loop action once - otherwise if you put it inside the loop () it
outputs the information repeatedly - which makes you spin (try it and see)!
Copy the code into the Arduino IDE. Compile and run the program. Start
the serial monitor to see the output.
This code shows an example Arduino for loop with the for loop itself
inside the setup () function. This isn't where you should normally use the
for loop (you can) - it's just here to turn off multiple outputs.
void setup ( void ){
Serial . begin ( 9600);
Serial . println ( "Arduino for loop" );
for ( int i = 0; i < 10; i ++) Serial . println ( i );
}
Initialize
Int i = 0;
First of all, the variable "i" is created (if it doesn't already exist) and set to
zero.
This section of the for-loop runs only once at the beginning.
TEST
i < 10;
After that the loop variable is tested. Here, if it's less than 10, go ahead -
otherwise the loop gets out. This is performed every time around the loop.
ITERATOR
i ++;
The loop control variable (ring counter) is increased by one.
This is performed every time around the loop.
ARDUINO FOR-LOOPOUTPUT
So the for-loop runs the code "Serial.print (i)" 10 times with a value of 'i'
going from 0 to 9.
And this is the result:
Arduino for loop
0
1
2
3
4
5
6
7
8
9
For a different way of doing similar work, you can allow the control
variable to change from 1 to 10.
for ( int i = 1; i < =10; i ++) Serial . println ( i );
This will print from 1 to 10. It still has 10 iterations but starts from 1.
Note: Here the value of the letter "i" ranges from 1 to 10. At the end of
Ring "i" it has the value 10 - as before.
Notice how there are two terms - ending with a semicolon and both are
enclosed in square brackets. Compare this to the previous example, which
used only one phrase ending with a semicolon.
In this case the output is:
Arduino for loop
i is : 0
i is : 1
i is : 2
i is : 3
i is : 4
i is : 5
i is : 6
i is : 7
You can create a for loop that counts down by changing all three
parameters in the for loop. Let's say you want to count down from 10 to 1
(ten iterations around the loop).
void setup ( void ){
void loop () {
}
While-Loop Structure
The while loop has a structure like this:
while (loop test expression goes here) {
Statements that run in the loop go here
Statement 1
Statement 2
...
}
The while loop begins with the keyword while followed by a test
expression between the open and close parentheses. The opening and
closing brackets denote the body of the ring.
TEST EXPRESSION
As with the for loop, the while loop contains a test expression that will
determine whether the statements in the loop will work or not. If the test
expression evaluates to true, then loop statements run. If the test expression
evaluates to false, then the loop statements will not run, but the statements
that follow the loop closing parenthesis will run - that is, execution
continues outside and under the loop.
INITIALIZE EXPRESSION
The for loop contains an initialization expression as part of the loop. The
while loop can use any variable from the schema that has a valid value. In
the example diagram, the variable used in loop (i) must be initialized when
defined, otherwise it will contain any random value.
INCREMENT EXPRESSION
The expression increase was used in the for-loop examples in the previous
part of this cycle. In the while loop example, the increment expression is
placed inside the body of the loop.
How does a while-loop example work?
In the example drawing, the following happens:
1. The variable i is initialized to 0 when the diagram is started.
2. The while loop evaluates the test expression (i <10).
3. The test expression is evaluated to true because i is less than 10.
4. Because the test expression is correct, the phrases in the loop are
played.
5. The current value of i is printed and then incremented.
6. Upon reaching the bottom of the loop, execution begins at the top of the
loop again.
7. The test expression is evaluated again, and it is true again, so the loop is
played again.
Only when the variable i is increased to 10 will the loop expression
evaluate to false and the loop will exit.
While-Loop example 2
In the schematic example below, the while loop is used to count up to 25
by five by adding five to a variable each time throughout the loop.
void setup () {
int sum = 0;
// count up to 25 in 5s
while (sum < 25) {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
}
}
void loop () {
}
In this diagram, a variable called sum is defined and initialized to 0. The
test expression in a while loop tests whether the sum contains a value less
than 25.
Within the loop, the sum variable is incremented by 5 each time during
the loop by arithmetic expression:
sum = sum + 5;
This expression means "add 5 to the sum variable."
Then the value held by the sum variable is printed, followed by a delay of
half a second.
Since the variable's value is incremented first and then printed, we see the
value 5 printed first and not the 0 value it was initialized for.
Although the test expression will be evaluated as false when the sum is ==
25, the number 25 remains the last number printed. This is because the last
time a test expression evaluates to TRUE is when the sum is == 20, but the
sum is then increased to 25 and printed out before the test expression is
evaluated again.
// count up to 25 in 5s
do {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
} while (sum < 25);
}
void loop () {
}
All statements run in the body of the loop before the test expression
evaluates.
If the sum is initialized to a value of 25 when specified, as shown in the
diagram below, the loop will run once and 30 will be printed. The loop will
not run again after that because the test expression is evaluated to false.
void setup () {
int sum = 25;
// count up to 25 in 5s
do {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
} while (sum < 25);
}
void loop () {
}
Using the same scheme, but changing a do while loop to a while loop, as
shown below, the statements in the body of the loop will never work. This
is because the test expression is evaluated before the statements in the loop
body are executed. Test expression evaluates instantly to false, so loop
statements will never work.
void setup () {
int sum = 25;
// count up to 25 in 5s
while (sum < 25) {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
}
}
void loop () {
}
In the example above, no output will appear in the serial monitor window
when the diagram is run. The while loop evaluates to false and then the
execution falls directly into the empty main Arduino loop.
ARDUINO FUNCTIONS
T he functions allow the programmer to divide a specific code into different
sections, and each section performs a specific task. Jobs are created to
perform a task multiple times in the program.
A function is a type of procedure that returns the area of code from which
it is called.
The function returns something, or a value called the return value. Return
values can be of several types, some of which are listed here:
Integers
Float
Double
Character
Void
Boolean
Another term, an argument, denotes something that is passed into the
function and is computed or used within the function. In our previous
example, the ingredients that go into our coffee making process can be
called arguments (sugar, milk, etc.), and finally we get the coffee, which is
the return value of the job.
By definition, there are two types of jobs. It is a system defined function
and a user defined function. In our Arduino code, we often saw the
following syntax:
void setup (){
}
void loop (){
}
setup () and loop () are also functions. The return type for these jobs is
void. Don't worry, we'll discuss the job type soon. Setup () and loop () are
system-defined functions. There are a number of functions specified by the
system. User-defined jobs cannot be named after them.
Before we dive into the types of functions, let's get to know the syntax of
a function. The functions could be as follows:
void functionName ()
{
//statements
Or like
void functionName ( arg1, arg2, arg3)
//statements
}
So what's the difference? Well, the first function doesn't have arguments,
but the second function has it.
There are four types of functions, depending on the return type and the
arguments. They are as follows:
//statements
Inside the function, we can do all the things we need. Suppose we want to
print I love Arduino! Ten times if the function is called. Therefore, the
function must have a loop that continues ten times and then stops.
Therefore, our function can be written as follows:
void myFunction (){
int i;
for ( i = 0 ; i
The previous function does not contain a return value. But if we call the
function from our main function (from the setup function (); we might also
call it from the loop function (), unless we don't want an infinite loop), it'll
print the function I love Arduino! Ten times. No matter how many times
we call, it will print ten times per call.
Let's write the complete code and take a look at the output. The complete
code is as follows:
void myFunction (){
int i;
for ( i = 0 ; i
In the code, we have put our (myFunction) function after the loop ()
function. The custom job posting before the prep () loop is good practice.
Inside our setup () function, we called the function, then printed out a few
dots, and finally, we called the function again. You can guess what will
happen. Yes, I love Arduino! It'll print ten times, then a few dots will print,
and finally, I love the Arduino! It will be printed ten times. Let's take a
look at the output on the serial monitor:
int a = 3 , b = 5 , c = 6 , addition;
addition = a + b + c;
return addition;
The previous function should return 14. Let's store the function return
value to another integer type of variable in the setup () function and print it
to the serial screen.
The complete code will be as follows:
void setup (){
}
Now, we should call the function like this: myInitialAndAge (6, 'T'); ,
Where 6 is my age and T is my initial letter. We should not do it as follows:
myInitialAndAge ("T", 6);
We called the function and ran two values through it (12 and 24). We get
the answer where the sum is 36. Isn't that cool? Let's delve a little deeper.
In our job, we declare the two arguments (A and B) as whole numbers.
Within the entire function, the values (12 and 24) that we ran through the
function are as follows:
A = 12 and b = 24;
If we call the function this sumOfTwo (24, 12) then the values of the
variables will be as follows:
A = 24 and b = 12;
Hope you can now understand the sequence of job arguments. How about
the experience? Call sumOfTwo () five times in setup (), with different
values for a and b, and compare the results.
This type of function will have both arguments and a return value. Inside
the function, there will be some operation or arithmetic using arguments,
and after that, there will be a result, which we want as a return. Since this
type of function will return a value, the function must have type. Let's look
at an example.
We will write a function that checks whether the number is prime or not.
From your math class, you might remember that a prime number is a
natural number greater than 1 and has no positive denominators other than 1
and itself.
The basic logic behind checking whether or not a number is prime is to
check all numbers starting from 2 to the number before the number itself by
dividing the number. Not clear? Okay, so let's check if 9 is a prime
number. No, it is not a prime number. why? Because it can be divided by
3. According to the definition, it cannot be divided by any number other
than 1 and the number itself.
Therefore, we will check if the number 9 is divisible by 2. No, it is not the
case. Then we divide by 3 and yes, it's divisible. So 9 is not a prime
number, according to our reasoning. Let's check if 13 is a prime number.
We will check if the number is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 and
12. No, the number is not divisible by any of these numbers. We may also
shorten the verification process by only checking the number that is half of
the number we are verifying. Look at the following code:
int primeChecker ( int n) // n is our number which will be checked
{
int i; // Driver variable for the loop
for ( i = 2 ; i
The code is very simple. If the remainder is equal to zero, then the
number is completely divisible by a number other than 1 and itself, so it is
not a prime number. If there is any remainder, the number is a prime
number. Let's write the code completely and look at the output of the
following numbers:
23
65
235
4543
4241
The complete source code to check whether the numbers are raw or not is
as follows:
void setup (){
Serial. begin ( 9600 );
primeChecker ( 23 ); // We called our function passing our number to test.
primeChecker ( 65 );
primeChecker ( 235 );
primeChecker ( 4543 );
primeChecker ( 4241 );
for ( i = 2 ; i
This is a very simple code. We just called our primeChecker () function
and passed the numbers. Inside our primeChecker () function we wrote the
logic to check the number. Now let's look at the output:
From the result, we can see that, except for 23 and 4, 241, there is no
prime number.
Let's look at an example, where we'll write four functions: add (), sub (),
mul (), and divi (). In these functions, we will pass two numbers and print
the value on the serial screen. The four functions can be defined as follows:
float sum ( float a, float b){
float sum = a + b;
return sum;
}
}
float mul ( float a, float b){
float mul = a * b;
return mul;
}
}
Now write the rest of the code, which will give the following output:
USES OF FUNCTIONS
You might be wondering what kind of job we should be using. The
answer is simple. Functionality uses depend on software operations. But
whatever the job, I suggest doing only one task with the job. Do not
multitask inside the job. This will usually speed up processing time and
symbol computation time.
You may also want to know why we need to use the functions. Well,
there are a number of uses for the functions, as follows:
✓ Functions that help programmers write more structured code
✓ Functions help reduce errors by simplifying code
✓ Functions make the entire code smaller
✓ Functions create an opportunity to use the code multiple times
TIME LIBRARY IN ARDUINO
T ime is a library that provides Arduino timer functions. With Arduino
Library Manager, install "Time by Michael Margolis".
The code is derived from the Playground DateTime library but is being
updated to provide a more flexible and easier-to-use API.
The primary goal was to enable a date and time function that can be used
with a variety of external time sources with the minimum required
differences in drawing logic.
The graphics examples show how similar graphic symbol can be used
with: Real Time Clock, NTP Online Time Service, GPS time data, and
serial time messages from a computer for time synchronization.
FUNCTIONALITY
To use the time library in an Arduino diagram, include TimeLib.h.
# include <TimeLib.h>
The functions available in the library include
hour (); // the hour now (0-23)
minute (); // the minute now (0-59)
second (); // the second now (0-59)
day (); // the day now (1-31)
weekday (); // day of the week (1-7), Sunday is day 1
month (); // the month now (1-12)
year (); // the full four digit year: (2009, 2010 etc)
there are also functions to return the hour in 12-hour format
hourFormat12 (); // the hour now in 12 hour format
isAM (); // returns true if time now is AM
isPM (); // returns true if time now is PM
now (); // returns the current time as seconds since Jan 1 1970
The time and date functions can take an optional time parameter. This
prevents errors if time passes between elements. For example, if you start a
new minute between getting the minute and the second, the values will be
inconsistent. Using the following functionality solves this problem
time_t t = now(); // store the current time in time variable t
hour (t); // returns the hour for the given time t
minute (t); // returns the minute for the given time t
second (t); // returns the second for the given time t
day (t); // the day for the given time t
weekday (t); // day of the week for the given time t
month (t); // the month for the given time t
year (t); // the year for the given time t
Functions for managing the timer services are:
setTime (t); // set the system time to the give time t
setTime (hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr
// (2010 or 10 sets year to 2010)
adjustTime (adjustment); // adjust system time by adding the
adjustment value
timeStatus (); // indicates if time has been set and recently
synchronized
// returns one of the following enumerations:
timeNotSet // the time has never been set, the clock started on
Jan 1, 1970
timeNeedsSync // the time had been set but a sync attempt did
not succeed
timeSet // the time is set and is synced
Date and time values are invalid if the status is timeNotSet. Otherwise,
the values could be used but the returned time would have skewed if the
status was timeNeedsSync.
setSyncProvider (getTimeFunction); // set the external time provider
setSyncInterval (interval); // set the number of seconds between re-
sync
There are several fit macros in the time.h file for time constants and time
unit conversion. To use the library, copy the download to the library
directory.
EXAMPLES
The Time Guide contains the time library and some examples of diagrams
showing how to use the library with different time sources:
DIFFERENCES
Differences between this code and playground date and time library
Although the time library is based on the date and time database, the API
has changed. Changes to the time library API:
TECHNICAL NOTES
Internal system time is based on Unix time_t standard. The value is the
number of seconds since January 1, 1970. The system time starts at zero
when the drawing begins.
The internal time can be automatically synchronized at regular intervals
with an external time source. This is enabled by calling the
setSyncProvider (provider) function - the provider argument is the address
of a function that returns the current time as time_t. See drawings in the
guide for examples to use.
The default time interval for resync is 5 minutes but can be changed by
calling the setSyncInterval method to set the number of seconds between
resync attempts.
The time library defines a structure for holding time elements and is a
compact version of CTM architecture. All members of the Arduino ™
architecture are bytes and compensate for the year from 1970. The
convenient macros provide conversion to and from the Arduino format.
Low-level functions are provided for switching between system time and
individual time elements:
breakTime (time, & tm ); // break time_t into elements stored in tm struct
makeTime (& tm ); // return time_t from elements stored in tm struct
This DS1307RTC library provides an example of how a timer can use
low-level functions to interact with a time library.
ARDUINO CONTROL STATEMENTS
D ecision-making structures require that the programmer define one or
more conditions to be evaluated or tested by the program. It should be
along with a statement or clauses to perform if the condition is defined as
true, and optionally, other clauses to be performed if the condition is
defined as false.
Here is the general look of the typical decision making structure found in
most programming languages -
The control architecture tells how the code is organized to enable the
program to take action based on certain conditions. Take this example; you
want your software to only trigger an LED when the sensor scores 50
degrees Celsius, you have to structure your code in a way to do such an
exact thing.
The method for ensuring such procedures can be seen in the program as a
control structure of the program, also known as a "control structure". This
is especially true when there are certain conditions in the program, just as
mentioned above. In order to achieve an intelligent and efficient control
architecture in Arduino programming, we use control data.
Control statements are elements (functions) in source code that control the
flow of program execution, either to wait, jump, iterate, etc.
The Arduino control data includes:
If statement
Else statement
Else if statement
For statement
While statement
Do while statement
Switch case
Continue
IF STATEMENT
An IF statement is basically the simplest form of a conditional control
clause, it is a conditional statement. The code "if statement" evaluates a
unique condition, and executes a series of instructions or just instructions if
the condition is true.
If the control statement is basically the type of control indication used to
program the dark street lights, the statement evaluates whether the
environment is dark or not, if the environment is dark, then the if statement
code directs the microcontroller to execute the code instructions that would
turn on the light The street, and if the environment is not dark, the if
statement code directs the microcontroller to execute the code instructions
that will not turn off the street light on and off until the environment
becomes dark.
The arduino IF statement flow diagram and syntax are shown below:
ELSE STATEMENT
Most of the time, the IF statement is followed directly by the ELSE
clause, the ELSE clause tells the alternate instructions to execute when the
IF statement is false. Check out the drawing below.
Figure 3: IF and ELSE clauses combine
The graphic in the photo above is better than the one that only has a
statement of an energized dark street light design.
ELSE IF STATEMENT
The "Else if statement" is used when we want to check three different
conditions. Includes the IF statement, ELSE IF statement, and ELSE
statement all in the same diagram. See the image below.
Figure 4: Schematic diagram showing the ELSE IF statement
FOR STATEMENT
The For statement is also a conditional statement for the Arduino control
topology used for frequent operation. As the name suggests, it is used to
perform a repeated operation of a real case. Take, for example, when a
carrier warns you that “if you try to recharge your phone number with the
wrong recharge code for 5 times, you will be blocked” If the case is present,
you can try to recharge that number repeatedly using the wrong charging
code in order to even Four times without being prevented, however, on the
fifth track, the state breaks down and you are banned.
For a clause, give a condition and check if the condition is still in effect,
and if it does, then action is taken and repetition can occur, and this will
continue to happen until the condition stops performing the action
associated with the condition. This can be used to augment an event. For
example, we can use the For statement to hide the LED up and down. See
the image below.
Figure 5: Fading the LED up and down with the for loop
Typically, a for loop is used to iterate a block of code enclosed in square
brackets. The increment counter is usually used to increase and end the
loop.
WHILE STATEMENT
The while clause is like an "if" statement except that it continues to repeat
a block of code (the block of code is what is inside the curly braces) as long
as the condition is true. See the example below.
Figure 6: Indication while flashing two LEDs for two different conditions
DO WHILE STATEMENT
The do while statement is similar to the else if statement but works the
same as the while loop, except that the condition is tested at the end of the
loop, so the do statement always runs at least one time. See the drawing
below:
Do while using the phrase to flash the LED in response to the sensor
reading.
USING ARRAYS
The graphic below illustrates the basic use of a matrix.
voidsetup () {
int my_array[5]; // an array with 5 integer elements
int i; // used as an index into the array
// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial . println (my_array[i]);
}
}
voidloop () {
}
// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial . println (my_array[i]);
}
}
voidloop () {
}
The values to initialize each element are enclosed in brackets {} after the
assignment operator (equal sign =). The first value in parentheses will be
assigned to the first element in the array (element number 0), the second
number in parentheses will be assigned to the second element in the matrix
(element number 1), etc.
The code that defines and initializes without the number of elements in
the array can also be written in square brackets:
int my_array[] = {23, 1001, 9, 1234, 987};
In this case, the compiler will work to determine how many elements the
array should contain based on the number of values used in its
initialization.
USES OF ARRAYS
This part of the course demonstrates that arrays can store data variables of
the same type in succession in memory allowing easy access using a loop.
There are many uses for arrays in programming, for example, arrays can
store data that is recorded, such as temperatures. Strings, which are lines of
text, are actually arrays as we'll see in the next part of this cycle.
HOW TO USE STRINGS IN ARDUINO
S trings are used to store text. Can be used to display text on the LCD
screen or in the Arduino IDE Serial Monitor window.
Strings are also useful for storing user input - for example the characters a
user types on the keyboard connected to the Arduino.
There are two types of strings in Arduino programming:
voidloop () {
}
The diagram shows what the string is made of - it consists of a character
array with printable characters and a 0 in the last element of the array to
show that this is where the string ends.
The series can be printed to the Arduino IDE Serial Monitor window
using Serial.println () and passed the name of the series.
This same diagram can be written more conveniently in this way:
voidsetup () {
char my_str[] = "Hello" ;
voidloop () {
}
COPY A STRING
The strcpy () function is used to copy the str [] string into the out_num []
array. Strcpy () copies the second string passed to it in the first string.
There is now a copy of the string in the out_num [] array, but it only
contains 18 elements of the array, so we still have 22 free elements in the
array. These free items are found after the series in memory.
The series is copied into the matrix so we have more space in the matrix
to use for the next portion of the chart adding a series to the end of the
series.
ARRAY BOUNDS
When working with strings and matrices, it is very important to work
within the boundaries of a string or matrix. In the example drawing, an
array of 40 characters is created to allocate memory that can be used to
manipulate the strings.
If the matrix is very small and we try to copy a larger string from the
matrix to it, then the series will be copied at the end of the matrix. The
memory behind the end of the array can contain other important data used
in the chart which will then be replaced by our series. If the memory
beyond the end of the series is exceeded, it may crash the drawing or cause
unexpected behavior.
WHAT IS AN OBJECT?
An object is a construct that contains both data and functions. String
object can be created just like a variable and set a value or a string. A
String object contains functions (called "methods" in object-oriented
programming (OOP) that operate on the string data contained in the String
object.
The following diagram and explanation will explain what an object is and
how to use a String object.
voidsetup () {
String my_str = "This is my string." ;
voidloop () {
}
A string object is created and assigned a value (or string) at the top of the
diagram.
String my_str = "This is my string." ;
This creates a String object with the name my_str and gives it the value
"This is my string".
This can be compared by creating a variable and assigning it a value like
an integer:
int my_var = 102;
(1) Print the string
The string can be printed in the Serial Monitor window just like the
Character Matrix string.
(2) Convert the string to uppercase
The my_str string object generated has a number of functions or methods
that can operate on it. These methods are called using the object name
followed by the period operator (.) And then the function name to use.
my_str.toUpperCase();
The toUpperCase () function works on the string contained in the my_str
object and is of type String and converts the string data (or text) the object
contains to uppercase.
A list of the functions that the String class contains can be found in the
Arduino String reference.
Technically, String is called a class and is used to create String objects.
(3) Overwrite a string
The reference operator is used to assign a new string to the my_str object
that replaces the old string.
my_str = "My new string." ;
The assignment operator cannot be used on character array strings, it only
works on string objects.
(4) Replace a word in the string
The replace () function is used to replace the first string passed into it by
the second string it is passed to. replace () is another function included in
the String class and is available for use on the String my_str object.
(5) Get the length of the string
Thread length can be easily obtained using length (). In the example
drawing, the result returned by length () is passed directly to Serial.println
() without using an intermediate variable.
The wires for this are very easy to do, we'll start connecting them in this
order:
The main part of the program that we will be using is the latest version on
the Arduino IDE. The new update brings a new way to see the data that is
received from the Arduino, instead of being in text form from the serial
monitor, it can now be displayed in a graph in real time which will help us
determine when the data changes its pattern (when someone is lying)
To open the plotter, open the Arduino and go to the Tools menu and you'll
see there right below the serial screen.
Now the icon for the micro controller is in the code section below. Copy
it and upload it to your board.
Step 5: making the finger clips
Now that we've finished the basic look of the project, we can start adding
features to make it easier to use, we'll start adding finger clips to keep a
steady connection between our fingers and the cables. Let's start by
sticking a strip of tin foil to the bottom of the velcro tape, do this for each of
the two pieces of Velcro (hook and loop. Now tie it around your finger until
it fits tight (check pictures) then attach an exposed wire from the analog pin
0 to the tin foil and repeat this Step for pin 5V (make sure it makes good
contact)
Step 6: Making the case
The plan is to make a small chamber to fold the finger pads away and
have three holes for the bulbs to stick out. It will be made of cardboard and
for its work we will need to cut out the following shapes:
void loop ()
{
if ( analogRead ( A0 ) >60 )
{
digitalWrite ( 4 , HIGH );
}
else
{
digitalWrite ( 4 , LOW );
}
if ( analogRead ( A0 ) >20 )
{
digitalWrite ( 2 , HIGH );
}
else
{
digitalWrite ( 2 , LOW );
}
if ( analogRead ( A0 ) >45 )
{
digitalWrite ( 3 , HIGH );
}
else
{
digitalWrite ( 3 , LOW );
}