0% found this document useful (0 votes)
82 views

CS3691 Embedded System & IOT Lab Manual

The document outlines a series of assembly language experiments for an Embedded Systems and IoT course at Prathyusha Engineering College. Each experiment includes aims, software requirements, program code, and results, covering tasks such as data transfer, data exchange, finding the largest element in an array, sorting, and performing arithmetic operations on 16-bit numbers. The software used for these experiments is KeiluVision 5.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

CS3691 Embedded System & IOT Lab Manual

The document outlines a series of assembly language experiments for an Embedded Systems and IoT course at Prathyusha Engineering College. Each experiment includes aims, software requirements, program code, and results, covering tasks such as data transfer, data exchange, finding the largest element in an array, sorting, and performing arithmetic operations on 16-bit numbers. The software used for these experiments is KeiluVision 5.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 126

CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

LIST OF EXPERIMENTS
EXP MARKS
DATE TITLE OF THE EXPERIMENT SIGNATURE
NO OBTAINED

Page | 1
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXPT 1a OUTPUT:

Before Execution:

After Execution:

Page | 2
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:1 a DATE:


Aim:
To write an assembly language program to transfer N =05h bytes of data from location A:30h to
location B:40h.

Software Required:
KeiluVision 5

Program:

Org 0000h
mov r0,#30h //source address
mov r1,#40h //destination address
mov r7,#05h //Number of bytes to be moved
back: mov a,@r0
mov @r1,a
inc r0
inc r1
djnz r7,back //repeat till all data transferred
end

Result:
Thus an assembly language program to transfer N bytes of data from location A to B is written and
executed.

Page | 3
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXPT 1b OUTPUT:

Before Execution:

After Execution:

Page | 4
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:1 b DATE:


Aim:
To Write an assembly language program to exchange N =05h bytes of data location
A:30h and at location B:40h.

Software Required:
KeiluVision 5

Program:
Let N = 05h A: 30h B: 40h
mov r0,#30h //source address
mov r1,#40h //destination address
mov r7,#05h //count, the number of data to be exchanged
back: mov a,@r0
mov r4,a
mov a,@r1
mov @r0,a
mov a,r4
mov @r1,a
inc r0
inc r1
djnz r7,back
end

Result:
Thus an assembly language program to exchange N bytes of data from location A to B is written and
executed.

Page | 5
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:

Before Execution:

After Execution:

Page | 6
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:1 c DATE:


Aim:
To Write an assembly language program to find the largest element in a given array of
N =06 h bytes at location 4000h. Store the largest element at location 4062h.

Software Required:
KeiluVision 5

Program:
Let N = 06h
org 0000H
mov r3,#6 //length of the array
mov dptr,#4000H //starting address of array
mov b,#00H
loop2:movx a,@dptr
cjne a,b,loop1
loop3:inc dptr
djnz r3,loop2
mov a,b
mov dptr,#4062H //store at #4062H
movx @dptr,a
ret
loop1:jc loop3 // JNC FOR SMALLEST ELEMENT
mov b,a //update larger number
sjmp loop3
ret
end

Result:
Thus an assembly language program to find the largest element in a given array of N
bytes at location 4000h and Stored the largest element at location 4062h. is executed

Page | 7
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:

Before Execution:

After Execution : Ascending

After Execution : Descending

Page | 8
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:1 d DATE:


Aim:
To Write an assembly language program to sort an array of N bytes of data in
ascending/descending order stored from location 9000h.(Using bubble sort algorithm)
Software Required:
KeiluVision 5

Program:
Let N = 06h
mov r0,#05H //count (N-1) array size = N
loop1: mov dptr, #9000h //array stored from address 9000h
mov r1,#05h //initialize exchange counter
loop2: movx a, @dptr //get number from array and store in B register
mov b, a
inc dptr
movx a, @dptr //next number in the array
clr c //reset borrow flag
mov r2, a //store in R2
subb a, b //2nd-1st No, since no compare instruction in 8051
jnc noexchg // JC - FOR DESCENDING ORDER
mov a,b //exchange the 2 nos in the array
movx @dptr,a
dec dpl //DEC DPTR - instruction not present
mov a,r2
movx @dptr,a
inc dptr

noexchg: djnz r1,loop2 //decrement compare counter


djnz r0,loop1 //decrement pass counter
end

Result:
Thus an assembly language program to sort an array of N bytes of data in
ascending/descending order stored from location 9000h. is executed using bubble sort
algorithm.

Page | 9
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:

Before Execution:

After Execution:

Page | 10
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:1 e DATE:


Aim:

To write and execute an Assembly language program to transfer data between registers and
memory.

Software Required:
KeiluVision 5

Program:
ORG 0000H
CLR C
MOV R0, #55H
MOV R1, #6FH
MOV A, R0
MOV 30H, A
MOV A, R1
MOV 31H, A
END

Result:
Thus an assembly language program to transfer data between registers and memory is written and
executed.

Page | 11
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT: Example 1

MEMORY WINDOW
Before execution:

After execution:

Example 2

Before execution:

After execution:

Page | 12
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:2 a DATE:


Aim:
To Write an assembly language program to add two 16 bit numbers
Software Required:
KeiluVision 5

Program:
MOV R0,#51H // Initialize input1 memory pointer
MOV R1,#61H /* Initialize input2 memory pointer and store output also same */
MOV R2,#02H // Initialize iteration count
CLR C
BACK: MOV A,@R0 /*Get lower bytes data in first iteration, upper bytesdata in second
iteration, add them with carry and store in memory pointer2.*/
ADDC A,@R1
MOV @R1,A
DEC R0 // Increment memory pointer1 & 2 to get upper bytes
DEC R1
DJNZ R2,BACK /* Decrement iteration count and if it is not zero, go to relative address
and repeat the same process until count become zero.*/
JNC FINISH
MOV @R1,#01H
FINISH:SJMP $
END

Result:
Thus an assembly language program to add two 16 bit data has been executed.

Page | 13
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:
MEMORY WINDOW
Before execution:

After execution:

Eg. 0025 – 0AF6 = FFF52F (ANSWER IS NEGATIVE)


Before execution:
D:0x50H: 00 25 00 00 00 00
D:0X60H: 0A F6 00 00 00 00
After execution:
D:0x50H: 00 25 00 00 00 00
D:0x5FH: FF F5 2F 00 00 00

Page | 14
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:2 b DATE:


Aim:
To Write an assembly language program to subtract two 16 bit numbers
Software Required:
KeiluVision 5

Program:
MOV R0,#51H // Initialize input1 memory pointer
MOV R1,#61H /* Initialize input2 memory pointer and store output also same */
MOV R2,#02H // Initialize iteration count
CLR C
BACK: MOV A,@R0 /*Get lower bytes data in first iteration, upper bytesdata in second
iteration, add them with carry and store in memory pointer2.*/
ADDC A,@R1
MOV @R1,A
DEC R0 // Increment memory pointer1 & 2 to get upper bytes
DEC R1
DJNZ R2,BACK /* Decrement iteration count and if it is not zero, go to relative address
and repeat the same process until count become zero.*/
JNC FINISH
MOV @R1,#01H
FINISH:SJMP $
END

Result:
Thus an assembly language program to subtract two 16 bit data has been executed.

Page | 15
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:
RESULT
REGISTER VALUES:
R6 R7 = 02 03
R4 R5 = 04 05
R0 R1 R2 R3 = 00 08 16 0F

Page | 16
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:2 c DATE:


Aim:
To Write an assembly language program to multiply two 16 bit numbers
Software Required:
KeiluVision 5

