Arduino Coding Basics
Brackets
• There are two types of brackets used in the Arduino coding, which are
listed below:
• Parentheses ( )
• Curly Brackets { }
• Parentheses ( )
• The parentheses brackets are the group of the arguments, such as method,
function, or a code statement. These are also used to group the math
equations.
• Curly Brackets { }
• The statements in the code are enclosed in the curly brackets. We always
require closed curly brackets to match the open curly bracket in the code or
sketch.
• Open curly bracket- ' { '
• Closed curly bracket - ' } '
Line Comment
The comment will not be displayed in the output. Such text is specified for a
better understanding of the code or for the explanation of any code statement.
There are two types of line comments, which are listed below:
• Single line comment
• Multi-line comment
// Single line comment
• The text that is written after the two forward slashes are considered as a single line
comment
• The compiler ignores the code written after the two forward slashes.
• The // (two forward slashes) are also used to ignore some extra lines of code without
deleting it.
/ * Multi - line comment */
• The Multi-line comment is written to group the information for clear understanding. It
starts with the single forward slash and an asterisk symbol (/ *). It also ends with the / *.
• the larger text. It is a comment, which is also ignored by the compiler.
Coding Screen
The coding screen is divided into two blocks. The setup is
considered as the preparation block, while the loop is
considered as the execution block.
• The set of statements in the setup and loop blocks are enclosed with the curly brackets. We
can write multiple statements depending on the coding requirements for a particular
project.
For Example,
void setup ( )
{
Coding statement 1;
Coding statement 2;
.
.
.
Coding statement n;
}
void loop ( )
{
Coding statement 1;
Coding statement 2;
.
.
.
Coding statement n;
What is Setup? What type of code is written in the
setup block?
It contains an initial part of the code to be executed. The
pin modes, libraries, variables, etc., are initialized in the
setup section. It is executed only once during the
uploading of the program and after reset or power up of
the Arduino board.
What is Loop? What type of code is written in the
Loop block?
The loop contains statements that are executed
repeatedly. The section of code inside the curly brackets
is repeated depending on the value of variables.
Time in Arduino
• The time in Arduino programming is measured in a
millisecond.
• Where, 1 sec = 1000 milliseconds
• We can adjust the timing according to the milliseconds.
• For example, for a 5-second delay, the time displayed
will be 5000 milliseconds.
pinMode ( )
The specific pin number is set as the INPUT or OUTPUT in
the pinMode () function.
The Syntax is: pinMode (pin, mode)
Where,
pin: It is the pin number. We can select the pin number
according to the requirements.
Mode: We can set the mode as INPUT or OUTPUT according
to the corresponding pin number.
Let' understand the pinMode with an example.
pinMode (12, OUTPUT);
Can we set the pinMode as INPUT?
• The digitalWrite () will disable the LOW during the INPUT
mode. The output pin will be considered as HIGH.
• We can use the INPUT mode to use the external pull-
down resistor. We are required to set the pinMode as
INPUT_PULLUP. It is used to reverse the nature of the
INPUT mode.
digitalWrite( )
• The digitalWrite ( ) function is used to set the value of a pin as HIGH or LOW.
• Where,
• HIGH: It sets the value of the voltage. For the 5V board, it will set the value
of 5V, while for 3.3V, it will set the value of 3.3V.
• LOW: It sets the value = 0 (GND).
• If we do not set the pinMode as OUTPUT, the LED may light dim.
• The syntax is: digitalWrite( pin, value HIGH/LOW)
• pin: We can specify the pin number or the declared variable.
• Let's understand with an example.
• Example:
digitalWrite (13, HIGH);
digitalWrite (13, LOW);
What is the difference between digitalRead () and
digitalWrite ()?
The digitalRead () function will read the HIGH/LOW value
from the digital pin, and the digitalWrite () function is
used to set the HIGH/LOW value of the digital pin.
delay ( )
• The delay () function is a blocking function to pause a
program from doing a task during the specified duration in
milliseconds.
• For example, - delay (2000)
• Where, 1 sec = 1000millisecond
• Hence, it will provide a delay of 2 seconds.
Code:
digitalWrite (13, HIGH);
delay (2000);
digitalWrite (13, LOW);
delay (1000);
Arduino Syntax and
Program Flow
Syntax
• Syntax in Arduino signifies the rules need to be followed
for the successful uploading of the Arduino program to
the board.
• The syntax of Arduino is similar to the grammar in
English. It means that the rules must be followed in
order to compile and run our code successfully.
• If we break those rules, our computer program may
compile and run, but with some bugs.
• Functions
• Spaces
• Tools Tab
• Uses of Parentheses ( )
• Semicolon ;
• Program Flow
• Flow Charts
Functions
• The functions in Arduino combine many pieces of lines of code into
one.
• The functions usually return a value after finishing execution. But here,
the function does not return any value due to the presence of void.
• The setup and loop function have void keyword present in front of
their function name.
• The multiple lines of code that a function encapsulates are written
inside curly brackets.
• Every closing curly bracket ' } ' must match the opening curly bracket
'{ ' in the code.
• We can also write our own functions, which will be discussed later in
this tutorial.
Spaces
• Arduino ignores the white spaces and tabs before the
coding statements.
• The coding statements in the code are intent (empty
spacing at the starting) for the easy reading.
• In the function definition, loop, and conditional
statements, 1 intent = 2 spaces.
• The compiler of Arduino also ignores the spaces in the
parentheses, commas, blank lines, etc.
Tools Tab
• The verify icon present on the tool tab only compiles the
code. It is a quick method to check that whether the
syntax of our program is correct or not.
• To compile, run, and upload the code to the board, we
need to click on the Upload button.
Uses of Parentheses ( )
• It denotes the function like void setup ( ) and void loop (
).
• The parameter's inputs to the function are enclosed
within the parentheses.
• It is also used to change the order of operations in
mathematical operations.
Semicolon ;
• It is the statement terminator in the C as well as C++.
• A statement is a command given to the Arduino, which instructs it to take
some kind of action. Hence, the terminator is essential to signify the end of a
statement.
• We can write one or more statements in a single line, but with semicolon
indicating the end of each statement.
• The compiler will indicate an error if a semicolon is absent in any of the
statements.
• It is recommended to write each statement with semicolon in a different line,
which makes the code easier to read.
• We are not required to place a semicolon after the curly braces of the setup
and loop function.
Arduino processes each statement sequentially. It executes one statement at a
time before moving to the next statement.
Program Flow
• The program flow in Arduino is similar to the flowcharts.
It represents the execution of a program in order.
• We recommend to draw the flowchart before writing the
code. It helps us to understand the concept of code,
which makes it the coding simpler and easier.
Arduino Serial |
Serial.begin()
Arduino Serial |Serial.begin()
• The serial communication is a simple scheme that uses the UART (Universal Asynchronous
Receiver/Transmitter) on the Microcontroller. It uses,
• 5V for logic 1 (high)
• 0V for logic 0 (low)
For a 3.3V board, it use
• 3V for logic 1 (high)
• 0V for logic 0 (low)
Every message sent on the UART is in the form of 8 bits or 1 byte, where 1
byte = 8 bits.
The Serial.begin( ) is a part of the serial object in the Arduino. It tells the
serial object to perform initialization steps to send and receive data on the
Rx and Tx (pins 1 and 0).
Serial.begin ( )
• The serial.begin( ) sets the baud rate for serial data communication.
The baud rate signifies the data rate in bits per second.
• The default baud rate in Arduino is 9600 bps (bits per second). We can
specify other baud rates as well, such as 4800, 14400, 38400, 28800, etc.
• The Serial.begin( ) is declared in two formats, which are shown below:
• begin( speed )
• begin( speed, config)
Where,
serial: It signifies the serial port object.
speed: It signifies the baud rate or bps (bits per second) rate. It
allows long data types.
config: It sets the stop, parity, and data bits.
Example :
It is shown below:
Arduino Serial.print ( )
• The serial.print ( ) in Arduino prints the data to the serial
port. The printed data is stored in the ASCII (American
Standard Code for Information Interchange) format,
which is a human-readable text.
• Each digit of a number is printed using the ASCII
characters.
• The printed data will be visible in the serial monitor,
which is present on the right corner on the toolbar.
• The Serial.print( ) is declared in two formats, which are
shown below:
• print( value )
• print( value, format)
Where,
serial: It signifies the serial port object.
print: The print ( ) returns the specified number of bytes
written.
value: It signifies the value to print, which includes any
data type value.
format: It consists of number base, such as OCT (Octal),
BIN (Binary), HEX (Hexadecimal), etc. for the integral
data types. It also specifies the number of decimal
places.
• he serial.print ( ) accepts the number using the ASCII character
per digit and value upto two decimal places for floating point
numbers.
Serial.print(15.452732)
• It sends bytes to the printer as a single character. In Arduino, the
strings and characters using the Serial.print( ) are sent as it is.
Serial.print("Hello Arduino")
It specifies the base format and gives the output according to the
specified format. It includes the formats Octal -OCT (base 8),
Binary-BIN (base 2), Decimal-DEC (base 10), and Hexadecimal-
HEX (base 16).
Serial.print(25, BIN)
Serial.print(58, HEX)
Serial.print(58, OCT)
Serial.print(25, DEC)
Serial.println ( )
• The Serial.println ( ) means print line, which sends the
string followed by the carriage return ('\r' or ASCII 13)
and newline ('\n' or ASCII 10) characters. It has a similar
effect as pressing the Enter or Return key on the
keyboard when typing with the Text Editor.
• The Serial.println( ) is also declared in two formats,
which are shown below:
• println( value )
• println( value, format)
Serial.available( )
• The Serial.available( ) function in Arduino gets the
stored bytes from the serial port that are available for
reading.
• It is the data, which is already stored and arrived in the
serial buffer.
• The serial buffer in Arduino holds the 64 bytes.
• Serial.available( ) function inherits from the utility class
called stream.
• The stream is only invoked when the function relying
on it is called. The stream class is considered as the
base class for binary and character-based streams.
• Let's understand with an example.
int arrivingdatabyte = 0; // initializing the incoming serial byte
void setup( )
{
Serial.begin(9600); // 9600 is the data rate in bps (bits per second).
}
void loop( ) // loop function that executes repeatedly
{
if(Serial.available( ) > 0) // It will only send data when the received data is greate
r than 0.
{
arrivingdatabyte = Serial.read( ); // It will read the incoming or arriving data byte
Serial.print("data byte received:");
Serial.println(arrivingdatabyte, DEC); // here, DEC means Decimal
}
}
Serial.read( )
• The Serial.read( ) in Arduino reads the incoming serial
data in the Arduino.
• The int data type is used here. It returns the first data
byte of the arriving serial data. It also returns -1 when
no data is available on the serial port.
• The syntax used in the Arduino programming is
Serial.read( ),
Serial.readString( )
• It reads the incoming serial data from the serial buffer in
the string. The String data type is used here.
How serial data is read by Serial.readString( ) and
Serial.read( )?
The Serial.read( ) function reads the data in terms of
bytes, while the Serial.readString( ) reads the data in the
term of string.
• Let's understand with an example.
String b;
void setup( )
{
Serial.begin(4800);
}
void loop( )
{
while( Serial.available( ) )
{
b = Serial.readString( );
Serial.println(b);
}
}
Serial.write( )
• It sends the binary data to the serial port in Arduino.
The data through Serial.write is sent as a series of bytes
or a single byte. The data type is size_t.
• The Serial.write( ) function will return the number of
written bytes.
• If we want to send the digits of numbers represented by
the characters, we need to use the Serial.print( )
function instead of Serial.write( ).
• The Serial.write( ) is declared in three formats, which are shown below:
• write( str )
• write( value )
• write( buffer, len)
• Let's understand with a simple example.
void setup( )
{
Serial.begin(14400);
}
void loop( )
{
Serial.write(55); // the specified value is 55.
// Serial.write( ) send the data as a byte with this value (55).
int Bytestosend = Serial.write( " Arduino" );
// It sends the Arduino string.
//The length of the string is a return parameter in this function.
}
Arduino Functions
• The functions allow a programmer to divide a specific code into
various sections, and each section performs a particular task. The
functions are created to perform a task multiple times in a
program.
• The function is a type of procedure that returns the area of code
from which it is called.
• For example, to repeat a task multiple times in code, we can use
the same set of statements every time the task is performed.
• Advantages of using Functions
• It increases the readability of the code.
• It conceives and organizes the program.
• It reduces the chances of errors.
• It makes the program compact and small.
• It avoids the repetition of the set of statements or codes.
• It allows us to divide a complex code or program into a simpler one.
• The modification becomes easier with the help of functions in a program.
• The Arduino has two common
functions setup() and loop(), which are called
automatically in the background. The code to be
executed is written inside the curly braces within these
functions.
• void setup() - It includes the initial part of the code,
which is executed only once. It is called as
the preparation block.
• void loop() - It includes the statements, which are
executed repeatedly. It is called the execution block.
• But sometimes, we need to write our own functions.
Function Declaration
• The method to declare a function is listed below:
• Function return type
• We need a return type for a function. For example, we can store the return
value of a function in a variable.
• We can use any data type as a return type, such as float, char, etc.
• Function name
• It consists of a name specified to the function. It represents the real body of
the function.
• Function parameter
• It includes the parameters passed to the function. The parameters are
defined as the special variables, which are used to pass data to a function.
• The function must be followed by parentheses ( ) and the semicolon ;
• The actual data passed to the function is termed as an argument.
• Let's understand with example.
Data Types
Data Types
• The data types are used to identify the types of data and the associated
functions for handling the data. It is used for declaring functions and
variables, which determines the bit pattern and the storage space.
• The data types that we will use in the Arduino are listed below:
• void Data Type
• int Data Type
• Char Data Type
• Float Data Type
• Double Data Type
• Unsigned int Data Type
• short Data Type
• long Data Type
• Unsigned long Data Type
• byte data type
• word data type
void Data Type
• The void data type specifies the empty set of values and only used to
declare the functions. It is used as the return type for the functions that
do not return any value.
• Let's understand with an example in Arduino.
int a = 3;
void setup( )
{
. //
}
void loop ( )
{
.
.
}
Int Data Type
• The integer data types are the whole numbers like 5, -6, 10, -123, etc.
They do not have any fractional part. The integer data types are
represented by int. It is considered as the primary data type to store the
numbers.
• The size of int is 2 bytes ( 16 bits).
• Minimal range: -32768 to 32767 or - (2^ 15) to ((2 ^ 15) - 1)
• The syntax is used as:
int var = val;
where,
var= variable
value = the value assigned to the variable
For example,
int a;
int b = 3;
• Let's understand with an example in Arduino.
int Sum = 0;
void setup( )
{
Serial.begin(9600);
}
void loop ( )
{
Sum++; // on every loop, it adds 1 to the Sum int
Serial.println ( Sum); // it prints the current state of the Sum variable
delay(1500); // delay of 1.5 seconds
}
Char Data Type
• The char datatype can store any number of character set. An identifier declared
as the char becomes a character variable. The literals are written inside a single
quote.
• The char type is often said to be an integer type. It is because, symbols, letters,
etc., are represented in memory by associated number codes and that are only
integers.
• The size of character data type is minimum of 8 bits. We can use the byte data
type for an unsigned char data type of 8 bits or 1 byte.
• For example, character ' A ' has the ASCII value of 65.
• If we specify, ' A ' + 2, it will have the ASCII value of 67.
• The syntax is:
char var = val;
where,
var= variable
val = The value assigned to the variable.
• Let's understand with an example.
char myvariable = ' B ';
char myvariable = 66 ; // both the value are equivalent
• The ASCII table is shown below:
Float Data Type
• A number having the fractional part and a decimal part is considered
as a floating-point number. For example, 4.567 is a floating-point
number. The number 13 is an integer, while 13.0 is a floating-point
number. Due to their greater resolution, fractional numbers are used
to approximate the contiguous and analog values.
• Floating point numbers can also be written in the exponent form. The
numbers can be as large as 3.4028235E+38 and as small as -
3.4028235E+38. The size of float data types is 4 bytes or 32 bits.
• The syntax is:
float var = val;
where,
var= variable
val = The value assigned to the variable
• Let's understand with an example.
int a ;
int b ;
float c ;
void setup ( )
{
Serial.begin (9600);
}
void loop ( )
{
a=3;
b = a/2 ; // b is an integer. It cannot hold fractions. The output will be 1.
c = (float) a / 2.0 ; // c now contains 1.5.
// Here, we have to use 2.0 instead of 2.
}
Double Data Type
• The double data type is also used for handling the decimal or
floating-point numbers. It occupies twice as much memory as
float. It stores floating point numbers with larger precision and
range. It stands for double precision floating point numbers.
• It occupies 4 bytes in ATmega and UNO boards, while 8 bytes
on Arduino Due.
• The syntax is:
double var = val;
where,
var= variable
val = The value assigned to the variable
Unsigned int Data Type
• The unsigned int stores the value upto 2 bytes or 16 bits. It
stores only positive values. The range of unsigned int data type
is from 0 to 65,535 or 0 to ((2 ^ 16) - 1).
• Arduino Due stores the unsigned data value of 4 bytes or 32-
bits.
• The syntax is:
unsigned int var = val;
where,
var= variable
val = The value assigned to the variable
• For example,
unsigned int pinofLED = 8;
Short Data Type
• The short is an integer data type that stores two bytes or 16-bit
of data.
• The range of short data types is from -32768 to 32767 or - (2^
15) to ((2 ^ 15) - 1). The ARM and ATmega based Arduino's
usually stores the data value of 2 bytes.
• The syntax is:
short var = val;
where,
var= variable
val = the value assigned to the variable
• For example,
short pinofLED = 8 ;
long Data Type
• The long data types are considered as the extended size variables,
which store 4 bytes (32 -bits). The size ranges from -
2,147,483,648 to 2,147,483,647.
• While using integer numbers, at least one of the numbers should
be followed by L, which forces the number to be a long data type.
• The syntax is:
long var = val;
where,
var= variable
val = The value assigned to the variable
• For example,
long speed = 186000L;
Unsigned long Data Type
• The unsigned long data types are also considered as the
extended size variables, which store 4 bytes (32 -bits).
• It does not store negative numbers like other unsigned data
types, which makes their size ranges from 0 to 4,294,967,295 or
(2^32 - 1).
• The syntax is:
unsigned long var = val;
where,
var= variable
val = The value assigned to the variable
• For example
unsigned long currenTtime;
byte
• 1 byte = 8 bits.
• It is considered as an unsigned number, which stores
values from 0 to 255.
The syntax 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 syntax is:
word var = val;
where,
var= variable
val = The value assigned to the variable
• For example,
word c = 2000;
Variables
• The variables are defined as the place to store the data and
values. It consists of a name, value, and type.
• The variables can belong to any data type such as int, float, char,
etc. Consider the url - Arduino data types for detailed information.
• Consider the below example:
• Here, the int data type is used to create a variable
named pin that stores the value 8. It also means that value 8 is
initialized to the variable pin.
• The above example can also be written as:
int LEDpin = 8;
• Here, the variable name is LEDpin.
• We can refer the declared variable further in our program or code.
• For example,
pinMode(LEDpin, OUTPUT);
• Here, the value stored (8) in the declared variable
(LEDpin) will be passed to the pinMode() function.
Advantages of Variables
• We can use a variable many times in a program.
• The variables can represent integers, strings,
characters, etc.
• It increases the flexibility of the program.
• We can easily modify the variables. For example, if we
want to change the value of variable LEDpin from 8 to
13, we need to change the only point in the code.
• We can specify any name for a variable. For example,
greenpin, bluePIN, REDpin, etc.
How can we change the value of a
variable in Arduino?
• The value of a variable can be changed using the assignment operator
( equal = sign). But we need to declare a variable before assigning the
value.
• If we directly specify the value as:
pin = 7;
• We will get an error that pin has not declared.
• We can easily change the variables by copying its value to another variable.
• For example,
int LEDpin = 7;
int pin1 = LEDpin;
LEDpin = 13;
• The LEDpin now contains the value 13 instead of 7. But, value of pin1 is still
7.
Variables Scope
• It means that in how many ways the variables can be
declared.
• The variables can be declared in two ways in Arduino,
which are listed below:
• Local variables
• Global variables
Local Variables
• The local variables are declared within the function. The variables have scope only
within the function. These variables can be used only by the statements that lie
within that function.
• For example,
void setup()
{
Serial.begin(9600);
}
void loop()
{
int x = 3;
int b = 4;
int sum = 0;
sum = x + b;
Serial.println(sum);
}
Global Variables
• The global variables can be accessed anywhere in the program. The
global variable is declared outside the setup() and loop() function.
• For example,
• Consider the below code.
int LEDpin = 8;
void setup()
{
pinMode(LEDpin, OUTPUT);
}
void loop()
{
digitalWrite(LEDpin, HIGH);
}
Constants
What are constants?
• The constants in Arduino are defined as the predefined
expressions. It makes the code easy to read.
• The constants in Arduino are defined as:
• Logical level Constants
• Pin level Constants
• LED_BUILTIN Constant
• Constant Keyword
• #define
Logical level Constants
• The logical level constants are true or false.
• The value of true and false are defined as 1 and 0. Any
non-zero integer is determined as true in terms of
Boolean language. The true and false constants are
type in lowercase rather than uppercase (such as HIGH,
LOW, etc.).
Pin level Constants
• The digital pins can take two value HIGH or LOW.
• In Arduino, the pin is configured as INPUT or OUTPUT using the pinMode() function. The pin is
further made HIGH or LOW using the digitalWrite() function.
• HIGH
• The board includes two types of voltage pins to provide HIGH value, which are listed below:
• 5V
• 3V
• Some boards include only 5V pins, while some include 3.3V.
• Some boards consist of both 5V and 3.3V pins. For example, Arduino UNO R3.
• The pin configured as HIGH is set at either 5V or 3.3V.
• The pins are configured at the 5V or 3.3V depending on:
• for voltage > 3.0V (presented at 5V pin)
• for voltage > 2.0V (presented at 3.3V pin)
• LOW
• The pin configured as LOW is set at 0 Volts.
• The pins are configured at the 5V or 3.3V depending on:
• for voltage < 1.5V (presented at 5V pin)
• for voltage < 1V (presented at 3.3V pin)
LED_BUILTIN Constant
• The Arduino boards have built-in LED connected in
series with the resistor. The particular pin number is
defined with the constant name called LED_BUILTIN.
• Most Arduino boards have the LED_BUILTIN connected
to Pin number 13.
Constant Keyword
• The name const represents the constant keyword. It modifies the behavior
of the variables in our program. It further makes the variable as 'read-only'.
• The variable will remain the same as other variables, but its
value cannot be changed.
It means we cannot modify the constant. For example,
const int a =2;
//....
a = 7; // illegal - we cannot write to or modify a constant
• The const keyword is considered superior compared to
the #define keyword because it obeys the rules of
the variable scope.
#define
• The #define in Arduino is used to give a name to the constant
value. It does not take any memory space on the chip.
• At the compile time, the compiler will replace the predefined value
in the program to the constants with the defined value.
• The syntax is:
#define nameOFconstant value
where,
nameOFconstant: It is the name of the macro or constant to define
value: It includes the value assigned to the constant or macro.
• For example,
#define LEDpin 12
// It is the correct representation of #define
Operators
• The operators are widely used in Arduino programming from
basics to advanced levels. It plays a crucial role in every
programming concept like C, C++, Java, etc.
• The operators are used to solve logical and mathematical
problems. For example, to calculate the temperature given by
the sensor based on some analog voltage.
• The types of Operators classified in Arduino are:
• Arithmetic Operators
• Compound Operators
• Boolean Operators
• Comparison Operators
• Bitwise Operators
Arithmetic Operators
• There are six basic operators responsible for performing mathematical operations in
Arduino, which are listed below:
• Assignment Operator ( = )
• The Assignment operator in Arduino is used to set the variable's value. It is quite different from the
equal symbol (=) normally used in mathematics.
• Addition ( + )
• The addition operator is used for the addition of two numbers. For example, P + Q.
• Subtraction ( - )
• Subtraction is used to subtract one value from the another. For example, P - Q.
• Multiplication ( * )
• The multiplication is used to multiply two numbers. For example, P * Q.
• Division ( / )
• The division is used to determine the result of one number divided with another. For example, P/Q.
• Modulo ( % )
• The Modulo operator is used to calculate the remainder after the division of one number by another
number.
• Let's understand the operators with the help of examples
int d;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
d = 5 - 2;
Serial.println(d);
d = d + 3;
Serial.println(d);
}
• Here, d= d +3 is not operated as a usual mathematical
operation. It is the assignment operator where right of
the function is evaluated first and is assigned to the left
of the equal sign.
Order of mathematical operations
• Let's understand the order of operations considered by the Arduino while performing
calculation:
1. Parentheses ( )
2. Multiplication, division, and modulo
3. Addition and subtraction
• If there are multiple operations next to each other, they will be computed from left to right.
• Let's understand with an example.
int c;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
c = 2 * 3 / (2 + 1) + 4;
Serial.println(c);
}
• Let's understand how the above output occurred.
Consider the below image:
Compound Operators
• The compound operators perform two or more calculations at once.
• The result of the right operand is assigned to the left operand, as already discussed above. The same
condition will apply to all the compound operators, which are listed below:
• Let's consider a variable b.
• b++
• Here, b = b + 1. It is called the increment operator.
• b+=
• For example, b + = 4. It means, b = b+ 4.
• b--
• Here, b = b - 1. It is called as the decrement operator.
• b-=
• For example, b - = 3. It means, b = b - 3.
• b*=
• For example, b * = 6. It means, b = b * 6.
• b/=
• For example, b / = 5. It means, b = b / 5.
• b%=
• For example, b % = 2. It means, b = b % 2.
• Now, let's use the above operators with two variables, b
and c.
• b + = c ( b = b + c)
• b - = c ( b = b - c)
• b * = c ( b = b * c)
• b / = c ( b = b / c)
• b % = c ( b = b % c)
• We can specify any variable instead of b and c.
Boolean Operators
• The Boolean Operators are NOT ( ! ), Logical AND ( & & ), and Logical OR ( | | ).
• Logical AND ( & & )
• The result of the condition is true if both the operands in the condition are true.
• Consider the below example:
if ( a = = b & & b = = c )
• Above statement is true if both conditions are true. If any of the conditions is false, the
statement will be false.
• Logical OR ( | | )
• The result of the condition is true, if either of the variables in the condition is true.
• Consider the below example.
if ( a > 0 | | b > 0 )
• The above statement is true, if either of the above condition ( a> 0 or b > 0 ) is true.
• NOT ( ! )
• It is used to reverse the logical state of the operand.
• For example, a ! = 2.
• The NOT operator returns the value 1 or TRUE when the specified operand is FALSE. It also
reverses the value of the specified expression.
Comparison Operators
• he comparison operators are used to compare the value of one variable with the other.
• The comparison operators are listed below:
• less than ( < )
• The less than operator checks that the value of the left operand is less than the right operand.
The statement is true if the condition is satisfied.
• For example, a <b.
• If a is less than b, the condition is true, else false.
• greater than ( > )
• The less than operator checks that the value of the left side of a statement is greater than the
right side. The statement is true if the condition is satisfied.
• For example, a > b.
• If a is greater than b, the condition is true, else false.
• equal to ( = = )
• It checks the value of two operands. If the values are equal, the condition is satisfied.
• For example, a = = b.
• The above statement is used to check if the value of a is equal to b or not.
• not equal to ( ! = )
• It checks the value of two specified variables. If the values are not equal, the condition will
be correct and satisfied.
• For example, a ! = b.
• less than or equal to ( < = )
• The less or equal than operator checks that the value of left side of a statement is less or
equal to the value on right side. The statement is true if either of the condition is satisfied.
• For example, a < = b
• It checks the value of a is less or equal than b.
• greater than or equal to ( > = )
• The greater or equal than operator checks that the value of the left side of a statement is
greater or equal to the value on the right side of that statement. The statement is true if
the condition is satisfied.
• For example, a > = b
• It checks the value of a is greater or equal than b. If either of the condition satisfies, the
statement is true.
int b;
int c ;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
b = 3;
c = 5;
if ( b < 4 )
Serial.println(b);
if ( c < 4)
Serial.println( c);
}
Bitwise Operators
• The Bitwise operators operate at the binary level.
These operators are quite easy to use.
• There are various bitwise operators. Some of the
popular operators are listed below:
• bitwise NOT ( ~ )
• bitwise XOR ( ^ )
• bitwise OR ( | )
• bitwise AND ( & )
• bitwise left shift ( < < )
• bitwise right shift ( > > )
• bitwise NOT ( ~ )
• The bitwise NOT operator acts as a complement for reversing the bits.
• For example, if b = 1, the NOT operator will make the value of b = 0.
• Let's understand with another example.
0 0 1 1 // Input or operand 1 ( decimal value 3)
1 1 0 0 // Output ( reverses the input bits ) decimal value is 12
• bitwise XOR ( ^ )
• The output is 0 if both the inputs are same, and it is 1 if the two input bits are different.
• For example,
1 0 0 1 // input 1 or operand 1
0 1 0 1 // input 2
1 1 0 0 // Output ( resultant - XOR)
• bitwise OR ( | )
• The output is 0 if both of the inputs in the OR operation are 0. Otherwise, the output is 1. The two input
patterns are of 4 bits.
• For example,
1 1 0 0 // input 1 or operand 1
0 0 0 1 // input 2
1 1 0 1 // Output ( resultant - OR)
• bitwise AND ( & )
• The output is 1 if both the inputs in the AND operation are 1. Otherwise,
the output is 0. The two input patterns are of 4 bits.
• For example,
1. 1 1 0 0 // input 1 or operand 1
2. 0 1 0 1 // input 2
3. 0 1 0 0 // Output ( resultant - AND)
• bitwise left shift ( < < )
• The left operator is shifted by the number of bits defined by the right
operator.
• bitwise right shift ( > > )
• The right operator is shifted by the number of bits defined by the left
operator.
Array
Array
• The arrays are defined as the data structures that allow
multiple values to be grouped together in a simple way.
This is an easily access method.
• The array is normally built from the data types
like integer, reals, characters, and boolean. It refers
to a named list of finite number (n) of similar data
elements.
• The set of consecutive numbers usually represent the
elements in the array, which are 0, 1, 2, 3, 4, 5,
6,.......n.
• The array in Arduino is declared with the integer data
type.
• It is also defined as the collection of variables, which is
acquired with an index number.
• We can specify any name according to our choice. The
array name is the individual name of an element.
• The array is represented as:
• The elements of the array can be characters, negative numbers,
etc.
• For example,
int myarray[ 4 ] = { 1, -3, 4};
char myarray[ 6] = " Hi " ;
• The size of the array should not be less than the number of
elements. For example,
• int myarray[5 ] = { 1, 4, 6, 7 } ; can be written as int
myarray[8 ] = { 1, 4, 6, 7 } ;
• But, it cannot be written as int myarray[ 2] = { 1, 4, 6, 7 } ;
• Let's understand with an example.
Delay
• Here, Arduino Delay specifies the delay( )
function used in the Arduino programming. Let's
discuss the delay( ) function in detail.
• delay( ) function
• The delay( ) function pauses the program or task for a
specified duration of time. The time is specified inside
the open and closed parentheses in milliseconds.
Where,
1 second = 1000 milliseconds
If statement
• The if ( ) statement is the conditional statement, which
is the basis for all types of programming languages.
• If the condition in the code is true, the corresponding
task or function is performed accordingly. It returns one
value if the condition in a program is true. It further
returns another value if the condition is false.
• It means that if ( ) statement checks for the condition
and then executes a statement or a set of statements.
• It clearly explains the process of execution of a statement.
If the condition is False, it comes out of the if ( ) statement.
If the condition is true, the function is performed.
• The if ( ) statement is written as:
if ( condition)
{
// include statements
// if the condition is true
// then performs the function or task specified inside the curly brac
es
}
• Here,
• condition = It includes the boolean expressions, that can be true or false.
• We can also use one or more operators inside the parentheses.
• The comparison operators that can be used as a condition inside the
parentheses are listed below:
• a ! = b ( a not equal to b )
• a < b ( a less than b )
• a > b ( a greater than b )
• a = = b ( a equal to b )
• a < = b ( a less than or equal to b )
• a > = b ( a greater than or equal to b )
• where,
• a and b are the variables.
• Example :
int a = 6; // initiaization of values to variables a and b
int b = 4;
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (a > b )
{
Serial.println( " a is greater than b ");
}
if (b > a )
{
Serial.println( " b is greater than a ");
}
}
if-else and else-if
If else
• The if-else condition includes if ( ) statement and else ( )
statement. The condition in the else statement is
executed if the result of the If ( ) statement is false.
• Example :
int a = 5;
int b= 6;
void setup ( )
{
Serial.begin ( 9600 );
}
void loop ( )
{
if ( a > b )
{
Serial.println ( " a is greater " );
}
else
{
Serial.println ( " a is smaller " );
}
}
Else if
• The else if statement can be used with or without the else ( )
statement. We can include multiple else if statements in a program.
if (condition)
{
// statements
}
else if ( condition)
{
// statements
// only if the first condition is false and the second is true
}
else
{
//statements
}
• Example :
int i = 2;
int j = 3;
void setup ( )
{
Serial.begin(9600);
}
void loop ( )
{
if ( i > j )
{
Serial.println( " I is greater ");
}
else if ( i < j )
{
Serial.println( " J is greater " );
}
else
{
Serial.println( " Both are equal " );
}
}
for Loop
for Loop
• The statements inside the curly brackets under for loop are executed repeatedly
according to the specified condition. An increment counter in the for loop is used
to increment or decrement the loop repetitions.
• The for statement is commonly used for repetitive task or operation or to operate
on the group of data/pins in combination with arrays.
• The syntax is:
for (initialization; condition; increment)
{
\\ statements
}
where,
• initialization: It is defined as the initialization of the variable.
• condition: The condition is tested on every execution. If the condition is true, it
will execute the given task. The loop ends only when the condition
becomes false.
• increment: It includes the increment operator, such as i + +, i - - , i + 1, etc. It is
incremented each time until the condition remains true.
• Example :
int x;
void setup ( )
{
Serial.begin(9600);
for (x = 2; x < 100; x = x * 2)
{
Serial.println(x);
}
}
void loop ( ) {
}
while loop
while loop
• The while loop() is the conditional loop that continues to execute the code
inside the parentheses until the specified condition becomes false.
• The while loop will never exit until the tested condition is changed or
made to stop. The common use of a while loop in Arduino includes sensor
testing, calibration (calibrating the input of sensor), variable
increment, etc.
• The syntax is:
while (condition)
{
// code or set of statements
}
where,
condition: It specifies the boolean expression, which determines the condition to be
true or false.
• Example :
int a = 0;
void setup()
{
Serial.begin(9600);
while( a < 5)
{
Serial.println("Welcome to Arduino");
a = a + 1;
}
Serial.println("DONE");
Serial.println("Welcome to the code outside the loop");
}
void loop()
{
}
do...while
• The working of the do-while loop is similar to the while loop.
The condition inside the do-while will execute at least once.
It is because the condition is tested at the end of the loop
instead of the beginning.
• The syntax is:
do
{
// code or set of statements
} while (condition);
where,
condition: It specifies the boolean expression, which determines the
condition to be true or false.
• Example :
int a = 0;
void setup()
{
Serial.begin(9600);
do
{
Serial.println("Welcome to the do while loop");
a = a + 1;
} while( a < 3);
}
void loop()
{
}
switch case
switch case
• The switch case controls the flow of the program by
executing the code in various cases. A switch statement
compares a particular value of a variable with statements in
other cases. When the statements in a case matches the value
of a variable, the code associated with that case executes.
• The break keyword is used at the end of each case. For
example, if there are five cases, the break statements will also
be five. The break statement exits the switch case.
• The switch statement without a break will continue to execute
all the cases until the end. Hence, it is essential to include a
break statement at the end of each case.
• The syntax is:
switch(variable)
{
case 1:
// statements related to case1
break;
case 2:
// statements related to case2
break;
.
.
case n:
// statements related to case n
break;
default:
// it contains the optional code
//if nothing matches in the above cases, the default statement runs
break;
}
• where,
• variable: It includes the variables whose value will be compared with the multiple cases
• value: It consists of a value to compare. These values are constants. The allowed data
types are int and char.
• Example :
void setup()
{
Serial.begin(9600);
int a = 1;
switch(a) // the case matching the value in the declared variable will run
{
case 1:
Serial.println(" Case 1 matches");
// the value of variable matches with the value in case 1.
// The message associated with case 1 will be printed
break;
case 2:
Serial.println(" Case 2 matches");
break;
case 3:
Serial.println(" Case 3 matches");
break;
default:
Serial.println(" default matches");
break;
}
}
void loop()
{
}
String
• The string is a data type that stores text rather than the integer values. It
is similar to other data types such as integer, float, etc., in Arduino.
• The string is an array of characters or a set of characters that consists
of numbers, spaces, and special characters from the ASCII table.
• The string can be declared in the following ways:
• char StrA[10];
• char StringA[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e’};
• char StringB[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
• We can also declare an array with extra space for a string constant StrA.
• char StrA[10]; = "Hello";
• char StrD[6]; = "Hello";
• char StrD[]; = "Welcome";
• Example :
const int length = 15;
char myString[length] = "Hello Arduino";
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println(myString);
delay(500);
}