CH 3
CH 3
Arduino programs can be divided in three main parts: Structure, Values (variables and constants),
and Functions. In this tutorial, we will learn about the Arduino software program, step by step, and
how we can write the program without any syntax or compilation error.
Let us start with the Structure. Software structure consist of two main functions –
Setup( ) function
Loop( ) function
These sketches contain the code – the instructions the board will follow. All sketches are divided into
two parts – setup function and loop function. You should put code that will run only once (for
example, code to set up a board for the application) in the setup function. The loop function contains
the code that will be run continuously after the initial setup is complete.
Arduino data types.They plays an important role when it comes to programming the Arduino. The
Arduino which is a computer is highly data agnostic (it does not know or care in what manner the
data it receives was sent to it.)
void
boolean
char
Unsigned char
byte
int
Unsigned int
Word
Long
Unsigned long
short
float
double
void
void is only used when declaring functions. It is used to indicate that the function is expected to return no
values when they are called.
void setup()
Serial.begin(9600);
void loop(
boolean
A boolean holds either one of two boolean values, true or false. boolean is a non-standard type alias for bool
defined by Arduino.
int switchPin = 13; // momentary switch on 13, other side connected to ground
void setup()
pinMode(LEDpin, OUTPUT);
pinMode(switchPin, INPUT);
void loop()
if (digitalRead(switchPin) == LOW)
char
char which is short for character, is a data type used to store a character value (A,B,C). When initializing
multiple characters it will be written in single quotes (eg. ‘A’) but for strings, they use double quotes
(eg.”ABC”)
Characters will be stored as numbers. For the specific encoding, you can refer to the ASCII Chart as shown
below.
Unsigned char
This Arduino data type has a memory of 8 bit/ 1 byte which is similar to the byte datatype. For clarity and
consistency of the Arduino programming style, for an unsigned, one-byte data type, the byte data type is
recommended.
byte
Similar to the unsigned char data type, a byte encodes an 8-bit unsigned number from 0-255
int
int which is short for integer is one of the most commonly used data type in Arduino. They are your primary
data type for storing numbers.
Do note that int size varies from board to board. For example, in ATmega based Arduino boards like the Uno,
Mega and Nano, an int uses 2 byte of memory and as a range of -32,768 to +32,767. While for the Due and
SAMD based boards (eg. MKR1000, Zero), int uses 4 byte of memory and as a range of -2,147,483,648 to +
2,147,483,647.
Unsigned int
The unsigned int is similar to int in the way that they store a 2-byte value. However, instead of storing negative
numbers, they store only positive values with a range of 0 to +65,535.
Same as int, unsigned int size varies from board to board with ATmega based Arduino boards storing a 2-byte
value while the Due and SAMD based boards stores a 4 bytes (32-bit) value and has a range of 0 to
4,294,967,295.
The main difference between unsigned int and ints is how the highest bit/sign bit is interpreted. In the int type
(which is signed), if the highest bit is “1”, the number is interpreted as a negative number, and the other 15 bits
are interpreted with.
Word
The word data type is very similar to the previous unsigned int data type. On the ATmega based Arduino
boards, a word stores a 16-bit unsigned number with a 2-byte value and a range from 0 to +65535. As for Due
and SAMD based boards, it stores a 32-bit unsigned number with a 4-byte value.
word w = 10000;
Long
Long variables are extended size variables for number storage. Long variables use 4 bytes from memory (32
bits) with a range from -2,147,483,648 to +2,147,483,647.
long speedOfLight = 186000L; //declaration of variable with type Long and initialize it with 186000
Unsigned long
Similar to the Long data type, unsigned long variables are extended size variables for number storage and use 4
bytes from memory (32 bits). However, unlike standard Longs, unsigned longs do not store negative numbers.
They have a range of 0 to +4,294,967,295.
void setup() {
Serial.begin(9600);
void loop() {
Serial.print("Time: ");
time = millis();
Serial.println(time);
delay(1000);
short
A short datatype stores a 16 bit value and uses 2 bytes from memory on ALL Arduinos. They have a range of -
32,768 to +32,767.
Prepared By: Department of Computer Engineering Page 7
Subject Name: Fundamentals of IoT Unit No: 03 Subject Code: 4360703
short ledPin = 13
float
The float is one of the most important Arduino data type as it can store decimal numbers. This data type is for
floating-point numbers which are numbers with a decimal point.
Floating-point numbers are often used to approximate the analog and continuous values because they have
greater resolution than integers.
This data type has a memory of 32 bit/ 4 bytes and a range of -3.4028235E+38 to +3.4028235E+38.
float myfloat;
int x;
int y;
float z;
x = 1;
double
This data type is a double-precision floating point number. On ATmega based Arduino boards like the Uno,
Mega and Nano, double precision floating-point number occupies 4 bytes (32 bit). That is, the double
implementation is exactly the same as the float, with no gain in precision.
While for Due and SAMD based boards (eg. MKR1000, Zero), double have 8 bytes (64-bit) precision.
double num = 45.352 ;// declaration of variable with type double and initialize it with 45.352
1. Arithmetic Operators
2. Compound Operators
3. Boolean Operators
4. Comparison Operators
5. Bitwise Operators
1.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 ( * )
Division ( / )
The division is used to determine the result of one number divided with another. For example, P/Q.
Modulo ( % )
Prepared By: Department of Computer Engineering Page 9
Subject Name: Fundamentals of IoT Unit No: 03 Subject Code: 4360703
The Modulo operator is used to calculate the remainder after the division of one number by another number.
Most of the operators are similar to the usual operator used in mathematics.
Example 1:
int b;
void setup ( )
Serial.begin( 9600 );
void loop ( )
b = 5 + 2;
Serial.println(b);
2. Compound Operators
b++
b+=
b--
b-=
b*=
b/=
b%=
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)
3.Boolean Operators
The Boolean Operators are NOT ( ! ), Logical AND ( & & ), and Logical OR ( | | ).
The result of the condition is true if both the operands in the condition are true.
Prepared By: Department of Computer Engineering Page 11
Subject Name: Fundamentals of IoT Unit No: 03 Subject Code: 4360703
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.
if ( a > 0 | | b > 0 )
The above statement is true, if either of the above condition ( a> 0 or b > 0 ) is true.
NOT ( ! )
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.
4.Comparison Operators
The comparison operators are used to compare the value of one variable with the other.
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.
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);
Output: 3
In the above code, if any of the two statement is correct, the corresponding value of the variable will be printed.
Here, only first condition is correct. Hence, the value of b will be printed.
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.
equal to ( = = )
It checks the value of two operands. If the values are equal, the condition is satisfied.
For example, a = = b.
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.
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.
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.
It checks the value of a is greater or equal than b. If either of the condition satisfies, the statement is true.
5.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 ( ~ )
The bitwise NOT operator acts as a complement for reversing the bits.
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
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
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 0 0 // input 1 or operand 1
0 1 0 1 // input 2
The left operator is shifted by the number of bits defined by the right operator.
The right operator is shifted by the number of bits defined by the left operator.
Decision making structures require that the programmer specify one or more conditions to be evaluated or
tested by the program. It should be along with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the programming
languages –
If statement
1 It takes an expression in parenthesis and a statement or block of statements. If
the expression is true then the statement or block of statements gets executed
otherwise these statements are skipped.
If …else statement
2 An if statement can be followed by an optional else statement, which executes
when the expression is false.
5 Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the
general form of a loop statement in most of the programming languages −
while loop
1 while loops will loop continuously, and infinitely, until the expression inside
the parenthesis, () becomes false. Something must change the tested variable,
or the while loop will never exit.
do…while loop
2 The do…while loop is similar to the while loop. In the while loop, the loop-
continuation condition is tested at the beginning of the loop before performed
the body of the loop.
for loop
3 A for loop executes statements a predetermined number of times. The control
expression for the loop is initialized, tested and manipulated entirely within the
for loop parentheses.
4 Nested Loop
C language allows you to use one loop inside another loop. The following
5 Infinite loop
It is the loop having no terminating condition, so the loop becomes infinite.
There are two required functions in an Arduino sketch or a program i.e. setup () and loop(). Other
functions must be created outside the brackets of these two functions:
Example
// Function declaration
void setup() {
Serial.begin(9600);
// Function call
Serial.println(result);
void loop() {
int sum = a + b;
return sum;
}
Explanation:
Function Declaration:
A function declaration provides information about the function, including its return type, name, and
parameter types.
It serves as a prototype for the function, letting the compiler know what to expect when the function is
defined later in the code.
Function Definition:
It specifies the return type, function name, and parameters, followed by the code block that contains the
function's logic.
In the example, addNumbers is a function that takes two integers as parameters and returns their sum.
Function Call:
In the setup function (which runs once at the beginning), we call the addNumbers function with
arguments 5 and 7.
The result is stored in a variable, and then it is printed using the Serial.println function.
Library functions
I/O Functions
In Arduino programming, I/O (Input/Output) functions are used to interact with digital and analog pins
to read inputs or control outputs. These functions are essential for working with sensors, actuators, and
other peripherals connected to the Arduino board. Here are some commonly used I/O functions in
Arduino:
1.pinMode(pin, mode):
2.digitalWrite(pin, value):
3.digitalRead(pin):
Reads the digital value (HIGH or LOW) from a specified digital pin.
1.analogRead(pin):
Reads the analog voltage value from a specified analog pin (0 to 1023).
2.analogWrite(pin, value):
Writes a PWM (Pulse Width Modulation) value to a specified PWM-enabled pin (commonly used for
simulating analog output).
Time Functions:
1.delay(ms):
2.millis():
Returns the number of milliseconds since the Arduino board began running the current program.
3.micros():
Returns the number of microseconds since the Arduino board began running the current program.
Example: Serial.begin(9600);
Checks for available data in the serial buffer and reads a byte.
In Arduino programming, character (char) functions are used for working with individual characters or
sequences of characters (strings). Here are some commonly used char functions and techniques in Arduino:
The char data type in Arduino is used to store a single character (8 bits).
Arduino supports the use of the String class for working with strings.
substring(start, length): Returns a substring starting from the specified index and of the specified length.
You can convert numerical values to strings using the String() constructor or the dtostrf() function for floating-
point numbers.
You can convert strings to numerical values using functions like toInt(), toFloat(), toDouble(), etc.
Prepared By: Department of Computer Engineering Page 22
Subject Name: Fundamentals of IoT Unit No: 03 Subject Code: 4360703
In Arduino, you often work with character arrays (C-strings) when dealing with strings.
When working with serial communication, you often use Serial.read() to read individual characters from the
serial buffer.
These are just a few examples of working with characters and strings in Arduino. When working with strings,
especially if you need dynamic memory allocation, be mindful of the memory constraints of Arduino boards.
Additionally, using C-strings and the String class should be chosen based on the requirements and constraints of
your specific application.
Math Functions
1. abs(x):
Returns the absolute value of x (the distance from zero without regard to the sign).
2. sqrt(x):
Returns a random number between min and max. The randomSeed(seed) function can be used to initialize the
random number generator.
5. constrain()
The function returns the constrained value within the specified range.
Hardware Setup:
1.Components Needed:
2.Circuit Connections:
Connect the longer leg (anode) of the LED to a digital pin on the Arduino (e.g., pin 13).
Connect the shorter leg (cathode) of the LED to the ground (GND) pin on the Arduino.
Connect one end of the resistor to the same digital pin to which the LED is connected.
Connect the other end of the resistor to the positive voltage (5V) on the Arduino.
Arduino Code
void setup() {
pinMode(ledPin, OUTPUT);
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
Explanation:
Defines a constant variable ledPin and assigns it the value 13. This is the digital pin to which the LED is
connected.
2. pinMode(ledPin, OUTPUT);:
Configures the ledPin as an output. This step is done in the setup() function, which runs once at the
beginning.
3. digitalWrite(ledPin, HIGH);:
Turns on the LED by setting the voltage on the ledPin to HIGH (5V).
4. delay(1000);:
5. digitalWrite(ledPin, LOW);:
Turns off the LED by setting the voltage on the ledPin to LOW (0V).
6. Looping:
The loop() function runs continuously, causing the LED to blink on and off in a 1-second interval.
Once the code is uploaded, you should see the LED connected to pin 13 on the Arduino blinking on and off at a
1-second interval.
1. Serial.begin(baudrate):
Initializes serial communication with a specified baud rate. Common baud rates include 9600, 115200,
etc.
Example: Serial.begin(9600);
2. Serial.available():
3. Serial.println (data):
4.Serial.print(data):
5.Serial.read():
Reads a byte of data from the serial buffer. Returns -1 if no data is available.
7.Serial.write(data):
8.Serial.readBytes()
Description
Serial.readBytes() reads characters from the serial port into a buffer. The function terminates if the determined
length has been read, or it times out (see Serial.setTimeout()).
Serial.readBytes() returns the number of characters placed in the buffer. A 0 means no valid data was found.
Syntax
Serial.readBytes(buffer, length)
9.Serial.end()
Description
Disables serial communication, allowing the RX and TX pins to be used for general input and output. To re-
enable serial communication, call Serial.begin().
Syntax
Serial.end()
10. Serial.readString()
Description
Serial.readString() reads characters from the serial buffer into a String. The function terminates if it times out
(see setTimeout()).
Syntax
Serial.readString()