PROGRAM:
MOV R6,#02H //0203 X 0405 = 0008160F
MOV R7,#03H // input the multiplicand
MOV R4,#04H // input the multiplier
MOV R5,#05H
//Multiply R5 by R7
MOV A,R5 // Move the R5 into the Accumulator
MOV B,R7 // Move R7 into B
MUL AB // Multiply the two values
MOV R2,B // Move B (the high-byte) into R2
MOV R3,A // Move A (the low-byte) into R3
//Multiply R5 by R6
MOV A,R5 // Move R5 back into the Accumulator
MOV B,R6 // Move R6 into B
MUL AB // Multiply the two values
ADD A,R2 // Add the low-byte into the value already in R2
MOV R2,A // Move the resulting value back into R2
MOV A,B // Move the high-byte into the accumulator
ADDC A,#00h // Add zero (plus the carry, if any)
MOV R1,A // Move the resulting answer into R1
MOV A,#00h // Load the accumulator with zero
ADDC A,#00h // Add zero (plus the carry, if any)
MOV R0,A // Move the resulting answer to R0.
//Multiply R4 by R7
MOV A,R4 // Move R4 into the Accumulator
MOV B,R7 // Move R7 into B
MUL AB // Multiply the two values
ADD A,R2 // Add the low-byte into the value already in R2
MOV R2,A // Move the resulting value back into R2
MOV A,B // Move the high-byte into the accumulator
ADDC A,R1 // Add the current value of R1 (plus any carry)
MOV R1,A // Move the resulting answer into R1.

Page | 17
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 16
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

MOV A,#00h // Load the accumulator with zero


ADDC A,R0 // Add the current value of R0 (plus any carry)
MOV R0,A // Move the resulting answer to R1.
//Multiply R4 by R6
MOV A,R4 // Move R4 back into the Accumulator
MOV B,R6 // Move R6 into B
MUL AB // Multiply the two values
ADD A,R1 // Add the low-byte into the value already in R1
MOV R1,A // Move the resulting value back into R1
MOV A,B // Move the high-byte into the accumulator
ADDC A,R0 // Add it to the value already in R0 (plus any carry)
MOV R0,A // Move the resulting answer back to R0

// answer is now in R0, R1, R2, and R3


SJMP $
END

Result:
Thus an assembly language program to multiply two 16 bit data has been executed.

Page | 17
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:
RESULT
REGISTER VALUES:
R1 R0 = D7 FE // D7FE/D9 = FE
R3 R2 = 00 D9
R3 R2 = 00 FE

Page | 18
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:2 d DATE:


Aim:
To Write an assembly language program to divide two 16 bit numbers
Software Required:
KeiluVision 5

Assume
R1 R0 = D7 4E
R3 R2 = 00 D9
R3 R2 = 00 FE
PROGRAM:
MOV R1,#0D7H
MOV R0,#4EH
MOV R3,#00H
MOV R2,#0D9H
div16_16:
CLR C // Clear carry initially
MOV R4,#00h // Clear R4 working variable initially
MOV R5,#00h // CLear R5 working variable initially
MOV B,#00h /* Clear B since B will count the number of left-shifted bits*/
div1:
INC B // Increment counter for each left shift
MOV A,R2 // Move the current divisor low byte into the accumulator
RLC A /* Shift low-byte left, rotate through carry to apply highest bit to
high-byte*/
MOV R2,A // Save the updated divisor low-byte
MOV A,R3 /* Move the current divisor high byte into the accumulator*/
RLC A // Shift high-byte left high, rotating in carry from low-byte
MOV R3,A // Save the updated divisor high-byte

Page | 19
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 20
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

JNC div1 // Repeat until carry flag is set from high-byte


div2: // Shift right the divisor
MOV A,R3 // Move high-byte of divisor into accumulator
RRC A // Rotate high-byte of divisor right and into carry
MOV R3,A // Save updated value of high-byte of divisor
MOV A,R2 // Move low-byte of divisor into accumulator
RRC A // Rotate low-byte of divisor right, with carry from high-byte
MOV R2,A // Save updated value of low-byte of divisor
CLR C // Clear carry, we don't need it anymore
MOV 07h,R1 // Make a safe copy of the dividend high-byte
MOV 06h,R0 // Make a safe copy of the dividend low-byte
MOV A,R0 // Move low-byte of dividend into accumulator
SUBB A,R2 /* Dividend - shifted divisor = result bit (no factor, only 0or 1)*/
MOV R0,A // Save updated dividend
MOV A,R1 // Move high-byte of dividend into accumulator
SUBB A,R3 /* Subtract high-byte of divisor (all together 16-bit
subtraction)*/
MOV R1,A // Save updated high-byte back in high-byte of divisor
JNC div3 // If carry flag is NOT set, result is 1
MOV R1,07h /* Otherwise result is 0, save copy of divisor to undo subtraction*/
MOV R0,06h
div3:
CPL C // Invert carry, so it can be directly copied into result
MOV A,R4
RLC A // Shift carry flag into temporary result
MOV R4,A
MOV A,R5

Page | 21
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 22
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

RLC A
MOV R5,A
DJNZ B,div2 // Now count backwards and repeat until "B" is zero
MOV R3,05h // Move result to R3/R2
MOV R2,04h // Move result to R3/R2
END

Result:
Thus an assembly language program to divide two 16 bit data has been executed.

Page | 23
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:

Before execution: After execution:

Page | 24
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:2 e DATE:

AIM:
To write 8051 Assembly Language Program for an 8-bit addition using Keil simulator and execute
it.

Software Required:
KeiluVision 5

PROGRAM:

ORG 0000H
CLR C
MOV A, #29H
ADD A, #98H
MOV R0, A
END

Result:
Thus an assembly language program for 8-bit addition has been executed.

Page | 25
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:

MEMORY WINDOW

Before execution:

After execution:

Page | 26
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:2 f DATE:

AIM:
To write 8051 Assembly Language Program for ALU operation using Keil simulator and execute
it.

Software Required:
KeiluVision 5

PROGRAM:

ORG 0000H
CLR C
//ADDITION
MOV A, #20H
ADD A, #21H
MOV 41H, A

//SUBTRACTION
MOV A, #20H
SUBB A, #18H
MOV 42H, A

//MULTIPLICATION
MOV A, #03H
MOV B, #04H
MUL AB
MOV 43H, A
MOV 44H, B

//DIVISION
MOV A, #95H
MOV B, #10H
DIV AB
MOV 45H, A
MOV 46H, B

//AND
MOV A, #25H
MOV B, #12H
ANL A, B
MOV 47H, A

Page | 27
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 28
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

//OR
MOV A, #25H
MOV B, #15H
ORL A, B
MOV 48H, A

//XOR
MOV A, #45H
MOV B, #67H
XRL A,B
MOV 49H, A

//NOT
MOV A, #45H
CPL A
MOV 4AH, A
END

Result:
Thus an assembly language program for ALU operations has been executed.

Page | 29
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:
When LED is OFF

When LED is ON

Page | 24
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:3 a DATE:


Aim:
To Write an 8051 C program to flash LED
Software Required:
KeiluVision 5
Steps:

Select the port pin for led.


Configure the pin as an output to write the first value 0.
Now pin configured as the output, if we have passed 1 or 0 on that pin it will directly reflect on
it.
Create a macro IN_BINARY, which takes input in 1 and 0 format. It set and reset the PORT Pin
corresponding the input binary value

Program:

#include<reg51.h>

void Delay()
{
int i;
for(i=0;i<=1000;i++)
{
}
}
void main()
{
while(1)
{
P2=0x00;
Delay();
P2=0xFF;
Delay();
}
}

Result:
Thus an Embedded C program to flash LED has been written and executed.

Page | 25
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:
PERIPHERAL WINDOW
Before execution:

After execution:

Page | 28
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:3 b DATE:


Aim:
To Write an 8051 C program to get a byte of data form P1, wait ½ second, and then send it to P2.

Software Required:
KeiluVision 5

Program:

#include <reg51.h>
void MSDelay(unsigned int);
void main(void)
{
unsigned char mybyte;
P1=0x55; //make P1 input port
while (1)
{
mybyte=P1; //get a byte from P1
MSDelay(500);
P2=mybyte; //send it to P2
}
}
void MSDelay(unsigned int time)
{
unsigned int i,j;
for(i=0;i<time;i++)
for(j=0;j<1275;j++)
{
}
}

Page | 29
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 30
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Result:
Thus an 8051 C program was executed to get a byte of data form Port 1, wait ½ second,
and then send that data to Port 2.

