IOT Unit 4
IOT Unit 4
Arduino UNO R3
Arduino UNO is a kind of microcontroller board based on ATmega328 which is a kind of single chip microcontroller
formed with Atmel within the megaAVR family. The architecture of this Arduino Uno is a customized Harvard
architecture with 8 bits RISC processor core.
This board includes 14 digital I/O pins, 6 analog I/O pins, power jack, USB connector, Reset Buttons etc. Power is
supplied to this board with the help of AC to DC adapter, USB cable, or a battery.
void setup()
{
//statements;
}
void loop()
{
//statements;
}
❖ Where setup() is the preparation and loop() is the execution. Both functions are required for the program to work.
❖ The setup function should follow the declaration of any variables at the very beginning of the program.
❖ It is the first function to run in the program, is run only once, and is used to set pinMode or initialize serial
communication.
❖ The loop function follows next and includes the code to be executed continuously – reading inputs, triggering
outputs, etc. This function is the core of all Arduino programs and does the bulk of the work.
setup()
The setup() function is called once when your program starts. Use it to initialize pin modes, or begin serial. It must be
included in a program even if there are no statements to run.
void setup()
{
pinMode(pin, OUTPUT); // sets the 'pin' as output
}
loop()
After calling the setup() function, the loop() function does precisely what its name suggests, and loops consecutively,
allowing the program to change, respond, and control the Arduino board.
void loop()
{
digitalWrite(pin, HIGH); // turns 'pin' on
delay(1000); // pauses for one second
digitalWrite(pin, LOW); // turns 'pin' off
delay(1000); // pauses for one second
}
{} curly braces
Curly braces (also referred to as just "braces" or "curly brackets") define the beginning and end of function blocks and
statement blocks such as the void loop() function and the for and if statements.
return_type function_name()
{
statements;
}
; semicolon
A semicolon must be used to end a statement of the program. A semicolon is also used to separate elements in a for
loop.
int x = 13; // declares variable 'x' as the integer 13
Because comments are ignored by the program and take no memory space they should be used generously and can also
be used to “comment out” blocks of code for debugging purposes.
Note: While it is possible to enclose single line comments within a block comment, enclosing a second block comment
is not allowed.
// line comments
Single line comments begin with // and end with the next line of code. Like block comments, they are ignored by the
program and take no memory space.
Single line comments are often used after a valid statement to provide more information about what the statement
accomplishes or to provide a future reminder.
Variable
A variable is a container that can hold any value depending upon its data type. The value of the variable can be changed
during execution of the program. A variable is a name of the memory location where its data is stored.
Variable Declaration
A variable must be declared before we can use it in a program. When we declare a variable, it reserves the space in the
memory whose size depends upon its data type.
Syntax: data_type variable_name;
Example:
int num;
Char c;
float x; etc.
Variable Initialization
Variable initialization means assigning a value to the variable. Value can be assigned to a variable using assignment
operator.
Example:
int x=5;
char c=’a’; etc
Constants
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "Programming" etc.
Data Types
char – This datatype is used to store a character. Character constants are written in single quotes.
String – This datatype is used to store set of characters that can also contain spaces and number. Strings are always
written in double quotes
byte – Byte stores 8 bits unsigned numbers, from 0 – 255 (Total - 2^8 = 256).
word – Word data type stores 16 bit (2 bytes) unsigned numbers from 0 – 65535 (Total 2^16 = 65536).
int – This datatype is used to store integer numbers in 2 bytes.
float – This datatype is used to store floating integers in 4 bytes.
double – This datatype is also used to store floating integers in 4 bytes.
bool – This datatype is used to store only Boolean values (true, false, 1, 0, HIGH, LOW)
Variable Scope
Scope refers to the availability of variables and functions in certain parts of the code.
1. Global Scope
A global variable is one that can be seen and used by every function and statement in a program. This variable
is declared at the beginning of the program, before the setup() function.
2. Local Scope
A local variable is one that is defined inside a function or as part of a specific loop. It is only visible and can only
be used inside the function in which it was declared.
int value; // 'value' is visible to any function
void setup()
{
// no setup needed
}
void loop()
{
for (int i=0; i<20;) //'i' is visible only inside the for-loop
{
i++;
}
float f; // 'f' is only visible inside loop
}
Variable Qualifier
Qualifier defines additional behavior to our variables. There are two main kinds of qualifier.
• Constant
Constant qualifier is declared by using const keyword. It is a variable qualifier that modifies the behaviour of
the variable by making a variable read-only. This means the variable can be used just as any other variable of
its type but its value can’t be changed while executing the program. You will get compile error if you try to alter
its value.
Syntax: const data_type variable_name = value;
Example: const int pi = 3.14;
• static
Static variables have a property of preserving their value even after they are out of their scope. Hence, static
variables preserve their previous value in their previous scope and are not initialized again in the new scope.
Syntax: static data_type variable_name = value;
Example: static int num = 5;
Digital Write
digitalWrite() is a function which is used to write a state of low(0V) or high(5V) to a digital pin.
Syntax: digitalWrite(pin, state);
Whenever we use digital write, we have to declare that pin as output using pinMode() function
Digital Read
digitalRead() is a function which is used to read the state of a digital pin that is it high or low.
Syntax: digitalRead(pin);
Analog Read
This function reads the value from specified analog pin. analogRead() function can only be used with the analog pins
which are numbered A0 to A5. Arduino board contains 10 bit ADC. This means that it will map input voltage from 0V
to 5V into integer value from 0 to 1023.
Syntax: analogRead(pin);
Analog Write
analogWrite() function writes analog value to PWM pins. This is used to control the brightness of an LED or to control
the speed of a motor.
Syntax: analogWrite(pin, value); Its value range from 0-255.
3. Reading from Serial Monitor: You can also read data from the Serial Monitor and use it in your Arduino
program.
Operators
1. Assignment Operators
Used to assign values to variables.
Examples include =, +=, -=, *=, /=, etc.
2. Arithmetic Operators
Perform basic arithmetic operations.
Common operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulus).
3. Increment & Decrement Operators
Used to increase or decrease the value of a variable by 1.
o ++ (increment)
o -- (decrement)
4. Relational Operators
Used to compare two values. Examples include == (equal to), != (not equal to), > (greater than), < (less than),
>= (greater than or equal to), <= (less than or equal to).
5. Logical Operators
Used to combine multiple conditions.
Examples include && (logical AND), || (logical OR), and ! (logical NOT).
Conditional Statements
1. if Statement
Executes a block of code if a specified condition is true.
if (condition) {
// code to execute
}
2. if-else Statement
Executes one block if a condition is true, and another if it’s false.
if (condition) {
// code if true
}
else {
// code if false
}
3. if-else-if Ladder
Used when you have multiple conditions to check sequentially.
if (condition1) {
// code for condition1
}
else if (condition2) {
// code for condition2
}
else {
// code if all conditions are false
}
4. Nested if Statement
if statements inside another if statement for checking multiple conditions.
if (condition1) {
if (condition2) {
// code if both conditions are true
}
}
Loops
1. for Loop
Repeats a block of code a specified number of times.
for (initialization; condition; increment/decrement) {
// code to repeat
}
2. while Loop
Repeats a block of code as long as a condition remains true.
while (condition) {
// code to repeat
}
3. do-while Loop
Executes a block of code at least once, then repeats while a condition is true.
do {
// code to execute
} while (condition);
Control Statements
1. break Statement
Used to exit from a loop or a switch case immediately.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // loop stops when i is 5
}
}
2. continue Statement
Skips the current iteration of a loop and moves to the next one.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // skip the rest of the code when i is 5
}
// code to execute
}
3. switch-case Statement
Allows branching based on multiple possible values of an expression (often used with integers or characters).
int choice = 2;
switch (choice) {
case 1:
// code for case 1
break;
case 2:
// code for case 2
break;
default:
// code if no cases match
break;
}
Arrays
An Array is a data structure that stores a collection of elements (of the same data type) in contiguous memory
locations.
Syntax:
data_type array_name[size];
For example:
int numbers[5] = {1, 2, 3, 4, 5};
• Arrays can be accessed using an index:
int first = numbers[0]; // Accesses the first element
• Arrays can be single-dimensional or multi-dimensional (like 2D arrays, which are arrays of arrays).
Functions
A Function is a block of code that performs a specific task. It is reusable and helps modularize the code.
1. Function Declaration
Defines the function's name, return type, and parameters.
return_type function_name(parameter_list);
2. Function Definition
Contains the actual code that will be executed.
return_type function_name(parameter_list) {
// code to execute
}
3. Function Call
Executes the function's code.
function_name(arguments);
Example:
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3); // Function call
// result now holds the value 8
}
Functions can be used to simplify code, reduce repetition, and increase readability.
Practical Programs
1. Write a program to Blink default Light Emitting Diode(LED) on Arduino board with the delay of 2 sec.
2. Write a program to interface LEDs on pin no. 10,11,12,13 and blink alternatively at the delay of 1 sec.
3. Write a program to run pattern(s) on LEDs connect at pins 10,11,12,13. Pattern example:
(2) (3)
ON OFF OFF OFF ON ON OFF OFF
OFF ON OFF OFF OFF ON ON OFF
OFF OFF ON OFF OFF OFF ON ON
OFF OFF OFF ON ON OFF OFF ON
4. Write a program to interface buzzer with Arduino board to buzz on/off with the delay of 1sec.
5. Write a program to interface LED and Buzzer with Arduino board, so that buzzer is put on whenever LED is on
and Buzzer is put off when LED is off.
6. Write a program to interface Button and LED, so that LED glow when button is pressed.
7. Write a program to interface Button, buzzer and LED, whenever the button is pressed the buzzer gives beep for
100ms and LED status is toggled.
8. Write a program to interface LEDs at pins 10,11,12,13 and buttons at pins 7,8. When first time button at pin
7(increment button) is pressed first LED at pin 10 is switched on, when second time button is pressed the next
LED at 11 is switched on. Similarly, when the button at pin 8 (decrement button) is pressed the LEDs are
switched off sequentially.
9. Write a program to interface LEDs at pins 10,11,12,13 and button at pins 7. The press of button changes the
pattern of LED glow. (considering four patterns of LED glow).
10. Write a program to interface Light Dependent Resistor (LDR) and display the values read on the Serial
monitor after delay of 2 seconds each.
11. Write a program to interface Light Dependent Resistor (LDR) and LED with Arduino board. Whenever there
is sufficient light falls on LDR the LED is off and when there is dark around LDR the LED is put on.
12. Write a program to interface LEDs at any two PWM pins and exhibit LED fading.
13. Write a program to interface LED at PWM pin and LDR, in such a way that when the light intensity falling on
LDR rises the LED glow should be reduced and after a threshold value the LED should be put off. (representing
smart street light concept)
14. Write a program to interface any analog (pollution) sensor and display the values read on Serial monitor.
15. Write a program to interface LCD with Arduino board and display ‘Hello world’ on it.