0% found this document useful (0 votes)
21 views52 pages

CS3691 Es and Iot

The document is a laboratory record for the CS3691 Embedded Systems and IoT course at Aishwarya College of Engineering and Technology. It includes various experiments related to 8051 Assembly Language, data transfer operations, ALU operations, and programming with Embedded C, Arduino, and Raspberry Pi. Each experiment outlines the aim, required software, procedure, and results, indicating successful execution of the tasks.

Uploaded by

Divya Priya
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)
21 views52 pages

CS3691 Es and Iot

The document is a laboratory record for the CS3691 Embedded Systems and IoT course at Aishwarya College of Engineering and Technology. It includes various experiments related to 8051 Assembly Language, data transfer operations, ALU operations, and programming with Embedded C, Arduino, and Raspberry Pi. Each experiment outlines the aim, required software, procedure, and results, indicating successful execution of the tasks.

Uploaded by

Divya Priya
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/ 52

AISHWARYA COLLEGE OF

ENGINEERING AND TECHNOLOGY


ERODE–638312
[[

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

CS3691 – EMBEDDED SYSTEMS AND IOT


LABORATORY

SIXTH SEMESTER
(REGULATION 2021)

LABORATORYRECORD

NameRegist :
erNo. :

Class :
Subject&Code : _
AISHWARYA COLLEGE OF
ENGINEERING AND TECHNOLOGY
ERODE–638312
[[

Department of Computer Science


and Engineering

LABORATORY RECORD
Name:……………………………………………… RollNo : …………………………

Reg.No: ……………………………………………… Year/Sem :………………………....

Certified that this is the Bonafide Record of work done by the above student in the

......................................................................................................................... Laboratory during

the year…………………..

STAFF INCHARGE HEAD OF THE DEPARTMENT

Submitted for the University Practical Examination held on

INTERNAL EXAMINER EXTERNAL EXAMINER


CONTENTS
PAGE
EX.NO DATE NAMEOFTHEEXPERIMENT MARKS SIGN
NO.
Write 8051 Assembly Language
1 experiments using simulator

Test data transfer between


2 registers and memory

Perform ALU operations


3

Write Basic and arithmetic


4 Programs Using Embedded C

Introduction to Arduino platform


5 and programming

Explore different communication


6 methods with IoT devices
(Zigbee, GSM, Bluetooth)
Introduction to Raspberry PI
7 platform and python programming
Interfacing sensors with Raspberry PI
8
Communicate between Arduino and
Raspberry PI using any wireless medium
9

Setup a cloud platform to log the


data
10
Log Data using Raspberry PI and
upload to the cloud platform
11
12 Design an IOT based system

AVERAGE: __________
ExpNo:01
Date:
Write 8051 Assembly Language experiments using simulator.
Aim:
To write 8051 Assembly Language Experiments using Simulator.

SOFTWARE REQUIRED:
1. Keil uVision IDE

Theory:

General Block Diagram of 8051 Microcontroller Architecture

4
STEPS TO CREATE AND COMPILE Keil µVision-3/4 PROJECT:

5
6
Procedure:
Procedure:
1. Launch the Simulator
2. Write the Assembly Program and save it with .asm extension
3. Click the build target option from project menu to assemble the program
4. Click the Debug menu to Start/Stop Debug Session
5. Press STEP button to single step the Program

7
8051 Assembly Language Experiments

a. Write an assembly language program to find the square of a given


number N.
Let N = 06
mov a,#06 // a=N=06
mov b,a
mul ab
mov 30h,a // result is stored in 30h and 31h
mov 31h,b
end

Result:

b. Write an assembly language program to find the cube of a given


number.
mov r0,#0fh // r0 = given number to find the cube of it.
mov a,r0
mov b,r0
mul ab
mov r1,b
mov b,r0
mul ab
mov 32h,a
mov r2,b
mov a,r1
mov b,r0
mul ab
add a,r2
mov 31h,a
mov a,b
addc a,#00h
mov 30h,a //result is stored in 30h, 31h, 32h
end

8
Result:

c. Write an assembly language program to perform logical operations


AND, OR, XOR on two eight bit numbers -45h & 67h

/ / Logical operations between two 8-bit numbers//


mov a,#45h //1st number 0100 0101
mov r0,#67h //2nd number 0110 0111
anl a,r0 //AND Logic 0100 0101
mov 20h,a // saving and result with 20h memory
mov a,#45h
orl a,r0 //OR Logic 0110 0111
mov 21h,a // saving and result with 21h memory
mov a,#45h
xrl a,r0 //XOR Logic 0010 0010
mov 22h,a // saving and result with 22h memory
mov a,#45h
cpl a //NOT LOGIC 1011 1010
mov 23h,a // saving and result with 23h memory
end

Result:

9
Result:
Thus the 8051 Assembly language experiments using Keil IDE was executed and
simulation results were verified.

10
ExpNo:02
Date:
TEST DATA TRANSFER BETWEEN REGISTERS AND MEMORY

Aim:To perform data transfer operations between registers and memory in 8051
microcontroller.

Simulator:Use any 8051 simulator of your choice (e.g., Keil uVision, Proteus, etc.)

Procedure:
1. Open the simulator and create a new 8051 Assembly project.
2. Write the assembly code to perform data transfer operations between registers and
memory.
3. Assemble the code and load it onto the 8051 microcontroller in the simulator.
4. Run the simulation and observe the data transfer operations.

ORG 0x0000 ; Start of code memory


MOV R0, #0x55 ; Load a value into register R0 ; Data transfer from register to
memory
MOV A, R0 ; Move the value from R0 to accumulator A
MOV @R1, A ; Move the value from A to the memory location pointed by R1;
Data transfer from memory to register
MOV A, @R1 ; Move the value from the memory location pointed by R1 to
accumulator A
MOV R2, A ; Move the value from A to register R2 ; Verify data transfer
MOV R3, #0x00 ; Clear R3 for comparison
CJNE R2, R3, NOT_MATCH ; Compare R2 with 0x00, jump to NOT_MATCH if not
equal
SJMP MATCH ; Jump to MATCH if R2 is equal to 0x00
NOT_MATCH:
; Insert code here to handle the case when data transfer is not successful (optional)
SJMP END
MATCH:
; Insert code here to handle the case when data transfer is successful (optional)
END:
SJMP $ ; Infinite loop ; Define memory locations for data transfer testing
R1: DB 0x30 ; Memory location to store data transferred from register

11
Output:

In this experiment, we will perform data transfer operations between registers and memory
using the 8051 microcontroller.

The code starts by loading a value (0x55) into the register R0.
Then, it transfers the value from R0 to the memory location pointed by R1 using the
accumulator (A) as an intermediate storage location.

Next, it transfers the value from the memory location pointed by R1 back to the register
R2, again using the accumulator (A) as an intermediate storage location.

The code then compares the value in R2 with 0x00. If the data transfer is successful, R2
should be equal to 0x00 (assuming the memory location R1 initially contains 0x00).

Depending on the result of the comparison, you can add code inside the MATCH and
NOT_MATCH sections to handle the success or failure of the data transfer (optional).

The code ends with an infinite loop to keep the microcontroller running indefinitely.

Note: The memory location R1 (address 0x30) is used for data transfer testing. Make sure
to adjust the memory location and values as needed for your specific simulation
environment.Top of Form

Result:
Thus the experiment was executed successfully.

12
EXP. NO: 03
DATE:
PERFORM ALU OPERATIONS
Aim:
To write 8051 Assembly Language program to Perform ALU operations.

SOFTWARE REQUIRED:
1. Keil uVision IDE
Theory:

General Block Diagram of 8051 Microcontroller Architecture

Procedure:
1. Launch the Simulator
2. Write the Assembly Program and save it with .asm extension
3. Click the build target option from project menu to assemble the program
4. Click the Debug menu to Start/Stop Debug Session
5. Press STEP button to single step the Program
Arithmetic Instruction Programming
a. Write an assembly language program to perform the addition of two
16-bit numbers.
/program to add 16bit numbers and storing the result in 40h and 41h location
// 1173
/// +2493
/// --------
// 3606
org 00h
mov a, #73h
13
mov r0, #93h
add a, r0
mov 41h,a
mov a, #11h
mov r0, #24h
add a, r0
mov 40h,a
end
Result:
Before Execution:

After Execution:

14
c. Write an assembly language program to perform the multiplication of
two 16-bit numbers.
mov r0,#34h // 5678*1234
mov r1,#12h
mov r2,#78h
mov r3,#56h
mov a,r0
mov b,r2
mul ab
mov 33h,a
mov r4,b
mov a,r0
15
mov b,r3
mul ab
add a,r4
mov r5,a
mov a,b
addc a,#00h
mov r6,a
mov a,r1
mov b,r2
mul ab
add a,r5
mov 32h,a
mov a,b
addc a,r6
mov 00h,c
mov r7,a
mov a,r3
mov b,r1
mul ab
add a,r7
mov 31h,a
mov a,b
addc a,20h
mov 30h,a
end

Result After Execution:

16
Result:
Thus the 8051 Assembly Language Program to perform ALU operation is
executed successfully.

17
EXP. NO :4
DATE :

BASIC ARITHMETIC PROGRAMS USING EMBEDDED C

AIM:
to check the number is prime or not

1.Program to check if a number is prime or not:

#include <stdio.h>
#include <stdbool.h>
bool is_prime(int num) {
if (num <= 1)
return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return false;
}
return true;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (is_prime(num))
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}

2.Program to find the greatest common divisor (GCD) of two numbers:

#include <stdio.h>
int gcd(int num1, int num2) {
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
return num1;
}

18
int main()
{
int num1, num2;
printf("Enter the first number: ");
scanf("%d", &num1);
printf("Enter the second number: ");
scanf("%d", &num2);
int result = gcd(num1, num2);
printf("GCD: %d\n", result);
return 0;
}

3.Program to calculate the power of a number using recursion:

#include <stdio.h>
int power(int base, int exponent) {
if (exponent == 0)
return 1;
else
return base * power(base, exponent - 1);}
int main() {
int base, exponent;
printf("Enter the base: ");
scanf("%d", &base);
printf("Enter the exponent: ");
scanf("%d", &exponent);
int result = power(base, exponent);
printf("%d^%d = %d\n", base, exponent, result);
return 0;
}

4.Program to find the factorial of a number without using recursion:

#include <stdio.h>
int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
int main() {
int num;
printf("Enter a number: ");
19
scanf("%d", &num);

int fact = factorial(num);


printf("Factorial: %d\n", fact);
return 0;
}

Result:
Thus the embedded C programs to perform basic and arithmetic Programs are
verified.

20
EXP. NO : 5
DATE :

INTRODUCTION TO ARDUINO PLATFORM AND PROGRAMMING

AIM:
To study the Arduino platform and write the Arduino program to blink
the LED.

COMPONENTS NEEDED:
1. Arduino UNO development board
2. LED
3. 220Ω resistor
4. Arduino to PC power cable
5. Breadboard
6. Connecting wires
Theory:

21
TECHNICAL SPECIFICATIONS OF ARDUINO UNO:

Microcontroller - ATmega328
Operating Voltage - 5V
Supply Voltage (recommended) - 7-12V
Maximum supply voltage (not recommended) - 20V
Digital I/O Pins - 14(of which 6 provide PWM o/p)
Analog Input Pins – 6
DC Current per I/O Pin - 40 mA
DC Current for 3.3V Pin - 50 mA
Flash Memory - 32 KB (ATmega328) of which 0.5KB Used by Bootloader
SRAM - 2 KB (ATmega328)
EEPROM - 1 KB (ATmega328)
Clock Speed - 16 MHz

Component Explanations:

Analog input pins – pins (A0-A5) that take-in analog values to be


converted to be represented with a number range 0-1023 through an
Analog to Digital Converter (ADC).

ATmega328 chip – 8-bit microcontroller that processes the sketch you


programmed.

Built-in LED – an on board LED to pin 13.

Crystal Oscillator – clock that has a frequency of 16MHz

DC Jack – where the power source (AC-to-DC adapter or battery)


should be connected. It is limited to input values between 6-20V but
recommended to be around 7-12V.

Digital I/O pins – input and output pins (0-13) of which 6 of them (3, 5,
6, 9, 10 and 11) also provide PWM (Pulse Width Modulated) output by
using the analogWrite() function. Pins (0 (RX) and 1 (TX)) are also used
to transmit and receive serial data.

ICSP Header – pins for “In-Circuit Serial Programming” which is


another method of programming.

ON indicator – LED that lights up when the board is connected to a


power source.

22
Power Pins – pins that can be used to supply a circuit with values VIN
(voltage from DC Jack), 3.3V and 5V.

Reset Button – A button that is pressed whenever you need to restart the
sketch programmed in the board.

USB port – allows the user to connect with a USB cable the board to a
PC to upload sketches or provide a voltage supply to the board. This is
also used for serial communication through the serial monitor from the
Arduino software.

Integrated Development Environment (IDE):


Once the board is installed, it’s time to open the Arduino IDE.
It is fairly simple when compared to larger desktop C language
development systems.

PROGRAMMING:
void setup()
{
// initialize digital pin 10 as an output.
pinMode(10, OUTPUT);

23
}
// the loop function runs over and over again forever
void loop()
{
digitalWrite(10, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(10, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}

CONNECTION DIAGRAM:

24
PROCEDURE:
1. Arduino development board is connected to PC through USB cable
2. Open “Arduino” icon from the computer desktop
3. Select tools menu to choose Arduino board type
4. Select tools menu to choose Arduino board COM port
5. Select file menu to choose new and type program

6. Click Verify icon to once compilation done to upload the program to Arduino
controller by clicking Upload icon
7. The circuit connections were given as shown in connection diagram.
8. When the given LED glows with a respective time delay.

Result:
Thus the study of the Arduino platform and the Arduino program to blink
LED has been studied and verified successfully.

25
EXP. NO : 6
DATE :

EXPLORE DIFFERENT COMMUNICATION METHODS WITH IOT DEVICES


(ZIGBEE, GSM, BLUETOOTH)

Certainly! IoT (Internet of Things) devices often use various communication methods to
interact with each other and with central systems. Three common communication
protocols are Zigbee, GSM (Global System for Mobile Communications), and Bluetooth.
Let's explore each of them, along with a simple implementation example for each:

1. Zigbee:
Overview: Zigbee is a wireless communication protocol designed for low-power, short-
range communication. It operates on the IEEE 802.15.4 standard and is commonly used in
home automation, industrial automation, and other IoT applications.

Implementation Example: Let's consider a scenario where you have a Zigbee-enabled


temperature sensor and a Zigbee-enabled smart home hub.

# Example Zigbee Communication in Python

from zigpy.zcl.clusters.general import TemperatureMeasurement


from zigpy.device import Device
from zigpy.zcl.clusters.security import IasZone

# Simulating a Zigbee-enabled Temperature Sensor


temperature_sensor = Device()
temperature_measurement_cluster =
temperature_sensor.add_cluster(TemperatureMeasurement.cluster_id)
temperature_measurement_cluster.attributes[0].value = 25.0 # Simulated temperature
reading

# Simulating a Zigbee-enabled Smart Home Hub


smart_home_hub = Device()
ias_zone_cluster = smart_home_hub.add_cluster(IasZone.cluster_id)

# Communication
temperature = temperature_measurement_cluster.attributes[0].value
ias_zone_cluster.value = "Temperature Alert: {}".format(temperature)

print("Temperature Sensor Reading:", temperature)


print("Smart Home Hub Alert:", ias_zone_cluster.value)

26
2. GSM (Global System for Mobile Communications):
Overview: GSM is a widely used standard for mobile communication. It enables devices
to communicate over cellular networks, making it suitable for IoT devices that require
wide-area coverage.
Implementation Example: Consider a scenario where you have a GSM-enabled GPS
tracker reporting its location.

# Example GSM Communication in Python (using a hypothetical library)


import gsm_module

# Simulating a GSM-enabled GPS Tracker


gps_tracker = gsm_module.GpsTracker()

# Get current location


latitude, longitude = gps_tracker.get_location()

# Send location information over GSM


gsm_module.send_sms("+123456789", "Current Location: {}, {}".format(latitude,
longitude))

3. Bluetooth:
Overview: Bluetooth is a short-range wireless communication standard used for
connecting devices over short distances. Bluetooth is commonly used in IoT scenarios like
wearables, smart home devices, and healthcare.
Implementation Example: Consider a scenario where you have a Bluetooth-enabled
heart rate monitor sending data to a smartphone.

# Example Bluetooth Communication in Python (using a hypothetical library)


import bluetooth_module

# Simulating a Bluetooth-enabled Heart Rate Monitor


heart_rate_monitor = bluetooth_module.HeartRateMonitor()

# Get current heart rate


heart_rate = heart_rate_monitor.get_heart_rate()

# Send heart rate data over Bluetooth to a smartphone


bluetooth_module.send_data("Smartphone", "Heart Rate: {}".format(heart_rate))

27
Result:
The heart rate monitor communicates its readings to a smart phone using Bluetooth
was successfully displayed.

28
EXP. NO : 7
DATE :

INTRODUCTION TO RASPBERRY PI PLATFORM AND PYTHON


PROGRAMMING

Introduction to Raspberry Pi:

Raspberry Pi is a series of small, affordable, single-board computers developed by the


Raspberry Pi Foundation. It is designed to promote computer science education and
facilitate experimentation with hardware and software in the field of embedded systems.
Raspberry Pi boards are widely used in various projects, ranging from simple hobbyist
endeavors to complex industrial applications.

Raspberry Pi Features:

Affordability: Raspberry Pi boards are cost-effective, making them accessible for


educational purposes and hobbyist projects.

Versatility: Raspberry Pi can run various operating systems, including Raspbian (a


Debian-based Linux distribution), allowing users to run a wide range of applications.

GPIO Pins: Raspberry Pi boards have General-Purpose Input/Output (GPIO) pins,


enabling interaction with the physical world by connecting sensors, actuators, and other
hardware components.

Connectivity: Raspberry Pi boards come with built-in USB ports, HDMI output, Ethernet,
Wi-Fi, and Bluetooth, providing connectivity options for different devices.

Python Programming on Raspberry Pi:


Python is a popular programming language for Raspberry Pi due to its readability,
versatility, and a vast number of libraries and frameworks available. Let's go through a
simple Python implementation on Raspberry Pi.

Example: LED Blinking using Python and GPIO on Raspberry Pi


This example demonstrates how to use Python to control a GPIO pin on a Raspberry Pi to
blink an LED.

Hardware Setup:
Connect a resistor from GPIO pin 17 to a breadboard.
Connect an LED's anode (longer leg) to the resistor and the cathode (shorter leg) to the
ground (GND) pin.

Python Code:

29
# Import necessary libraries
import RPi.GPIO as GPIO
import time

# Set up GPIO
led_pin = 17 # GPIO pin number
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

try:
# Blink the LED 5 times
for _ in range(5):
print("LED ON")
GPIO.output(led_pin, GPIO.HIGH) # Turn LED on
time.sleep(1) # Wait for 1 second

print("LED OFF")
GPIO.output(led_pin, GPIO.LOW) # Turn LED off
time.sleep(1) # Wait for 1 second

finally:
# Clean up GPIO on program exit
GPIO.cleanup()

Output:
Save the Python code in a file (e.g., blink_led.py).
Run the script using the following command in the terminal:

python3 blink_led.py

Result:
This is a basic example, but it illustrates the process of setting up GPIO pins on a
Raspberry Pi using Python. You can expand upon this foundation for more complex
projects, such as sensor readings, motor control, or even building IoT devices.

30
EXP. NO : 8
DATE :
INTERFACING SENSORS WITH RASPBERRY PI

Objectives:
Interfacing sensors with a Raspberry Pi is a common and essential task in many IoT
and embedded systems projects. I'll provide an example of interfacing a simple sensor,
such as a DHT11 temperature and humidity sensor, with a Raspberry Pi using Python.
Please note that the specific code and connections may vary depending on the sensor you
are using.

Example: Interfacing DHT11 Temperature and Humidity Sensor

Hardware Setup:
Connect the DHT11 sensor to the Raspberry Pi:
Connect the sensor's VCC pin to the 3.3V pin on the Raspberry Pi.
Connect the sensor's GND pin to a ground (GND) pin on the Raspberry Pi.
Connect the sensor's DATA pin to a GPIO pin on the Raspberry Pi, e.g., GPIO 17.
Install the required Python library:

pip3 install adafruit-circuitpython-dht

Python Code:
import board
import adafruit_dht
import time

# Set up the DHT sensor


dht_pin = board.D17 # GPIO pin where the sensor is connected
dht_sensor = adafruit_dht.DHT11(dht_pin)

try:
# Read and print temperature and humidity
while True:
try:
temperature_celsius = dht_sensor.temperature
humidity = dht_sensor.humidity
print(f"Temperature: {temperature_celsius}°C, Humidity: {humidity}%")
except RuntimeError as e:
print(f"Error reading DHT sensor: {e}")

time.sleep(2) # Read every 2 seconds

31
except KeyboardInterrupt:
print("Program terminated by user.")

finally:
# Cleanup
dht_sensor.exit()

Output:
Save the Python code in a file, e.g., read_dht_sensor.py.
Run the script using the following command in the terminal:

bashCopy code
python3 read_dht_sensor.py

Result:
The program will continuously read and print the temperature and humidity values
from the DHT11 sensor every 2 seconds.

32
EXP. NO : 9
DATE :

COMMUNICATE BETWEEN ARDUINO AND RASPBERRY PI USING ANY


WIRELESS MEDIUM

Objective:
The Communication between an Arduino and a Raspberry Pi using wireless
technology is a common scenario in various IoT projects. I'll provide an example using the
nRF24L01 wireless transceiver module, which operates on the 2.4GHz frequency band
and is suitable for short-range communication.

Example: Wireless Communication between Arduino and Raspberry Pi using nRF24L01

Hardware Setup:

Arduino Side:
Connect the nRF24L01 module to the Arduino. Typically, connections include
power (3.3V), ground (GND), SPI pins (MOSI, MISO, SCK), and a digital pin for the CE
and CSN pins.

Raspberry Pi Side:
Connect the nRF24L01 module to the Raspberry Pi. The connections include power
(3.3V), ground (GND), SPI pins (MOSI, MISO, SCK), and GPIO pins for CE and CSN.

Install the necessary Python library on the Raspberry Pi:

bashCopy code
pip3 install spidev
bashCopy code
pip3 install python-periphery
bashCopy code
pip3 install nRF24

Arduino Code:

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(9, 10); // CE, CSN

void setup() {

33
Serial.begin(9600);
radio.begin();
radio.openWritingPipe(0x7865543219LL); // Set the pipe address for
communication
}

void loop() {
const char text[] = "Hello, Raspberry Pi!";
radio.write(&text, sizeof(text));
delay(1000);
}

Raspberry Pi Code (Python):

import spidev
from nRF24 import nRF24

radio = nRF24(cePin=22, csnPin=0, channel=0, payloadSize=32)


radio.begin()
radio.openReadingPipe(1, 0x7865543219LL) # Set the same pipe address used on
the Arduino

radio.startListening()

while True:
if radio.available():
receivedMessage = []
radio.read(receivedMessage, radio.getDynamicPayloadSize())
print(f"Received message: {receivedMessage.decode('utf-8')}")

Output:
Upload the Arduino code to your Arduino board.
Run the Python script on your Raspberry Pi.

34
Result:
The basic one-way communication from Arduino to Raspberry Pi. In a real-world
scenario, you might want to implement bidirectional communication, error handling, and
possibly use more advanced protocols depending on your project requirements.

35
EXP. NO : 10
DATE :

SETUP A CLOUD PLATFORM TO LOG THE DATA

Objective:
The cloud platform to log data from your IoT devices (like Raspberry Pi and
Arduino) allows you to store and analyze the data remotely

Steps:
Create a ThingSpeak Account:
Go to the ThingSpeak website and sign up for an account.

Create a Channel:
After signing in, click on "Channels" and then "My Channels."
Click on "New Channel" to create a new channel.
Define the fields you want to log (e.g., Temperature, Humidity) and click "Save
Channel."

Get API Key:


After creating the channel, click on "API Keys" to get your Write API Key. You'll
need this key to send data to ThingSpeak.

Modify Raspberry Pi Code (Python):


import spidev
from nRF24 import nRF24
import requests
radio = nRF24(cePin=22, csnPin=0, channel=0, payloadSize=32)
radio.begin()
radio.openReadingPipe(1, 0x7865543219LL)
radio.startListening()
api_key = "YOUR_THINGSPEAK_API_KEY"
while True

if radio.available():
receivedMessage = []
radio.read(receivedMessage, radio.getDynamicPayloadSize())
data = receivedMessage.decode('utf-8')
# Log data to ThingSpeak
url = f"https://api.thingspeak.com/update?api_key={api_key}&field1={data}"
response = requests.get(url)
print(f"Data logged to ThingSpeak: {data}")

36
Replace "YOUR_THINGSPEAK_API_KEY" with the Write API Key you obtained from
ThingSpeak.

Run the Raspberry Pi Code:


Execute the modified Python script on your Raspberry Pi.
View Data on ThingSpeak:
Go back to the ThingSpeak website, navigate to your channel, and you should see
the data being logged in real-time.

Result:
Thus the program was demonstrates a simple integration with ThingSpeak. In a
more sophisticated setup, you might want to implement error handling, data validation,
and possibly use a dedicated IoT platform for more advanced analytics and control.

37
EXP. NO : 11
DATE :

CLOUD PLATFORM TO LOG DATA FROM ARDUINO AND RASPBERRY PI

Objective:
To log data from sensors connected to a Raspberry Pi and upload the data to a cloud
platform for storage and visualization.

Materials:
 Raspberry Pi (any model with GPIO pins will do)
 MicroSD card (at least 8GB recommended) with Raspberry Pi OS (formerly
Raspbian) installed
 Power supply for the Raspberry Pi
 Sensors (e.g., temperature sensor, humidity sensor, light sensor, etc.)
 Breadboard and jumper wires
 Python editor or IDE (e.g., Thonny, IDLE, Visual Studio Code with Python
extension)
 Cloud Platform: In this exercise, we will use ThingSpeak as the cloud platform.

Lab Exercise Steps:

1. Raspberry Pi Setup: a. Connect the Raspberry Pi to a monitor, keyboard, and mouse.


b. Insert the prepared microSD card with Raspberry Pi OS into the Pi. c. Power on
the Raspberry Pi by connecting it to a power supply. d. Follow the on-screen
instructions to complete the initial setup, such as setting up Wi-Fi, updating the
system, and changing the default password.

2. Sensor Connections: a. Connect the sensors to the Raspberry Pi's GPIO pins or any
suitable interface (e.g., I2C, SPI). b. Refer to the datasheets or sensor documentation
for correct wiring and connections. c. Use breadboard and jumper wires as needed
for connecting the sensors securely.

3. Python Sensor Data Logging: a. Open a new Python script in your chosen Python
editor or IDE. b. Import any required libraries/modules for sensor interfacing and
data logging (e.g., RPi.GPIO, Adafruit_DHT, etc.). c. Initialize the required GPIO
pins or sensor communication interface. d. Write Python code to read data from the
sensors. e. Store the sensor data in variables or data structures (e.g., lists or
dictionaries). f. Optionally, implement data processing or calibration for sensor
readings. g. Append the sensor data to a log file or a CSV file.

38
4. ThingSpeak Cloud Setup:
a. Create an account on ThingSpeak (https://thingspeak.com/) or any other cloud
platform of your choice.
b. Create a new ThingSpeak channel to store the sensor data.
c. Note the Write API Key provided by ThingSpeak for your channel. This key
will be used to upload data to the cloud.

5. Uploading Data to Cloud: a. Modify the Python script to include code for uploading
the sensor data to the ThingSpeak channel using the Write API Key. b. Use suitable
libraries or APIs (e.g., requests library) to send HTTP POST requests to ThingSpeak
with the sensor data. c. Implement error handling to ensure data is successfully
uploaded to the cloud.

6. Scheduling Data Logging and Upload (Optional): a. Implement a scheduling


mechanism (e.g., using time.sleep(), cron jobs, or Python libraries like schedule) to
log sensor data at regular intervals. b. Adjust the data logging interval according to
the application requirements.

7. Data Visualization: a. Access your ThingSpeak channel online to view the logged
sensor data in real-time on charts and graphs provided by the cloud platform.

Program:

import requests
import random
import time

API_KEY = 'YOUR_THINGSPEAK_API_KEY'
URL = f'https://api.thingspeak.com/update?api_key={API_KEY}'

def send_data_to_thingspeak(data):
response = requests.get(URL + f'&field1={data}')
print(response.text)

try:
while True:
sensor_data = random.randint(0, 100) # Replace this with actual sensor reading
send_data_to_thingspeak(sensor_data)
time.sleep(15) # Adjust the delay based on your needs

except KeyboardInterrupt:
print("Logging stopped.")
39
Arduino Code:
#include <WiFi.h>

const char *ssid = "your-ssid";


const char *password = "your-password";
const char *server = "api.thingspeak.com";
const String apiKey = "your-thingspeak-api-key";

void setup() {
Serial.begin(115200);
connectToWiFi();
}

void loop() {
int sensorData = analogRead(A0); // Replace this with your sensor reading
sendToThingspeak(sensorData);
delay(15000); // Adjust the delay based on your needs
}

void connectToWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}

void sendToThingspeak(int data) {


WiFiClient client;
if (client.connect(server, 80)) {
String postStr = "api_key=" + apiKey + "&field1=" + String(data);
client.println("POST /update HTTP/1.1");
client.println("Host: " + String(server));
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded");
client.println("Content-Length: " + String(postStr.length()));
client.println();
client.println(postStr);
client.stop();
Serial.println("Data sent to ThingSpeak");
}
}

40
Result:
To log data from sensors connected to a Raspberry Pi and upload the data to a cloud
platform is verified successfully.

41
EXP. NO : 12
DATE :
HEART RATE MONITORING SYSTEM USING IOT

DESCRIPTION:

In this project, we will interface Pulse Sensor with Arduino to Measure Pulse Rate
(BPM) or Heart Beat value. The Pulse rate will be displayed on 16×2 LCD Display.

A pulse sensor is a hardware device that can be used to measure heart rate in real-time.
When paired with an Arduino microcontroller, you can create a simple yet effective
heart rate monitor. This sensor is quite easy to use and operate. Place your finger on top
of the sensor and it will sense the heartbeat by measuring the change in light from the
expansion of capillary blood vessels.

COMPONENTS/HARDWARE REQUIRED:

Arduino UNO Board. 1 1.

Pulse Sensor. 1

16X2 I2C LCD Display. 1

Jumper Wires. 10 1.

Breadboard. 1

PULSE SENSOR :

The Pulse Sensor is a plug-and-play heart-rate sensor for Arduino. It can be used by
students, artists, athletes, makers, and game & mobile developers who want to easily
incorporate live heart-rate data into their projects.

42
The essence is an integrated optical amplifying circuit and noise eliminating
circuit sensor. Clip the Pulse Sensor to your earlobe or fingertip. Then it into
your Arduino, you are now ready to read heart rate.

The front of the sensor comes with the heart logo. This is where you place your finger.
On the front side, you will see a small round hole, from where the green LED shines. Just
below the LED

43
is a small ambient light photosensor APDS9008 which adjust the brightness in different
light conditions.

On the back of the module you will find MCP6001 Op-Amp IC, a few resistors, and
capacitors. This makes up the R/C filter network. There is also a reverse protection
diode to prevent damage if you connect the power leads reverse.

Pulse Sensor Technical Specifications :

Physical Characteristics :

 Dimensions: Approximately 0.625″ (15.875mm) in diameter


 Weight: Lightweight, usually around a few grams
 Material: Biocompatible materials for safe skin contact

Electrical Characteristics :

 Sen Operating Voltage: 3V – 5.5V


 Current Consumption: Typically around 4mA
 Output Signal: Analog (0.3V to VCC)
 Signal Range: 0-1023 (10-bit ADC output of Arduino)

44
Sensing Technology :

 Sensor Type: Photoplethysmogram (PPG)


 Wavelength: Typically around 565nm (Green LED)

Working of the Pulse Sensor :

The Pulse Sensor works on the principle of Photoplethysmography (PPG), which


is a non-invasive method for measuring changes in blood volume under the skin. The
sensor essentially consists of two main components: a light-emitting diode (LED) that
shines light into the skin and a photodetector that measures the amount of light that is
reflected back.

1. Light Emission: A green LED emits light into the skin.


2. Reflection & Detection: The light interacts with blood and is partially reflected
back, captured by a photodetector.

Heart Rate: Changes in reflected light create a waveform that correlates with heartbeats.

45
3. Oxygen Level: The amount of reflected light also indicates blood oxygen levels, as
oxygenated blood absorbs more green light.
4. Signal Filtering: A Low Pass Filter cleans up the noisy, raw signal from the
photodetector.
5. Amplification: An operational amplifier boosts the filtered signal for better
accuracy.
6. Data Reading: Finally, an Arduino reads the amplified signal and software
algorithms translate it into heart rate and potentially blood oxygen levels.

Pulse Sensor PinOut :


The pulse sensor has three pins: VCC, GND & Analog Pin.

Interfacing Pulse Sensor with Arduino :


Let us interface the Pulse Sensor with Arduino and start measuring the Pulse
Rate/Heart Beat/BPM Value.

Hardware Wiring Diagram :


The connection diagram between Pulse Sensor and Arduino is so easy.

 Connect the RED wire (Power) of the Pulse Sensor to the 5V pin on the Arduino.
 Connect the BLACK wire (Ground) to the GND pin on the Arduino.
 Connect the PURPLE wire (Signal) to Analog Pin 0 (A0) on the Arduino.

46
Pulse Sensor Library Installation :
Before moving to the coding part, you need to add the Pulse Sensor Library on your

47
Arduino Library Folder.

 Download the PulseSensor Playground Library from the Arduino IDE (Go
to Sketch -> Include Library -> Manage Libraries, then search for “PulseSensor
Playground” and install it).
 You visit Pulse Sensor Github repository to see the examples code with different
microcontrollers.

Source Code/Program :
 Now let us take a look at the Pulse Sensor Arduino Code, taken from the library
examples.
 Open the example sketch that comes with the library (Go to File -> Examples -
> PulseSensor Playground -> GettingStartedProject).

 #define USE_ARDUINO_INTERRUPTS true


2// Include necessary libraries
 3#include <PulseSensorPlayground.h>
 4
 5// Constants
 6constintPULSE_SENSOR_PIN=0; // Analog PIN where the PulseSensor is
 7connected
 8constintLED_PIN=13; // On-board LED PIN
 9constintTHRESHOLD=550; // Threshold for detecting a heartbeat
 10
 11// Create PulseSensorPlayground object
 12PulseSensorPlayground pulseSensor;
 13
voidsetup()
 14
{
 15
// Initialize Serial Monitor
 16
Serial.begin(9600);
 17
 18 // Configure PulseSensor
 19 pulseSensor.analogInput(PULSE_SENSOR_PIN);
 20 pulseSensor.blinkOnPulse(LED_PIN);
 21 pulseSensor.setThreshold(THRESHOLD);
 22
 23 // Check if PulseSensor is initialized
 24 if(pulseSensor.begin())
48
 25 {
 26 Serial.println("PulseSensor object created successfully!");
 27 }
 28}
 29
 30voidloop()
 31{
 32 // Get the current Beats Per Minute (BPM)
 33 intcurrentBPM=pulseSensor.getBeatsPerMinute();
 34
 35 // Check if a heartbeat is detected
if(pulseSensor.sawStartOfBeat())
 36
{
 37
Serial.println("♥ A HeartBeat Happened!");
 38
Serial.print("BPM: ");
 39
Serial.println(currentBPM);
 40 }
 41
 42 // Add a small delay to reduce CPU usage
 43 delay(20);
 44}
 45

Testing &Results :
After uploading the Pulse Sensor Arduino Example code, you can start the testing process.

Place the finger on the Pulse sensor as shown below.

49
Open the Serial Monitor to see the pulse sensor data

Source Code/Program :
The code requires I2C LCD Library for compilation. Therefore download the library and
add it to the Arduino library folder.

 Here is a complete code.

 // Include necessary libraries


3#define USE_ARDUINO_INTERRUPTS true
 4#include <PulseSensorPlayground.h>
 5#include <LiquidCrystal_I2C.h>
 6LiquidCrystal_I2C lcd(0x27,16,2);// set the LCD address to 0x27 for a 16
 7chars and 2 line display
 8
 9
 10// Constants
 11constintPULSE_SENSOR_PIN=0; // Analog PIN where the PulseSensor is
 12connected
 13constintLED_PIN=13; // On-board LED PIN
constintTHRESHOLD=550; // Threshold for detecting a heartbeat
 14
 15
// Create PulseSensorPlayground object
 16
PulseSensorPlayground pulseSensor;
 17
 18voidsetup()
 19{
 20 // Initialize Serial Monitor
 21 Serial.begin(9600);
 22 lcd.init();
 23 lcd.backlight();
 24
50
 25 // Configure PulseSensor
 26 pulseSensor.analogInput(PULSE_SENSOR_PIN);
 27 pulseSensor.blinkOnPulse(LED_PIN);
 28 pulseSensor.setThreshold(THRESHOLD);
 29
 30 // Check if PulseSensor is initialized
 31 if(pulseSensor.begin())
 32 {
 33 Serial.println("PulseSensor object created successfully!");
 34 }
 35}
 36
voidloop()
 37
{
 38
lcd.setCursor(0,0);
 39
lcd.print("Heart Rate");
 40
 41 // Get the current Beats Per Minute (BPM)
 42 intcurrentBPM=pulseSensor.getBeatsPerMinute();
 43
 44 // Check if a heartbeat is detected
 45 if(pulseSensor.sawStartOfBeat())
 46 {
 47 Serial.println("♥ A HeartBeat Happened!");
 48 Serial.print("BPM: ");
 49 Serial.println(currentBPM);
 50
 51 lcd.clear();
 52 lcd.setCursor(0,1);
 53 lcd.print("BPM: ");
 54 lcd.print(currentBPM);
 55 }
 56
 57 // Add a small delay to reduce CPU usage
 58 delay(20);
}

Testing &Results :
. Upload the above code and you can start testing the sensor working.

51
Result :
In this project, we’ve walked you through the step-by-step process of creating a Pulse Rate
Monitor using an Arduino and a Pulse Sensor. This project is not only educational but also highly
practical, offering a cost-effective solution for monitoring your heart rate in real-time. Whether you’re
a healthcare professional, a fitness enthusiast, or simply curious about electronics, this project provides
valuable insights into both health monitoring and Arduino programming. We hope you found this
guide informative and encourage you to explore further applications of this technology for your personal
or professional use.

52

You might also like