Page | 31
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

OUTPUT:
PERIPHERAL WINDOW
Before execution:

After execution:

Page | 30
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:4 DATE:


Aim:
To write an embedded C program for addition, subtraction, multiplication, and division
using the Keil simulator.

Software Required:
KeiluVision 5

Program:

#include<reg51.h>
void main(void)
{
unsigned char x,y,z,a,b,c,d;
x=0x12;
y=0x32;
P0=0x00;
z=x+y;
P0=z;
P1=0x00;
a=y-x;
P1=a;
P2=0x00;
d=x*y;
P2=d;
P3=0x00;
c=y/x;
P3=c;
while(1);
}

Result:
Thus an 8051 C program for addition, subtraction, multiplication, and division was executed

Page | 32
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Pin Diagram of Arduino UNO:

Page | 33
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No: 5 a Date:

Aim:
To study about Arduino platform and programming.
Introduction:
Arduino is a project, open-source hardware, and software platform used to design and build electronic
devices. It designs and manufactures microcontroller kits and single-board interfaces for building
electronics projects.
The Arduino board consists of sets of analog and digital I/O (Input / Output) pins, which are further
interfaced to breadboard, expansion boards, and other circuits. Such boards feature the model,
Universal Serial Bus (USB), and serial communication interfaces, which are used for loading
programs from the computers.
What is Arduino?
Arduino is a software as well as hardware platform that helps in making electronic projects. It is an
open source platform and has a variety of controllers and microprocessors. There are various types of
Arduino boards used for various purposes.
The Arduino is a single circuit board, which consists of different interfaces or parts. The board
consists of the set of digital and analog pins that are used to connect various devices and components,
which we want to use for the functioning of the electronic devices.
Most of the Arduino consists of 14 digital I/O pins.
The analog pins in Arduino are mostly useful for fine-grained control. The pins in the Arduino board
are arranged in a specific pattern. The other devices on the Arduino board are USB port, small
components (voltage regulator or oscillator), microcontroller, power connector, etc.
Types of Arduino Boards
There are many types of Arduino boards available in the market but all the boards have one thing in
common: they can be programmed using the Arduino IDE. The reasons for different types of boards
are different power supply requirements, connectivity options, their applications etc.
Arduino boards are available in different sizes, form factors, different no. of I/O pins etc. Some of the
commonly known and frequently used Arduino boards are Arduino UNO, Arduino Mega, Arduino
Nano, Arduino Micro and Arduino Lilypad.
There are add-on modules called Arduino Shields which can be used to extend the functionalities of
the Arduino boards. Some of the commonly used shields are Arduino Proto shield, Arduino WiFi
Shield and Arduino Yun Shield.

Page | 34
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 34
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

General purpose input/output pins of Arduino UNO.


General-Purpose Input Output (GPIO) is a digital pin of an IC. It can be used as input or output for
interfacing devices.

Digital Output
Arduino (ATmega) digital pins can be configured as output to drive output devices. We have to
configure these pins to use as output.
To configure these pins, pinMode() function is used which set direction of pin as input or output.
• pinMode(pin no, Mode)
This function is used to configure GPIO pin as input or output. pin no number of pin whose mode we
want to set.
Mode INPUT, OUTPUT or INPUT_PULLUP E.g. pinMode (3, OUTPUT) //set pin 3 as output
These pin produce output in terms of HIGH (5 V or 3.3 V) or LOW (0 V). We can set output on these
pins using digitalWrite () function.
• digitalWrite (pin no, Output value)
This function is used to set output as HIGH (5 V) or LOW (0 V)
pin no number of a pin whose mode we want to set. Output value HIGH or LOW
E.g. digitalWrite (3, HIGH) Digital Input
To read data from senor or from any device/circuit, we need to configure digital pin as input. Arduino
pin are set as digital input (default). So, there is no need to configure pin as input.
To configure pin as digital input, pinMode() function is used. We can read data from GPIO pin using
digitalRead() function.
• digitalRead(pin)
It is used to read data from specified GPIO pin. Digital Input with Pull-up Resistor
• Sometimes switching between one state to another or pins configured as input with nothing
connected to them may arise situation of High-impedance state i.e. floating state. This state may
report random changes in pin state.

Page | 35
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 36
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

• To avoid this state, there is option of adding pull-up (to +5V) or pull-down (to Gnd) resistor
which helps to set the input to a known state. Following image show the high impedance (undefine)
state and pull-up resistor.

• Arduino (ATmega) has in-built configurable pull-up resistor. These resistors enable using
pinMode() with mode set to INPUT_PULLUP. When connecting a device or sensor to a pin
configured as input with pull-up, the other end should be connected to ground.
e.g. pinMode (3, INPUT_PULLUP).
• We can configure input pull-up in another way too. If we set direction of pin as input and then
write HIGH value on that pin will turn on the pull-up resistor. In other manner, if we write HIGH on
pin configured as OUTPUT and then configure that pin as input will also enable the pull-up resistor.
e.g. pinMode (3, INPUT) //set pin as input
digitalWrite (3, HIGH) //setting high on input pin enables pullup
Pulse Width Modulation (PWM) is a technique by which width of a pulse is varied while keeping
the frequency of the wave constant. It is a method for generating an analog signal using a digital
source.
A PWM signal consists of two main components that define its behaviour: a duty cycle and a
frequency. Duty Cycle of Signal:
A period of a pulse consists of an ON cycle (5V) and an OFF cycle (0V). The fraction for which the
signal is ON over a period is known as a duty cycle.

Through PWM technique, we can control the power delivered to the load by using ON-OFF signal.
The
PWM signals can be used to control the speed of DC motors and to change the intensity of the LED.
Pulse Width Modulated signals with different duty cycle are shown below

Frequency of Signal
The frequency of a signal determines how fast the PWM completes a cycle (i.e. 1000 Hz would be
1000 cycles per second) which means how fast it switches between ON (high) and OFF (low) states.
By repeating this ON-OFF pattern at a fast-enough rate, and with a certain duty cycle, the output will
appear to behave like a constant voltage analog signal when providing power to devices.
PWM Pins of Arduino Uno
Arduino Uno has 6 8-bit PWM channels. The pins with symbol ‘~’ represents that it has PWM
support. These PWM pins are shown in below image.

Page | 37
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 38
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Arduino PWM Pin Details


Arduino Functions for PWM
analogWrite (pin, duty cycle)
It is used to generate PWM or output analog value to a specified PWM channel.
pin – pin on which we want to generate pwm or analog signal.
duty cycle – it lies in between 0 (0%, always off) – 255 (100%, always on).
e.g. analogWrite (3, 127) //generates pwm of 50% duty cycle
Programming Structure in Arduino UNO.
Arduino program is divided into 3 main parts.
1.Structure
2.Values
3.Functions
1.Structure:
The basic structure of the Arduino programming language is fairly simple and runs in at least two
parts. These two required parts, or functions, enclose blocks of statements.
void setup()
{
statements;
}
void loop()
{
statements;
}
Where setup() is the preparation, loop() is the execution. Both functions are required for the program
to work.

Page | 39
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 40
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

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
}

Page | 41
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 42
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

2.Functions:
A function is a block of code that has a name and a block of statements that are executed when the
function is called. The functions void setup() and void loop() have already been discussed and other
built-in functions will be discussed later.
Custom functions can be written to perform repetitive tasks and reduce clutter in a program.
Functions are declared by first declaring the function type. This is the type of value to be returned by
the function such as 'int' for an integer type function. If no value is to be returned the function type
would be void. After type, declare the name given to the function and in parenthesis any parameters
being passed to the function.
type functionName(parameters)
{
statements;
}
The following integer type function delayVal() is used to set a delay value in a program by reading
the value of a potentiometer. It first declares a local variable v,sets v to the value of the potentiometer
which gives a number between 0-1023, then divides that value by 4 for a final value between 0-255,
and finally returns that value back to the main program.
int delayVal()
{
int v; // create temporary variable 'v'
v = analogRead(pot); // read potentiometer value
v /= 4; // converts 0-1023 to 0-255
return v; // return final value
}
3. Variables:
A variable is a way of naming and storing a numerical value for later use by the program. As their
namesake suggests, variables are numbers that can be continually changed as opposed to constants
whose value never changes. A variable needs to be declared and optionally assigned to the value
needing to be stored.

Page | 43
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 44
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

The following code declares a variable called inputVariable and then assigns it the value obtained on
analog input pin 2:
int inputVariable = 0; // declares a variable and // assigns value of 0
inputVariable = analogRead(2); // set variable to value of // analog pin 2
‘inputVariable’ is the variable itself. The first line declares that it will contain an int, short for integer.
The second line sets the variable to the value at analog pin 2. This makes the value of pin 2 accessible
elsewhere in the code. Once a variable has been assigned, or re-assigned, you can test its value to see
if it meets certain conditions, or you can use its value directly. As an example to illustrate three useful
operations with variables, the following code tests whether the inputVariable is less than 100, if true it
assigns the value 100 to inputVariable, and then sets a delay based on inputVariable which is now a
minimum of 100:
if (inputVariable < 100) // tests variable if less than 100
{
inputVariable = 100; // if true assigns value of 100
}
delay(inputVariable); // uses variable as delay
Constants
The Arduino language has a few predefined values, which are called constants. They are used to make
the programs easier to read. Constants are classified in groups. True/False
These are Boolean constants that define logic levels. FALSE is easily defined as 0 (zero) while
TRUE is often defined as 1, but can also be anything else except zero. So in a Boolean sense, -1, 2,
and -200 are all also defined as TRUE.
if (b == TRUE);
{
doSomething;
}
High/Low
These constants define pin levels as HIGH or LOW and are used when reading or writing to digital
pins. HIGH is defined as logic level 1, ON, or 5 volts while LOW is

Page | 45
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 46
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

logic level 0, OFF, or 0 volts.


digitalWrite(13, HIGH);
Input/Output
Constants used with the pinMode() function to define the mode of a digital pin as
either INPUT or OUTPUT.
pinMode(13, OUTPUT);
LED_BUILTIN
Most Arduino boards have a pin connected to an on-board LED in series with a resistor. The constant
LED_BUILTIN is the number of the pin to which the on-board LED is connected. Most boards have
this LED connected to digital pin 13.

Result:
Thus the basics of Arduino and its programming structures has been studied

Page | 47
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Arduino UNO with LED:

Page | 48
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:5 b DATE:


Aim:
To write and execute Arduino programming for digital Communication

Hardware Required:
Arduino UNO
LED
Jumper Wires
Software Required:
Arduino IDE

PROGRAM:
DIGITAL WRITE:
void setup()
{
pinMode(2, OUTPUT);
}
void loop()
{
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
}

Result:

Thus program to interface LED with Arduino UNO has been written and established the
communication between them.

Page | 48
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Arduino UNO with switch control LED :

Page | 49
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:5 c DATE:

Aim:
To write and execute Arduino programming for digital Communication

Hardware Required:
Arduino UNO , LED, Switch, Jumper Wires
Software Required:
Arduino IDE

PROGRAM:

DIGITAL READ:
void setup()
{
pinMode(2, OUTPUT);
pinMode(5, INPUT_PULLUP);
}
void loop()
{
int sw=digitalRead(5);
if(sw==1)
{
for(int i=0; i<5; i++)
{
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
}
}
else
{
digitalWrite(2, LOW);
}
}

Result:

Thus program to interface switch control LED with Arduino UNO has been written and established the
communication between them
Page | 50
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Arduino UNO for PWM :

Page | 51
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:5 d DATE:

Aim:
To write and execute Arduino programming for Analog Communication

Hardware Required:
Arduino UNO, LED, Oscilloscope, Jumper Wires
Software Required:
Arduino IDE

PROGRAM:
ANALOG WRITE:
void setup()
{
pinMode(3, OUTPUT);
}
void loop()
{
for(int i=0; i<256;i++)
{
analogWrite(3,i);
delay(20);
}
for(int i=255; i>=0;i--)
{
analogWrite(3,i);
delay(20);
}
}

Result:

Thus program to interface PWM controlled LED with Arduino UNO has been written and
established the communication between them

Page | 52
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Arduino UNO for Serial Communication :

OUTPUT

Page | 53
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

EXP NO:5 e DATE:

Aim:
To write and execute Arduino programming for Serial Communication

Hardware Required:
Arduino UNO, LED, Jumper Wires
Software Required:
Arduino IDE

PROGRAM:

SERIAL COMMUNICATION:
void setup()
{
Serial.begin(9600);
pinMode(4, OUTPUT);
}
void loop()
{
if(Serial.available()>0)
{
char data=Serial.read();
Serial.println(data);
if(data=='1')
{
digitalWrite(4,HIGH);
Serial.println("The LED is On");
}
else if(data=='2')
{
digitalWrite(4,LOW);
Serial.println("The LED is Off");
}
}
}

Result:

Thus program to interface LED with Arduino UNO has been written and established the serial
communication between them

Page | 54
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Arduino UNO with Zigbee:

Page | 55
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No:6 a Date:


Aim:
To write a program to interface Zigbee module with Arduino UNO and establish the communication
between them.
Hardware Required:
Arduino UNO
XBEE(Zigbee Module)
Software Required:
Arduino IDE
Procedure:

1.XBee is configured as a Coordinator in API mode with API enable set to 1

2.SoftwareSerial of Arduino is used for communication with XBee. Serial of Arduino is used to display
the received data on the serial monitor.

3.Another XBee device is configured as a Router in API mode with API enable set to 1 Use the same
API enable setting for both XBee devices.

4.A switch is connected to pin DIO1 (pin 19 on the module) of the Router (or End Device) XBee
module and the pin is configured as a Digital Input.

5.A potentiometer is given 1.2V and ground to its fixed terminals and the variable terminal of the
potentiometer is connected to pin AD2 (pin 18on the module) of the Router (or End Device) XBee
module and the pin is configured as an Analog Input.

6.IO Sampling (IR) rate can be set according to the requirement of the application, 100 msec for
example.

7.All the configurations and settings are done using X-CTU software provided by Digi International.

8.The Router (or End Device) XBee module sends the IO samples of the potentiometer and the switch
periodically depending on the IR setting. This data is received by the coordinator and the Sketch
uploaded in the Arduino parses the data received and extracts the IO samples information from it.

Page | 56
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 50
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Program:
#include <XBee.h>
#include <SoftwareSerial.h>

#define ssRX 9 /* Rx pin for software serial */


#define ssTX 8 /* Tx pin for software serial */

/* Create object named xbee_ss of the class SoftwareSerial */


SoftwareSerial xbee_ss(ssRX, ssTX); /* Define pins for software serial instance named xbee-ss(any
name of your choice) to be connected to xbee */
/* ssTx of Arduino connected to Din (pin 3 of xbee) */
/* ssRx of Arduino connected to Dout (pin 2 of xbee) */

XBee xbee = XBee(); /* Create an object named xbee(any name of your choice) of the class XBee */

ZBRxIoSampleResponse ioSamples = ZBRxIoSampleResponse();


/* Create an object named ioSamples(any name of your choice) of the class ZBRxIoSampleResponse */

void setup() {
Serial.begin(9600); /* Define baud rate for serial communication */

xbee_ss.begin(9600); /* Define baud rate for software serial communication */

xbee.setSerial(xbee_ss); /* Define serial communication to be used for communication with xbee */


/* In this case, software serial is used. You could use hardware serial as well by writing "Serial" in
place of "xbee_ss" */
/* For UNO, software serialis required so that we can use hardware serial for debugging and
verification */
/* If using a board like Mega, you can use Serial, Serial1, etc. for the same, and there will be no need
for software serial */
}

void loop() {
xbee.readPacket(); /* Read until a packet is received or an error occurs */

if(xbee.getResponse().isAvailable()) /* True if response has been successfully parsed and is complete


*/
{
if(xbee.getResponse().getApiId()==ZB_IO_SAMPLE_RESPONSE) /* If response is of
IO_Sample_response type */
{
xbee.getResponse().getZBRxIoSampleResponse(ioSamples); /* Get the IO Sample Response */

Serial.print("Received I/O Sample from: ");

Page | 51
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 52
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Serial.print(ioSamples.getRemoteAddress64().getMsb(), HEX); /* DH(in HEX format) of the


sending device */
Serial.print(ioSamples.getRemoteAddress64().getLsb(), HEX); /* DL(in HEX format) of the sending
device */
Serial.println("");

if (ioSamples.containsAnalog()) { /* If Analog samples present in the response */


Serial.println("Sample contains analog data");
}

if (ioSamples.containsDigital()) { /* If Digital samples present in the response */


Serial.println("Sample contains digtal data");
}

/* Loop for identifying the analog samples present in the received sample data and to print it */
for (int i = 0; i <= 4; i++) { /* Only 4 Analog channels */
if (ioSamples.isAnalogEnabled(i)) { /* Check Analog channel mask to see if the any pin is enabled
for analog input sampling */
Serial.print("Analog (AI");
Serial.print(i, DEC);
Serial.print(") is ");
Serial.println(ioSamples.getAnalog(i), DEC);
}
}
for (int i = 0; i <= 12; i++) { /* 12 Digital IO lines */
if (ioSamples.isDigitalEnabled(i)) { /* Check Digital channel mask to see if any pin is enabled for
digital IO sampling */
Serial.print("Digital (DI");
Serial.print(i, DEC);
Serial.print(") is ");
Serial.println(ioSamples.isDigitalOn(i), DEC);
}
}
}
else
{
Serial.print("Expected I/O Sample, but got ");
Serial.print(xbee.getResponse().getApiId(), HEX); /* Print response received instead of
IO_Sample_Response */
}
}
else if (xbee.getResponse().isError()) { /* If error detected, print the error code */
Serial.print("Error reading packet. Error code: ");
Serial.println(xbee.getResponse().getErrorCode());
}
}

Page | 53
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 54
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Result:

Thus program to interface Zigbee module with Arduino UNO has been written and established the
communication between them.

Page | 55
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Arduino UNO with GSM module:

Page | 56
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No: 6 b Date:


Aim:
To write a program to interface GSM module with Arduino UNO and establish the communication
between them.
Hardware Required:
Arduino Uno
GSM Modem
Switch
1kΩ Resistor
Breadboard
Connecting Wires
Software Required:
Arduino IDE
Connections

Connect TX pin of GSM Module to RX pin of Arduino Uno.


Connect RX pin of GSM Module to TX pin of Arduino Uno.
Connect GND pin of GSM Module to GND pin of Arduino Uno.

Steps to boot GSM module

1. Power ON the GSM module by providing 5V and GND.


2. Insert the SIM card to GSM module and lock it.
3. Initially blinking rate of network LED will be high. After sometime observe the blinking rate of
‘network LED’ (GSM module will take some time to establish connection with mobile network)
4. Once the connection is established successfully, the network LED will blink continuously for
every 3 seconds.
5. Even we can check the connection establishment of GSM module with mobile by making a call
to the number of the SIM. If we hear a ring back, the GSM module has successfully established
network connection.

Page | 57
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 58
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Program:

const int Input1=8;


int State1=0; void setup(){
Serial.begin(9600);
pinMode(Input1, INPUT);
}
void loop(){
State1= digitalRead(Input1);

if(State1 == HIGH)
{
sendsms();
delay(2000);
}
}
void sendsms()
{
Serial.println("AT\r"); //AT is the abbreviation of Attention. Checking communication.
delay(1000);
Serial.println("AT+CMGF=1\r"); // To set the modem in SMS sending mode.
delay(1000);
Serial.println("AT+CMGS=\"XXXXXXXXXX\"\r"); // For sending SMS to a number.
delay(1000);
Serial.println("MESSAGE 1"); // Message to send
delay(1000);
Serial.println((char)26); // End command for SMS a^Z, ASCII code 26.
delay(100);
}

Result:
Thus thea program to interface GSM module with Arduino UNO has been written and established the
communication between them.

Page | 59
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Interfacing Bluetooth module with Arduino UNO:

Page | 60
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No: 6 c Date:


Aim:
To write a program to interface Bluetooth module with Arduino UNO and establish the communication
between them.
Hardware Required:
Arduino Uno
HC-05 Blue Tooth Module
Connecting Wires
LED
220 ohm resistor
Software Required:
Arduino IDE
Description:

First we need to define the pin to which our LED will be connected and a variable in which we will store
the data coming from the smartphone. In the setup section we need to define the LED pin as output and
set it low right away. As mention previously, we will use the serial communication so we need to begin
the serial communication at 38400 baud rate, which is the default baud rate of the Bluetooth module. In
the loop section with the Serial.available() function we will check whether there is available data in the
serial port to be read. This means that when we will send data to the Bluetooth module this statement will
be true so then using the Serial.read() function we will read that data and put it into the “state” variable.
So if the Arduino receive the character ‘0’ it will turn the LED off and using the Serial.println() function
it will send back to the smartphone, via the serial port, the String “LED: OFF”. Additionally we will reset
the “state” variable to 0 so that the two above lines will be executed only once. Note here that the “state”
variable is integer, so when we receive the character ‘0’ that comes from smartphone, the actual value of
the integer “state” variable is 48, which corresponds to character ‘0’, according to the ASCII table.. That’s
why in the “if” statement we are comparing the “state” variable to a character ‘0’. On the other hand, if
the received character is ‘1’, the LED will light up and the String “LED: ON” will be sent back.

Now the code is ready to be uploaded but in order to do that we need to unplug the TX and RX lines
because when uploading the Arduino uses the serial communication so the pins RX (digital pin 0) and TX

Page | 61
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 62
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

(digital pin1) are busy. We can avoid this step if we use the other TX and RX pins of the Arduino Board,
but in that case we will have to use the SoftwareSerial.h library for the serial communication.

Program:

#include<SoftwareSerial.h>

/* Create object named bt of the class SoftwareSerial */


SoftwareSerial bt(2,3); /* (Rx,Tx) */

void setup() {
bt.begin(9600); /* Define baud rate for software serial communication */
Serial.begin(9600); /* Define baud rate for serial communication */
}

void loop() {

if (bt.available()) /* If data is available on serial port */


{
Serial.write(bt.read()); /* Print character received on to the serial monitor */
}
}

Result:

Thus a program to interface Bluetooth module with Arduino UNO has been written and established the
communication between them

Page | 63
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Pin Diagram of Raspberry Pi:

Page | 64
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No: 7 Date:


Aim:
To study the basics of Raspberry PI platform and python programming.

Introduction:
Raspberry Pi is defined as a minicomputer the size of a credit card that is interoperable with any
input and output hardware device like a monitor, a television, a mouse, or a keyboard – effectively
converting the set-up into a full-fledged PC at a low cost.

Pin Description:
The various components/peripherals present in Raspberry pi are as follows
1. Central Processing Unit (CPU)
Every computer has a Central Processing Unit, and so does the Raspberry Pi. It is the computer’s
brain and carries out instructions using logical and mathematical operations. Raspberry Pi makes
use of the ARM11 series processor on its boards.
2. HDMI port
Raspberry Pi board has an HDMI or High Definition Multimedia Interface port that allows the
device to have video options of the output from the computer displayed. An HDMI cable
connects the Raspberry Pi to an HDTV. The supported versions include 1.3 and 1.3. It also comes
with an RCA port for other display options.
3. Graphic Processing Unit (GPU)
This unit, GPU or Graphic Processing Unit, is another part of the Raspberry pi board. Its primary
purpose is to hasten the speed of image calculations.
4. Memory (RAM)
Random Access Memory is a core part of a computer’s processing system. It is where real -
time information is stored for easy access. The initial Raspberry Pi had 256MB RAM. Over the
years, developers gradually and significantly improved the siz e. Different Raspberry Pi models
come with varying capacities. The model with the maximum capacity presently is the Raspberry Pi
4 with 8GB RAM space.
5. Ethernet port
The Ethernet port is a connectivity hardware feature available on B models of Raspberry Pi.
The Ethernet port enables wired internet access to the minicomputer. Without it, software updates,
web surfing, etc., would not be possible using the Raspberry Pi. The Ethernet port found on
Raspberry computers uses the RJ45 Ethernet jack. With this component, Raspberry Pi can connect
to routers and other devices.

Page | 65
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 66
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

6. SD card slot
Like most other regular computers, Raspberry Pi must have some sort of storage device. However,
unlike conventional PCs, it does not come with a hard drive, nor does it come with a memory card.
The Raspberry Pi board has a Secure Digital card or SD card sl ot where users must insert SD cards
for the computer to function. The SD card functions like a hard drive as it contains the operating
system necessary for turning the system on. It also serves to store data.
7. General Purpose Input and Output (GPIO) pins
These are upward projecting pins in a cluster on one side of the board. The oldest models of the
Raspberry Pi had 26 pins, but most have 40 GPIO pins. These pins are pretty sensitive and should
be handled carefully. They are essential parts of the Raspb erry Pi device as they add to its
diverse applications. GPIO pins are used to interact with other electronic circuits. They can read and
control the electric signals from other boards or devices based on how the user programs them.
8. LEDs
These are a group of five light-emitting diodes. They signal the user on the present status of
the
Raspberry Pi unit. Their function covers:
PWR (Red): This functions solely to indicate power status. When the unit is on, it emits a red light
and only goes off when the unit is switched off, or disconnected from the power source.
ACT (Green): This flashes to indicate any form of SD card activity.
LNK (Orange): LNK LED gives off an orange light to signify that active Ethernet connectivity
has been established.
100 (Orange): This light comes on during Ethernet connection when the data speed reaches
100Mbps . FDX (Orange): FDX light also comes during Ethernet connection. It shows that the
connection is a full-duplex.
9. USB ports
Universal service bus (USB) ports are a principal part of Raspberry Pi. They allow the computer to
connect to a keyboard, mouse, hard drives, etc. The first model of Raspberry Pi had only two USB
2.0 ports. Subsequent models increased this number to four. Raspberry Pi 4 and Pi 400, much newer
models , come with a mix of USB 2.0 and USB 3.0 ports.
10. Power source
Raspberry Pi has a power source connector that typically uses a 5V micro USB power cable. The
amount of electricity any Raspberry Pi consumes depends on what it’s used for and the number of
peripheral hardware devices connected.

Page | 67
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

When you open Mu for the first time, you’ll be given the option to select the Python mode for the
editor. For the code in this tutorial, you can select Python 3:

Raspberry Pi Icon → Preferences → Recommended Software

This will open up a dialogue containing recommended software for your Raspberry Pi. Check the box
next to Mu and click OK to install it:

Page | 68
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Running Python on the Raspberry Pi


One of the best things about working with Python on the Raspberry Pi is that Python is a first-class
citizen on the platform. The Raspberry Pi Foundation specifically selected Python as the main
language because of its power, versatility, and ease of use. Python comes preinstalled on Raspbian, so
you’ll be ready to start from the get-go.

You have many different options for writing Python on the Raspberry Pi. In this tutorial, you’ll look
at two popular choices:

Using the Mu editor


Editing remotely over SSH

Let’s start by looking at using the Mu editor to write Python on the Raspberry Pi.

Using the Mu Editor


The Raspbian operating system comes with several preinstalled Python IDEs that you can use to write
your programs. One of these IDEs is Mu. It can be found in the main menu:

Raspberry Pi Icon → Programming → Mu

While Mu provides a great editor to get started with Python on the Raspberry Pi, you may want
something more robust. In the next section, you’ll connect to your Raspberry Pi over SSH.

Result:
Thus basics of Raspberry pi and p ython program has been studied

Page | 69
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Circuit Diagram:

Page | 70
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No: 8 Date:


Aim:
To write a Python program to interface Light sensor with Raspberry Pi
Hardware Required:
Raspberry pi 4
Breadboard
Photoresistor LDR
Jumper wires
1uF Capacitor
Software Required:
Python
Procedure:
1. To begin, attach Pin1 of RPi4 to the breadboard's positive rail.
2. Then, attach pin 6 of RPi4 to the breadboard's ground rail.
3. Next, place the LDR sensor on the board with one end connected to the power supply's positive
rail.
4. Connect the opposite end of the LDR sensor to the Pin4 of RPi4 using a jumper wire.

Page | 71
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 72
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Program:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
ldr_threshold = 1000
LDR_PIN = 18
LIGHT_PIN = 25

def readLDR(PIN):
reading = 0
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(PIN, false)
time.sleep(0.1)
GPIO.setup(PIN, GPIO.IN)
while (GPIO.input (PIN) ==Flase):

reading=reading+1

return reading

def switchOnLight(PIN):
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, True)

def switchOffLight(PIN):
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, False)

Page | 73
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 74
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

while True:
ldr_reading = readLDR(LDR_PIN)
if ldr_reading < ldr_threshold:
switchOnLight (LIGHT_PIN)
else:
switchOffLight(LIGHT_PIN)
time.sleep(1)

Result:

Thus light sensor is interfaced with Raspberry pi 4 using Python Programming.

Page | 75
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 76
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No: 9 Date:


Aim:
To write a Python program to communication Arduino UNO with Raspberry Pi 4 using wireless
medium.
Hardware Required:

Ultrasonic Sensor

2 Arduino Uno

Raspberry Pi 3

2 nRF24l01 transmitter and receiver

Jump wires

Arduino cable

MINI USB 2.0 for Pi

Breadboard

Software Required:

Raspbian for pi

Arduino IDE

Putty on a remote computer for SSH

VNC viewer on a remote computer

Page | 77
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Components Specifications:

1.4 GHz 64-bit quad-core ARM Cortex-A53, 1GB RAM

2.4/5Ghz dual-band 802.11ac Wireless LAN, 10/100/1000Mbps Ethernet Bluetooth 4.2

4 USB ports, Full HDMI port, Combined 3.5mm audio jack and composite video port, 40 GPIO
pins

Micro SD card slot, Video Core IV 3D graphics core, Camera interface (CSI), Display interface

(DSI)

Raspberry Pi Pinout:

Page | 78
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Headless Raspberry Pi Setup:

Say, I just bought a raspberry pi and wish to check out how it works. But all I have is my Laptop,
the Pi, a micro SD card, and my Wi-Fi network. How do I connect and control the Pi?

1) Download Raspbian:

Your Pi needs an OS. Download Raspbian from Raspberrypi.org ‘s download section:

https://www.raspberrypi.org/downloads/raspbian/

2) Download SD Memory Card Formatter:

It is used to format the SD card as it is needed that the SD card should be empty before the
flashing image you downloaded. You can download it

from https://www.sdcard.org/downloads/formatter/eula_windows/

Page | 79
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

3) Flash it onto an SD card:

You need to flash this downloaded image to the micro SD card. Assuming your laptop has an SD
card slot or a micro Sd card reader, you need a flashing software like etcher. Go ahead and

download from https://etcher.io/

Page | 80
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

4) Configure Wi-Fi:

It’s easier to make two devices talk to each other if they are in the same network. An ethernet
cable can easily make your laptop’s network available to the Pi. But we don’t have one. So, we

are going to add a file to the SD card so that the Pi boots with a wifi pre-configured.

The SD card mounts as two volumes boot and rootfs . Open the boot volume and create a file

named wpa_supplicant.conf on booting the RPi, this file will be copied to /etc/wpa_supplicant

directory in /rootfs partition. The copied file tells the Pi the WIFI setup information. This would

overwrite any existing WIFI configuration, so if you had already configured WIFI on the pi, then

that will be overwritten.

A typical wpa_supplicant.conf file is as follows:


ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdevupdate_config=1country=US
network={ ssid="«your_SSID»" psk="«your_PSK»" key_mgmt=WPA-PSK}

NOTE: Your SSID is your WIFI’s name. And psk is the password of the WI-FI.

5) Enable SSH

We will later access the Pi using a secured shell (SSH), SSH is disabled by default in Raspbian.

To enable SSH, create a file named ssh in the boot partition. If you are on Linux, use the touch

command to do that.

Page | 81
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

6) Find Pi’s Ip address:

Before switching on your raspberry pi, we need to find out the existing devices connected to the

network. Make sure your laptop is connected to the same WIFI network as the one you configured

on pi above.

Download the Advanced IP Scanner to scan the IP of our raspberry pi. You can download it from
here https://www.advanced-ip-scanner.com/

Page | 82
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

7) SSH into your Pi:

To create a secured shell connection in Linux we can use the ssh command. If you are on windows,

try downloading Putty from https://www.putty.org/

Page | 83
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Default credentials are:


username: pipassword: raspberry

8) Access Pi remotely:

Sometimes it doesn’t feel right if we can’t use the mouse. For that, we need to look into the
Raspbian desktop.

We need to setup VNC (Virtual Network Connection) to see and control Pi graphically. Let’s do

that.

To access the remote desktop, you need VNC-viewer (client) for your laptop. Fortunately,
RealVNC is available for a lot of OSes, pick one for your OS

from https://www.realvnc.com/en/connect/download/viewer/

Page | 84
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

9) Commands for vncserver:

10) Now open VNC Viewer on your remote computer:

Page | 85
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

5. Implementation and Working:

5.1. Wireless communication of Arduino to Arduino with nRF24L01:

In this, we will learn how to make wireless communication between two Arduino boards using the

NRF24L01. And measure distance with ultrasonic sensor and transmit it to another Arduino with

transceiver module.

Wiring Instructions:

To wire your NRF24L01+ wireless Sender to your Arduino, connect the following pins:

Connect the VCC pin to 3.3 Volts

Connect the GND pin to ground (GND)

Page | 86
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Connect the CE pin to Arduino 9

Connect the CSN pin to Arduino 10

Connect the SCK pin to Arduino 13

Connect the MOSI pin to Arduino 11

Connect the MISO pin to Arduino 12

To wire your ultrasonic sensor to your Arduino, connect the following pins:

Connect the VCC pin to Arduino 5Volts

Connect the GND pin to ground (GND)

Connect the Trig pin to Arduino 4

Connect the Echo pin to Arduino 3

Page | 87
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Schematic Diagram for wiring of Arduino Uno with ultrasonic sensor and NRF24L01

To wire your NRF24L01+ wireless sender to your Arduino, connect the following pins:

Connect the VCC pin to 3.3 Volts

Connect the GND pin to ground (GND)

Connect the CE pin to Arduino 9

Connect the CSN pin to Arduino 10

Connect the SCK pin to Arduino 13

Connect the MOSI pin to Arduino 11

Page | 88
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Connect the MISO pin to Arduino 12

Schematic Diagram for wiring of Arduino Uno NRF24L01

NOTE: RF24 module is mandatory for the code to run so you can add the library accordingly

Start Arduino IDE then add the Downloaded Library from Here :

Page | 89
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 90
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Sender Code:

#include
<SPI.h>
#include "RF24.h"
RF24 myRadio (9, 10);
byte addresses[][6] = {"0"};
const int TriggerPin = 4; //Trig pin
const int EchoPin = 3; //Echo pin
long Duration = 0;
struct package
{
int id = 1;
float temperature = 18.3;
char text[100] = "Text to be transmitted";
};
typedef struct package Package;
Package data;
void setup()
{
pinMode(TriggerPin, OUTPUT); // Trigger is an output pin
pinMode(EchoPin, INPUT); // Echo is an input pin
Serial.begin(115200);
delay(1000); myRadio.begin();
myRadio.setChannel(115);
myRadio.setPALevel(RF24_PA_MAX);
myRadio.setDataRate( RF24_250KBPS ) ;
myRadio.openWritingPipe( addresses[0]);
delay(1000);
}

Receiver Code:

#include
<SPI.h>
#include "RF24.h"
RF24 myRadio (9,10);
struct package
{
int id=0;
float temperature = 0.0;
char text[100] ="empty";
};

Page | 91
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

byte addresses[][6] = {"0"};


typedef struct package Package;
Package data;
void setup()
{
Serial.begin(115200);
delay(1000);
myRadio.begin();
myRadio.setChannel(115);
myRadio.setPALevel(RF24_PA_MAX);
myRadio.setDataRate( RF24_250KBPS ) ;
myRadio.openReadingPipe(1, addresses[0]);
myRadio.startListening();
}
void loop()
{
if ( myRadio.available())
{
while (myRadio.available())
{
myRadio.read( &data, sizeof(data) );
}
Serial.print("\nPackage:");
Serial.print(data.id);
Serial.print("\n");
Serial.println(data.temperature);
Serial.println(data.text);
}
}

Page | 92
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Sending the Data

Receiving the data:

Result:
Thus the program to communicate Arduino and Raspberry pi has been written and data is
communicated without any wired medium.
Page | 93
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Page | 94
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No:10 Data:

Aim:

To create a Log Data using Raspberry PI and upload to the cloud platform

Components Required:

1. Raspberry Pi
2. Power Cable
3. WiFi or Internet

Steps for building Raspberry Pi Data Logger on Cloud


Step 1: Signup for ThingSpeak
For creating your channel on ThingSpeak you first need to sign up on ThingSpeak. In case if you
already have account on ThingSpeak just sign in using your id and password.
For creating your account go to www.thinspeak.com

Page | 95
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Click on signup if you don’t have account and if you already have account click on sign in.
After clicking on signup fill your details.

After this verify your E-mail id and click on continue.

Step 2: Create a Channel for Your Data


Once you Sign in after your account verification, Create a new channel by clicking “New Channel”
button

Page | 96
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

After clicking on “New Channel”, enter the Name and Description of the data you want to upload on
this channel. For example I am sending my CPU data (temperature), so I named it as CPU data.
Now enter the name of your data (like Temperature or pressure) in Field1. If you want to use more
than one Field you can check the box next to Field option and enter the name and description of your
data.
After this click on save channel button to save your details.

Step 3: Getting API Key in ThingSpeak


To send data to ThingSpeak, we need an unique API key, which we will use later in our python code
to upload our CPU data to ThingSpeak Website.
Click on “API Keys” button to get your unique API key for uploading your CPU data.

Now copy your “Write API Key”. We will use this API key in our code.

Page | 97
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Step 4: Python Code for Raspberry Pi


Complete code is given at the end of this tutorial, just make a file with any name and .py extension
and copy-paste the code and save the file. Don’t forget to replace the API key with yours. You can
run the python file any time using below command:

python /path/filename.py

Assuming you already installed python in Raspberry pi using this command

sudo apt-get install python

Case 1: If you are using monitor screen then just use the given code.
Now install all libraries:

sudo apt-get install httplib


sudo apt-get install urllib

After installing libraries run your python code (python /path/filename.py)


If the code runs properly you will see some CPU temperature values as shown in below image.

Page | 98
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

If there are any errors uploading the data, you will receive “connection failed” message.

Case 2: If you are using “Putty” then you should follow these commands:
First update your pi using:

sudo apt-get update

After this make a file cpu.py using:

nano cpu.py

After creating this file copy your code to this file and save it using CTRL + X and then ‘y’ and Enter.
After this install all libraries using:

sudo apt-get install httplib


sudo apt-get install urllib

Page | 99
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

After installing libraries run your python code using:

python cpu.py

If the code runs properly you will see some CPU temperature values as shown in above image.

Step 6: Check ThingSpeak site for Data Logging


After completing these steps open your channel and you will see the CPU temperature data is
updating into ThingSpeak website.

Like this you can send any sensor data connected with Raspberry pi to the ThingSpeak Cloud. In
next article we will connect LM35 temperature sensor with Raspberry Pi and send the temperature
data to ThingSpeak, which can be monitored from anywhere.
Complete Python code for this Raspberry Pi Cloud Server is given below. Code is easy and
self- explanatory to understand.

Page | 100
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Code
import httplib
import urllib
import time
key = "ABCD" # Put your API Key here
def thermometer():
while True:
#Calculate CPU temperature of Raspberry Pi in Degrees C
temp = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3 # Get Raspberry Pi CPU
temp
params = urllib.urlencode({'field1': temp, 'key':key })
headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print temp
print response.status, response.reason
data = response.read()
conn.close()
except:
print "connection failed"
break
if name == " main ":
while True:
thermometer()

Result:

Thus log data has been created using Raspberry Pi and uploaded it in the cloud platform

Page | 101
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Circuit Diagram:

Page | 102
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Exp No:11 Date:

Aim:

To write a Arduino program for smart home automation system using Bluetooth.

Components Required:

Arduino UNO (or Mega, Pro, Mini – but in this tutorial we use the UNO)

Relay module

HC 05 Wireless Bluetooth Module

Lamp

2.2k ohm resistor

1k ohm resistor

Breadboard

Jumper wires

Description:

To develop a home automation system using an Arduino board with Bluetooth being remotely
controlled by any Android OS smart phone. As technology is advancing so houses are also getting
smarter. Modern houses are gradually shifting from conventional switches to centralized control
system, involving remote controlled switches. Presently, conventional wall switches located in
different parts of the house makes it difficult for the user to go near them to operate. Even more it
becomes more difficult for the elderly or physically handicapped people to do so. Remote controlled
home automation system provides a most modern solution with smart phones. In order to achieve
this, a Bluetooth module is interfaced to the Arduino board at the receiver end while on the
transmitter end, a GUI application on the cell phone sends ON/OFF commands to the receiver where
loads are connected. By touching the specified location on the GUI, the loads can be turned ON/OFF
remotely through this technology.

Page | 103
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

Connection procedure:

1) Connect the Arduino’s +5V and GND pins to the bus strips on the breadboard, as shown in the
above circuit diagram.
2) Power the HC-05 module by connecting the 5V and GND pins to the bus strips on the breadboard.
The HC-05 is powered using 5VDC but includes an on-board voltage regulator that generates a 3.3V
supply to power the transceiver. This means the TXD/RXD pins operate at only 3.3V.

3) Connect the TXD pin on the HC-05 module with the RXD pin (Pin 0) on the Arduino. This
connection allows the HC-05 to send data to the Arduino.
The reason why we pair up TXD on the Bluetooth module with RXD on the Arduino is because the
TXD pin is used to transmit data from the Bluetooth transceiver, while the RXD pin is used to receive
data on the Arduino.

Although the Arduino is using 5V signal levels, and the HC-05 is using only 3.3V signal levels, no
level shifting is required on this particular signal.

This is because the Arduino is based on an ATmega328 microcontroller which defines a logic high as
any level above 3V. So no level shifting is necessary when going from 3.3V to 5V.

However, that isn’t always true when going the other direction from 5V to 3,3V as we’ll discuss in the
next step.

4) Now we need to connect the TXD pin on the Arduino to the RXD pin on the HC-05.
This connection will form the second half of the two-way communication and is how the Arduino
sends information to the HC-05.

Since the receiver data lines on the HC-05 are only 3.3V tolerant, we need to convert the 5V transmit
signal coming from the Arduino into a 3.3V signal.

While this is usually best done using a logic level converter, we’re instead just using a simple voltage
divider to convert the 5V signal into a 3.3V signal.

Page | 104
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

As shown in the circuit diagram, we’ve connected a 1k ohm and a 2.2k ohm resistor across the GND
and TXD pins on the Arduino.

This is called a resistor divider because it divides down the input voltage. We obtain the 3.3V level
signal from the intersection of these two resistors.

The equation for a divided down voltage is Vout = [2.2k/(2.2k + 1k)]*5V = (2.2k/3.2k)*5V = 3.46V,
which is close enough to 3.3V to prevent any damage to the HC-05.

This crude solution should never be used with a high-speed signal because the resistors form a low-
pass RC filter with any parasitic capacitance on the connection.

Once you have connected the HC-05 module to the Arduino, you can power the Arduino with a 12V
DC supply or USB cable.

If the red and blue LEDs on the HC-05 are blinking, then you have successfully connected the
Bluetooth module with the Arduino.

We don’t use the STATE and EN pins on the HC-05 module, since they are not required for this
setup.

Setting up the Relay Circuit:

Page | 105
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

The next step is to connect the Arduino to a relay module, so that we can turn the connected device
ON/OFF.

As shown in the circuit diagram above, we’ll be connecting the relay module in series with our
electrical load, so that we can break the connection when we want to turn the device off and complete
the circuit when we want to turn it on.

For this application we’re using a relay module which includes the relay drive circuit allowing it to
connect directly to a microcontroller GPIO pin.The relay module we’re using can handle up to 10
amps of current at up to 240V AC.

How to connect the relay module to the Arduino:


1) First, connect the 5V and GND pins of the relay module to the bus terminals on the breadboard.
2) Next, connect the IN1 pin on the relay module with PIN 4 on the Arduino.
If you have a multi-channel module (2, 4 or 8 channels), you can connect IN2, IN3 … In(n) with
different digital pins on the Arduino, and repeat the steps below for configuring the other pins.

3) Now we need to connect the AC load to the relay module. If you look carefully at the terminal
block on the relay module, you’ll find these three terminals:
C: Common
NC: Normally Closed
NO: Normally Open

Here’s how the relay module works:

Page | 106
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

When the relay is off, the COM terminal is connected to the NC (Normally Closed) terminal, which
means if you connect the bulb to the NC terminal, it will turn ON even when the relay isn’t energized.

But that’s not what we want. We want to turn on the bulb only when we send a signal from
smartphone.
That’s the reason we connect the load to the NO (Normally Open) terminal, so that when the relay is
triggered from the Arduino, the contact switches from the NC terminal to the NO terminal, thereby
completing the circuit.

Program:

#define RELAY_ON 0
#define RELAY_OFF 1
#define RELAY_1 4
char data = 0;
void setup() {
// Set pin as output.
pinMode(RELAY_1, OUTPUT);
// Initialize relay one as off so that on reset it would be off by default
digitalWrite(RELAY_1, RELAY_OFF);
Serial.begin(9600);
Serial.print(“Type: 1 to turn on bulb. 0 to turn it off!”);
}
void loop() {
if (Serial.available() &gt; 0) {
data = Serial.read(); //Read the incoming data and store it into variable data
Serial.print(data); //Print Value inside data in Serial monitor
Serial.print(“\n”); //New line
if(data == ‘1’){
digitalWrite(RELAY_1, RELAY_ON);
Serial.println(“Bulb is now turned ON.”);
}
else if(data == ‘0’)
{
Page | 107
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

digitalWrite(RELAY_1, RELAY_OFF);
Serial.println(“Bulb is now turned OFF.”);
}
}
}

Controlling the bulb from your Android device


Now that we have setup the hardware and successfully uploaded the code, the next step is to control the
setup from a smartphone.

In order to that, you’ll need to download the Arduino Bluetooth Controller app on your Android
device. Here’s how to configure your Android device to send commands to the Arduino:

1) Open the app on your smartphone. It will ask for Bluetooth permissions. Click
‘Allow’.

Page | 108
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

2) Next, it will list all the available devices in your vicinity. Select HC-05.

3) Once you select the device, you’ll be connected to the HC-05 transceiver. The app will now
prompt you to enter the mode that you wish to use. Select ”Switch” mode.

Page | 109
PRATHYUSHA ENGINEERING COLLEGE
CS3691-EMBEDDED SYSTEM & IOT DEPARTMENT OF CSE

4) You should be redirected to the following screen. Click on the “Settings” icon in the top-right corner
of the screen.

5) It will now ask you to set values for ON and OFF. Enter ‘1’ in the ON textbox and ‘0’ in the OFF
textbox. Click Submit.

Result:

Thus an Arduino program has been written to control the home automation systems using Bluetooth.

Page | 110
PRATHYUSHA ENGINEERING COLLEGE

You might also like