0% found this document useful (0 votes)
22 views55 pages

CS3691 ESIOT Lab Record Final

The document outlines a bonafide certificate format for students, detailing various experiments conducted using Edsim51 and Arduino platforms. It includes aims, procedures, and sample programs for tasks such as displaying data on a 7-segment display, data transfer between registers and memory, performing ALU operations, and controlling LEDs with pushbuttons. Additionally, it introduces the Arduino platform, its programming environment, and provides examples of embedded C programs for various applications.

Uploaded by

KING GAMING
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)
22 views55 pages

CS3691 ESIOT Lab Record Final

The document outlines a bonafide certificate format for students, detailing various experiments conducted using Edsim51 and Arduino platforms. It includes aims, procedures, and sample programs for tasks such as displaying data on a 7-segment display, data transfer between registers and memory, performing ALU operations, and controlling LEDs with pushbuttons. Additionally, it introduces the Arduino platform, its programming environment, and provides examples of embedded C programs for various applications.

Uploaded by

KING GAMING
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/ 55

An ISO 9001:2015 Certified Institution

(Approved By AICTE & Affiliated To Anna University Chennai)


Vagaikulam – 628 102, Thoothukudi District, Tamilnadu, India.
Phone: 0461 – 2269301

BONAFIDE CERTIFICATE

NAME

REG.NO

BRANCH

SEMESTER

SUBJECT

Certified that this is the bonafide record of work done by the above student in the

............................................................ laboratory during the academic year .......................

Staff-in-Charge Head of the Dept.

Submitted for the University Practical Examination held on: _____________________

INTERNAL EXAMINER EXTERNAL EXAMINER


INDEX

Page Signature
S.NO Date Title
Number
1 Seven Segment Display Using
Edsim51 Simulator
Data transfer between Register
2 and memory

3 Perform ALU (arithmetic) operations using


Edsim51 Simulator
LEDs Blink and Pushbutton Based LED
4 Control Using Arduino

Displaying Hello world message


5 in LCD using Arduino
6 RC Servo position control using Arduino
7
Temperature & Humidity DHT11 Sensor
Interfacing with Arduino
Explore Different Communication
8 Methods with IoT devices (Bluetooth)

9 Blinking of LED using Raspberry Pi

10 Distance Measurement Using Ultrasonic


Sensors with Raspberry Pi
Communication between Arduino
11 and Raspberry PI using any
wireless medium
Setup a cloud platform to log the
12 Data
Log Data using Raspberry PI and upload to
13 Cloud platform

14 Design an IOT based system


EXPT NO: 1
SEVEN SEGMENT DISPLAY USING
DATE :
EDSIM51 SIMULATOR

AIM:
To Display a hexadecimal digit on a 7-segment display connected to
Port 1 of the 8051 microcontroller and also to display a hexadecimal digit
on a 7-segment display connected to Port 0 Display using
Edsim51 simulator and execute it.
APPARATUS REQUIRED:
PC with edsim51 simulator installed.
PROCEDURE:
STEP 1 : Initialize Port 1 as an output port.
STEP 2 : Enter an infinite loop labeled as "LOOP."
STEP 3 : The delay subroutine is called "DELAY."
Initialize register R2 with the value 0xFF (255 in decimal).
Enter a loop labeled as "DELAY_LOOP."
STEP 4 : The program continues to loop indefinitely, creating a blinking
LED effect on P1.0.
Objective: Blink an LED connected to Port 1 of the 8051 microcontroller.

2
PROGRAM 1:
ORG 0x00
MOV P1, #0x00; Initialize Port 1 as output LOOP:
SETB P1.0 ; Turn on LED at P1.0

ACALL DELAY; Call the delay subroutine


CLR P1.0 ; Turn off LED at P1.0

ACALL DELAY; Call the delay subroutine


SJMP LOOP

DELAY:
MOV R2, #0xFF DELAY_LOOP:
DJNZ R2, DELAY_LOOP
RET

3
OUTPUT:

The output screen for the above program

4
PROCEDURE:

STEP 1: Initialize Port 0: Set up Port 0 as an output port to control the


7- segment display.

STEP 2: Enter the Main Loop (MAIN)

STEP 3: Display Subroutine (DISPLAY)

STEP 4: Display Subroutine (DISPLAY)

STEP 5: Delay Subroutine (DELAY)

STEP 6: Return from the delay subroutine

PROGRAM:

ORG 0x00
MOV P1, #0x00; Initialize Port 1 as output LOOP:
SETB P1.0 ; Turn on LED at P1.0
ACALL DELAY; Call the delay subroutine
CLR P1.0 ; Turn off LED at P1.0
ACALL DELAY; Call the delay subroutine
SJMP LOOP

DELAY:

DELAY_LOOP:
DJNZ R2, DELAY_LOOP
RET

RESULT:

Thus the 8051-assembly language program for 7 segment display


using edsim51 simulator has been executed successfully.

5
EXPT NO: 2
DATA TRANSFER BETWEEN REGISTER
DATE :
AND MEMORY

AIM:
To write a assembly language program to transfer data between
register and memory.

APPARATUS REQUIRED:
PC with edsim51 simulator installed.
PROCEDURE:

Transfer a value from a register to memory and then from memory back to
another register. We'll use the ‘MOV’ (move) instruction for this purpose.

STEP 1: Text Section:


We declare the program's entry point using the global main directive.

STEP 2: Main Function:


The main function begins.

STEP 3: Load a Value into a Register

STEP 4: Store the Value in Memory

STEP 5: Load the Value from Memory

STEP 6: Program Exit

6
PROGRAM:
; 8051 Data Transfer Between Register and Memory Example
ORG 0x0000; Start address

MAIN:
; Move a value (e.g., 0xAA) from register R0 to a memory location
(e.g., 0x30)

MOV A, #0xAA; Load the accumulator with the value 0xAA

MOV 0x30, R0; Move the content of Register R0 to memory location 0x30
; Move a value from a memory location (e.g., 0x30) to register

R1 MOV A, 0x30; Load the accumulator with the content of memory


location 0x30

MOV R1, A; Move the accumulator content to Register R1

; End of the program (you can add more instructions as needed)


; Infinite loop for the simulator SJMP MAIN

END

7
OUTPUT:
The output screen of the above program

RESULT:

Thus, the 8051-assembly language program for data transfer from


registers to memory using simulator has been executed successfully.

8
EXPT NO : 3
Perform ALU (arithmetic) Operations using
DATE :
EDSIM51 Simulator

AIM:

To write and execute the ALU (arithmetic) operations using EDSIM51 simulator.

APPARATUS REQUIRED:

PC with edsim51 simulator installed.

PROCEDURE:

ALU Operations using EdSim51

STEP 1: Download and install EdSim51 from the official website


(
STEP 2: Open EdSim51 and create a new file.
STEP 3: Initialization:
⚫ Load the value 10 into R0 (First operand).
⚫ Load the value 5 into R1 (Second operand).
STEP4: Addition, Subtraction, Multiplication, Division

STEP5: Infinite Loop:


⚫ Enter an infinite loop using the HERE label and the SJMP HERE
instruction. This loop keeps the program running indefinitely.

9
PROGRAM:
; ALU Operations in 8051 Assembly for EdSim51

ORG 0x0000
; Initialize data in RAM
MOV R0, #10 ; First operand (e.g., 10)
MOV R1, #5 ; Second operand (e.g., 5)

; Addition
ADD A, R0 ; A = A + R0
; Result of addition will be stored in the Accumulator (A)

; Subtraction
MOV R2, A ; Store the result of addition in R2
SUBB A, R1 ; A = R2 (Result of addition) - R1
; Result of subtraction will be stored in the Accumulator (A)

; Multiplication
MOV R2, A ; Store the result of subtraction in R2
MUL AB ; Multiply A by B (R2), Result will be in ACC (A,
lower byte) and B (higher byte)
; Result of multiplication will be stored in the Accumulator (A)

; Division
MOV R2, A ; Store the result of multiplication in R2
DIV AB ; Divide ACC (A) by B (R2), Quotient will be in ACC
(A), Remainder in B
; Result of division will be stored in the Accumulator (A) and B
(Remainder)
; Infinite loop to hold the program
HERE:
SJMP HERE
END

ESULT:

Thus the 8051 assembly language program to perform ALU


operations using simulator has been executed successfully.

10
ARDUINO PROGRAMMING

INTRODUCTION:
Arduino is an open-source electronics platform that has gained immense
popularity among beginners, students, hobbyists, and professionals for its
simplicity and versatility. This introduction provides an overview of the
Arduino platform and its programming aspects.

What is Arduino?
Arduino is a versatile microcontroller-based hardware and software platform
that enables users to create interactive and programmable electronic projects.
It consists of two main components:

Hardware: Arduino boards are the physical computing devices at the core
of the platform. They come in various shapes and sizes but share common
elements, including a microcontroller, digital and analog input/output pins,
power supply, and communication interfaces.

Software: The Arduino Integrated Development Environment (IDE) is a


user-friendly programming environment for writing, compiling, and
uploading code to Arduino boards. It uses a simplified version of the C and
C++ programming languages.

11
Why Use Arduino?
Here are some key reasons why Arduino has become so popular:
1. Accessibility: Arduino is designed to be easy for beginners to start
working with electronics and programming. It lowers the entry barrier
for those new to the field.
2. Open Source: Arduino's hardware and software are open source,
meaning the designs and source code are freely available. This
encourages a vibrant community of users and developers who share their
knowledge and contribute to its growth.
3. Versatility: Arduino is not limited to any specific application. It can be
used for a wide range of projects, including robotics, home automation,
art installations, and scientific experiments.
4. Abundance of Resources: There is a wealth of online resources, tutorials,
and libraries available to help users get started and solve problems they
encounter.

"shields" – additional boards that provide extra functionality. These shields


can be stacked on top of the Arduino board.

The Arduino Programming Environment:


Arduino programming is done in the Arduino IDE, which provides a simple
and straightforward way to write code for your projects.

12
Here are some key aspects of the Arduino programming environment:
Sketch: In Arduino, a program is called a "sketch." A sketch typically
consists of two essential functions: setup() (for initialization) and loop() (for
continuous execution).
Libraries: Arduino libraries are pre-written code packages that simplify
working with external components like sensors and displays. Many libraries
are available for various purposes.
Upload: Once you've written your code, you can upload it to the Arduino
board via a USB connection. The Arduino IDE handles the compilation and
uploading process for you.

Conclusion:
Arduino is a powerful and accessible platform for learning about electronics
and programming. It allows you to turn your creative ideas into tangible
projects, whether you're a student learning the basics or an experienced
engineer building advanced systems. This introduction sets the stage for
exploring Arduino further and getting hands-on experience with this
remarkable platform.

13
14
EXPT NO : 4
LEDs BLINK AND PUSHBUTTON BASED
DATE :
LED CONTROL USING ARDUINO

AIM:
To write an embedded C program to make LEDs blink and pushbutton based
LED connected to Arduino (micro controller) pin.

APPARATUS REQUIRED:
1. PC with Arduino IDE
2. Arduino Uno Kit with USB Cable
3. Pushbutton
4. LED
5. Power chord
6. Patch Cords

ALGORITHM:

STEP 1 : Include necessary header files


STEP 2 : Define the LED pin
STEP 3 : Start the main function
STEP 4 : Configure the LED pin as an output
STEP 5 : Enter an infinite loop with while(1)
STEP 6 : Create a delay
STEP 7 : Repeat the LED toggle and delay
STEP 8 : Exit the main function

15
PROGRAM 1:
// Simple Embedded C Program for LED Blinking

int LED_PIN = 13;

void setup()
{
pinMode(LED_PIN, OUTPUT);
}

void loop()
{
digitalWrite(LED_PIN, HIGH);
delay(1000);
digitalWrite(LED_PIN, LOW);
delay(1000);
}}

PROGRAM 2:
// To make 4 LEDs blink in Arduino Kit

void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
// turn the LED on by making the voltage HIGH
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);

delay(1000); // wait for a second

16
// turn the LED off by making the voltage LOW
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);

delay(1000); // wait for a second


}

PROCEDURE :

➢ There are 4 LEDs in the kit namely D4, D5, D6 and D7. They are to be connected
to the D4, D5, D6 and D7 pins of Arduino board. The power supply +5V and Gnd
pins of Arduino board also are to be connected in this section.
➢ Connect the USB connector to the USB of Arduino board and the computer system.
➢ Using this program, the first LED (left most LED) is switched on for 0.5 sec and
then it is switched off.
➢ After 0.5 sec., the second LED is switched on for 0.5 sec. and then it is switched
off. In this way, all the four LEDs are switched on and off. Then the cycle repeats
continuously.
➢ In computer, open the sketch software and write the program LED blinking and
execute the program in sketch and check for the proper result.

PROGRAM 3:
// Program to get input from pushbutton and make LED on/off

const int buttonPin = 2; // the number of the pushbutton pin


const int ledPin = 8; // the number of the LED pin

// variables will change:


int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
17
}

void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed. If it is, the buttonState is HIGH:


if (buttonState == LOW) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}}

OUTPUT:

INITIALLY LIGHT IS OFF

LIGHT IS GLOWING AFTER THE EXECUTING OF THE PROGRAM.

RESULT:

Thus, the embedded C program to make LEDs blink and also


control a LED based on pushbutton input using Arduino kit has been
executed successfully.

18
EXP.NO : 5 Displaying Hello world message in LCD using Arduino

AIM :

APPARATUS REQUIRED:
1. PC with Arduino IDE
2. Arduino Uno Kit with USB Cable
3. LCD
4. Patch Cords

THEORY:
In this experiment, 16 characters (columns) and 2 lines (rows) LCD is used.
In the internal library of Sketch software, there is a library called LiquidCrystal.
It is defined as LiquidCrystal.h. This header file has to be used in the beginning
of the program. This library has got many functions that can be used in the
program. We are going to see only a few functions of the LiquidCrystal.h in
this program.

PROGRAM:
/* LiquidCrystal Library - Hello World

Demonstrates the use a 16x2 LCD display. The LiquidCrystal


library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.

This sketch prints "Hello World!" to the LCD and shows the time.

The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
19
* LCD D4 pin to digital pin 4
* LCD D5 pin to digital pin 5
* LCD D6 pin to digital pin 6
* LCD D7 pin to digital pin 7
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor:
* ends to +5V and ground
* wiper to LCD VO pin (pin 3) */

#include <LiquidCrystal.h>

// initialize the library by associating any needed LCD interface pin


// with the arduino pin number it is connected to
const int rs = 12, en = 11, d4 = 4, d5 = 5, d6 = 6, d7 = 7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
// lcd.setCursor(0, 1);
// print the number of seconds since reset:
// lcd.print(millis() / 1000);
}

RESULT:
Thus the LCD is interfaced with Arduino and Hello World is displayed.

20
EXP.NO : 6 RC Servo position control using Arduino

AIM:
To Perform Interfacing of RC Servo Motor with Arduino board and
evaluate the response of variations.

APPARATUS REQUIRED:
1. PC with Arduino IDE
2. Arduino Uno Kit with USB Cable
3. RC Servo Motor
4. Patch Cords

THEORY:
RC servo motor can be used to set the position of the shaft of the servo motor
to 0 to 180 degrees.
50 Hz frequency pulses (Period 20msec) with pulse width (0.5 to 2.5msec)
positions the servo between 0 degrees and 180 degrees.
There is a built in servo library in sketch software. It is used by writing
#include Servo.h as the first line in the Arduino program. In this experiment,
potentiometer is used to output 0-5V analog voltage.

The analog voltage is read in A0 pin using analogRead function. It converts


the 0-5V analog voltage to 10 bit digital outputs (10 bit resolution) and digital
output with decimal value 0-1023. This read value is sent out from the
Arduino as PWM signal in pin D9. The 0-1023 value is changed to the output
of 0-255. If the analog converted value is 1023, then the output will have full
on time pulse width 255. If the analog converted value is 500, then the output
will have on time pulse width of (1023/255) x 500. Since the pulses are
continuous, the average output will be dc voltage depending upon the analog
voltage input. However, a map function to convert 0-1023 to 0-180 is used in
the program. Servo.write() function is used to give control input to the servo
motor 0-180 degrees.
21
Program
//Small servo motor is tested for 0 to 180 degrees positioning
// Library Servo is included in this program
// Servo motor is operated by giving the angle information through the arduino
pin 9
// as pwm signal which goes from 0 to 255, but it is mapped to 0-180
// Potentiometer voltage input is used to provide angle information

#include <Servo.h>

int servoPin = 9;
Servo servo;
int angle = 0; // servo position in degrees

void setup() {
servo.attach(servoPin);
}

void loop() {

// scan from 0 to 180 degrees


for(angle = 0; angle < 180; angle++)
{
servo.write(angle);
delay(15);
}

// now scan back from 180 to 0 degrees


for(angle = 180; angle > 0; angle--)
{
servo.write(angle);
delay(15);
}
}
RESULT:
Thus, the RC servo motor is interfaced with Arduino and varied for desired
angles of rotation

22
EXPT NO : 7
TEMPERATURE & HUMIDITY DHT11
DATE :
SENSOR INTERFACING WITH ARDUINO

AIM:
To measure/monitor temperature and humidity using Arduino

APPARATUS REQUIRED:
1. PC with Arduino IDE
2. Arduino Uno Kit with USB Cable
3. DHT11 Sensor
4. Power chord
5. Patch Cords

PROGRAM:
//DHT11 Sensor
#include "DHT.h"
#define DHTPIN 12 // what digital pin we're connected to
#define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE);


//I2C LCD:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>

// Set the LCD I2C address


LiquidCrystal_I2C lcd(0x27, 16, 2);

23
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
dht.begin();
}
void loop() {
int h = dht.readHumidity();
int t = dht.readTemperature();

lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(t);
lcd.print(" C");

lcd.setCursor(0,1);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("%");

Serial.print("Temp: ");
Serial.print(t);
Serial.print("C, Humidity: ");
Serial.print(h);
Serial.println("%");
delay(500);
}
RESULT:
The Temperature and humidity were measured using Arduino.

24
EXPT NO : 8 EXPLORE DIFFERENT
COMMUNICATION METHODS WITH IoT
DATE :
DEVICES (BLUETOOTH)

AIM:
To explore different communication methods with IOT devices using
Bluetooth.

APPARATUS REQUIRED:
1. PC with Arduino IDE
2. Arduino Uno Kit with USB Cable
3. DHT11 Sensor
4. Power chord
5. Patch Cords

PROGRAM:

//Code to control an LED via bluetooth through a phone app //

//Bluetooth uses serial communication. So, we use many serial functions


in this sketch.

const int LED = 5;

char switchstate;

void setup() {//Here the code only runs once.

Serial.begin(9600);

/*To start serial communication t a rate of 9600 bits per second. This
is the default rate anyways.*/

pinMode(LED, OUTPUT);
25
//Declaring that the LED is an output.
}

void loop() {//This code repeats. This is our main code.

while(Serial.available()>0){

//code to be executed only when Serial.available()>0


/*Serial.available>0 is to check if there is any reading from the
HC-05 Bluetooth module.*/

switchstate = Serial.read();

/*The character we had declared earlier is now being assigned a value-


the value of whatever Serial.read() is.*/

Serial.print(switchstate);
//Serial.read() is to read the value coming from app.

Serial.print("\ "); //This will print the value onto the Serial monitor.
//This moves to the next line after every new line printed.

delay(15);
/*Gives a break of 15 milliseconds. Delay is for human eye, and for
speed of some computers, as some will crash at high speeds.*/

if(switchstate == '1'){ //Checking if the value from app is '1'


digitalWrite(5, HIGH); //If it is, write the component on pin 5(LED) high.
}
else if(switchstate == '0'){ //Else, if the vaue from app is '0',
digitalWrite(5, LOW); //Write the component on pin 5(LED) low.
}
}
}

26
THEORY:
BLUETOOTH:

Wearable and Health Devices:


• Bluetooth, particularly Bluetooth Low Energy (BLE), is extensively used in
wearable health devices and fitness trackers.
• These devices collect health-related data, such as heart rate, steps taken, and
sleep patterns, and transmit this information to smartphones or cloud
platforms for analysis and tracking.
• The low energy consumption of BLE ensures that wearables can operate for
extended periods without frequent recharging.

Proximity-Based Services:
• Bluetooth beacons are employed in projects that provide proximity- based
services and notifications.
• This technology is invaluable for location-based marketing, guiding visitors
in a museum or retail environment, and creating interactive exhibits.
Visitors receive contextually relevant information and notifications on their
smartphones when in proximity to Bluetooth beacons.

Smartphone Integration:
• Bluetooth is a preferred choice for projects that necessitate interaction with
smartphones.
• It allows IoT devices to connect to mobile apps for configuration, control,
and data exchange. This is especially useful in consumer IoT projects,
where user-friendliness and smartphone integration are paramount.
• When planning an IoT project, it's vital to carefully consider the specific
needs and objectives, as well as factors like power consumption, range, and
data throughput. Additionally, security and data privacy should be a top
priority, particularly in applications where sensitive information is
involved. The choice of communication method plays a pivotal role in the
project's success, and selecting the most appropriate technology will ensure
that the project meets its goals efficiently and effectively.

RESULT:
Thus the Bluetooth communication with IoT devices using
Arduino is explored

27
RASPBERRY PI PROGRAMMING

Introduction to Raspberry Pi and Python Programming in IoT:

Raspberry Pi is a small, affordable single-board computer that can


be used for a wide range of applications, including Internet of Things (IoT)
projects. Python is a popular programming language for IoT development
on the Raspberry Pi due to its simplicity and extensive libraries. In this
program, we'll provide a basic introduction to the Raspberry Pi platform and
demonstrate how to write a simple Python program for an IoT project.

Prerequisites:

➢ Raspberry Pi (any model)


➢ MicroSD card with Raspbian OS installed
➢ Power supply for Raspberry Pi
➢ Internet connection (Wi-Fi or Ethernet)
➢ LED and resistor (220-330Ω)
➢ Jumper wires
➢ Breadboard (optional)

Program Outline:

Setting Up Raspberry Pi:

➢ Insert the microSD card with Raspbian OS into the Raspberry Pi.
➢ Connect the power supply and boot up the Raspberry Pi.
➢ Connect to the Raspberry Pi via SSH (if headless) or use a monitor
and keyboard for direct access.

28
29
Basic Python Installation:

By default, Raspberry Pi comes with Python pre-installed.

Verify the version using the python --version command.

GPIO (General Purpose Input/Output) Pins:

➢ Raspberry Pi has GPIO pins that can be used to control external


devices.
➢ Identify and understand the GPIO pins on your Raspberry Pi model.

Python GPIO Library:

➢ Python has libraries like RPi.GPIO or gpiozero to work with GPIO


pins.
➢ Install the library if not already installed (pip install RPi.GPIO).

Blinking an LED:

➢ Connect an LED to a GPIO pin and a ground pin via a resistor.

IoT Integration:

To make it an IoT project, you can:


➢ Add sensors (e.g., temperature, humidity) to collect data.
➢ Send data to a cloud service or server.
➢ Create a web interface to monitor and control your IoT device
remotely.

30
Further Learning:

a) Explore more advanced IoT projects and sensors.


b) Learn about MQTT for IoT communication.
c) Dive deeper into Python libraries and frameworks for IoT
development.
d) This program provides a basic introduction to Raspberry Pi and
Python programming for IoT.
e) Depending on your interests and project goals, you can expand your
knowledge and create more complex IoT applications.

31
EXPT NO: 9
BLINKING OF LED USING
DATE :
RASPBERRY PI

AIM:
To make LED Blink using Raspberry Pi platform and Python Programming.

PROGRAM:
import time
import RPi.GPIO as GPIO

# Pin definitions
led_pin = 12

# Use "GPIO" pin numbering


GPIO.setmode(GPIO.BCM)

# Set LED pin as output


GPIO.setup(led_pin, GPIO.OUT)

# Blink forever
try:
while True:
GPIO.output(led_pin, GPIO.HIGH) # Turn LED on
time.sleep(1) # Delay for 1 second
GPIO.output(led_pin, GPIO.LOW) # Turn LED off
time.sleep(1) # Delay for 1 second

# When you press ctrl+c, nicely release GPIO resources


finally:
GPIO.cleanup()

RESULT:
Thus, Blinking of LED using Raspberry Pi platform and Python Programming is
executed successfully.

32
EXPT NO : 10
DISTANCE MEASUREMENT USING
DATE :
ULTRASONIC SENSORS WITH RASPBERRY PI

AIM:
To measure the distance using ultrasonic sensor with Raspberry Pi and Python
Programming.

THEORY:
Interfacing sensors with a Raspberry Pi using python programming for
IoT applications involves several steps.

Here's a high- level overview of the process:

Selecting the Sensor: Choose a sensor suitable for your IoT project. Common
sensors include temperature sensors (e.g., DHT11/DHT22), humidity sensors,
light sensors (e.g., LDR), motion sensors (e.g., PIR), and more. Ensure the
sensor you choose has good documentation and, if possible, code examples for
Raspberry Pi.

Wiring: Connect the sensor to the Raspberry Pi. You'll typically need to
connect the sensor's power, ground, and data pins to the appropriate GPIO pins
on the Raspberry Pi. Refer to the sensor's datasheet or documentation for the
pinout information.

Raspberry Pi Setup: Make sure your Raspberry Pi is set up with the necessary
software. This includes installing an operating system R a s p b i a n
O S (e.g., Raspberry Pi OS), enabling SSH if necessary, and ensuring you
have access to GPIO libraries for python programming.

Data Processing and IoT Integration:

Once you can read data from the sensor, you can process it and
integrate it into your IoT project. This might involve sending the data to a
cloud platform (e.g., AWS IoT, Google Cloud IoT, or Azure IoT Hub) or a
local IoT gateway for further processing and storage.

33
Error Handling and Debugging: Implement error handling in your C code
and use debugging techniques to troubleshoot any issues that may arise
during development.

Power Management: Consider how the sensor and Raspberry Pi will be


powered in your IoT application. Depending on your project, you may need
to address power consumption and battery management.

Security: Implement security best practices for your IoT project, especially if
it involves transmitting sensitive data over the internet.

Testing and Deployment:

➢ Thoroughly test your IoT system with the sensor and Raspberry Pi in
different scenarios. Once you're confident in its functionality, deploy
it in your target environment.

➢ Remember that this is a simplified overview, and the specific details


will vary depending on the sensor and IoT platform you're using.

Additionally, consider documenting your project and maintaining clean,


modular code to make future enhancements and maintenance easier.

PROGRAM:

import RPi.GPIO as GPIO


import time

GPIO.setmode(GPIO.BCM)

TRIG = 16
ECHO = 12
i=0

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG, False)
34
print ("Calibrating.....")
time.sleep(2)

print ("Place the object......")

try:
while True:
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)

while GPIO.input(ECHO)==0:
pulse_start = time.time()

while GPIO.input(ECHO)==1:
pulse_end = time.time()

pulse_duration = pulse_end - pulse_start

distance = pulse_duration * 17150

distance = round(distance+1.15, 2)

if distance<=20 and distance>=5:


print ("distance:",distance,"cm")
i=1

if distance>20 and i==1:


print ("place the object....")
i=0
time.sleep(2)

except KeyboardInterrupt:
GPIO.cleanup()

RESULT:
Thus the ultrasonic sensor was interfaced with Raspberry Pi and distance is measured
successfully.

35
EXPT NO: 11
COMMUNICATION BETWEEN ARDUINO
DATE :
AND RASPBERRY PI USING ANY
WIRELESS MEDIUM

AIM:
To communicate between Arduino and Raspberry Pi using any wireless
medium(ESP8266).

HARDWARE / SOFTWARE REQUIREMENTS:


1. Raspberry PI
2. ESP8266
3. Arduino UNO

THEORY:
To communicate between an Arduino and a Raspberry Pi using a
wireless medium in an IoT (Internet of Things) project, you can choose
from several wireless communication protocols such as Wi-Fi, Bluetooth,
Zigbee, LoRa, or MQTT, depending on your specific project requirements.
Here, for an example using Wi-Fi (ESP8266) for communication between
Arduino and Raspberry Pi with python code. We need an Arduino board
with an ESP8266 Wi-Fi module and a Raspberry Pi with Wi-Fi capabilities.

PROCEDURE:
1. BLUETOOTH:
STEP 1: Hardware Setup: Connect a Bluetooth module to both the
Arduino and Raspberry Pi. For Arduino, commonly used modules
include HC-05 or HC-06
STEP 2: Install Required Libraries
STEP 3: Arduino Sketch: Initializes the Bluetooth
module, communication parameters (baud rate, etc.).
STEP 4: Ensure the Raspberry Pi has Bluetooth support and is
discoverable.
STEP 5: Python Script on Raspberry Pi: Discover nearby

36
Bluetooth devices, including the Arduino module.
STEP 6: Define a protocol for data exchange between the two
devices
STEP 7: Implement error handling in both the Arduino sketch and
the Raspberry Pi script.
STEP 8: Test the communication between the Arduino and
Raspberry Pi.
STEP 9: Integrate the wireless communication into your project as
needed and document for future reference.

2.Arduino with ESP8266 (Wi-Fi) - Embedded C Program

➢ Set up the Arduino IDE to program Arduino with ESP8266.


➢ Install the necessary libraries for ESP8266, including the Wi-Fi
library.
➢ Write an Arduino sketch (embedded C program) that connects to
your Wi-Fi network and sends data to the Raspberry Pi over Wi-Fi.

PROCEDURE:
1. Connect pin TX of ESP8266 to RX (set as 3) of Arduino UNO.
2. Connect pin RX of ESP8266 to TX (set as 2) of Arduino UNO.
3. Connect pin ENABLE of ESP8266 to 3.3v(high).
4. Connect pin GND of ESP8266 to GND in Arduino UNO.
5. Connect VCC of ESP8266 to 3.3v in Arduino UNO.
6. Create a Wifi hotspot to get data connectivity for ESP01.
7. Connect Raspberry pi and Arduino to PC using USB-serial communication
cable.
8. Type and run the program.
9. After execution copy the IP address from Thonny IDE (Raspberry
pi environment) to Arduino IDE program.
10. Run the Arduino program.
11. Check the output received in Thonny IDE (Raspberry pi environment)
for random number generated using Arduino program.

37
PROGRAM:

Program to send data from Arduino

#include <SoftwareSerial.h>
#define RX 3
#define TX 2
String AP = "A54"; // AP NAME String PASS = "12345678";
// AP PASSWORD String HOST = "192.168.253.207";
String PORT = "1234";
int countTrueCommand;
int countTimeCommand; boolean found = false; int valSensor = 1;
SoftwareSerial esp8266(RX,TX);

void setup() {
Serial.begin(9600);
esp8266.begin(115200);
sendCommand("AT",5,"OK";
sendCommand("AT+CWMODE=1",5,"OK");
sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
/* String ip = "AT+CIFSR";

sendCommand(ip,5,"OK"); while(esp8266.available())
{
// The esp has data so display its output to the serial window char c =
esp8266.read(); // read the next character.
Serial.write(c); break;
}*/
}

void loop() {
valSensor = getSensorData();
String getData = String(valSensor);
38
sendCommand("AT+CIPMUX=1",5,"OK");
sendCommand("AT+CIPSTART=0,\"UDP\",\""+ HOST +"\","+

PORT,15,"OK");
sendCommand("AT+CIPSEND=0," +String(getData.length()),4,">");
esp8266.println(getData);delay(1500);countTrueCommand++;
sendCommand("AT+CIPCLOSE=0",5,"OK");
}

int getSensorData(){
return random(1000); // Replace with your own sensor code
}

void sendCommand(String command, int maxTime, char readReplay[]) {


Serial.print(countTrueCommand);
Serial.print(". at command => ");
Serial.print(command);
Serial.print(" ");
while(countTimeCommand < (maxTime*1))
{
esp8266.println(command);//at+cipsend
if(esp8266.find(readReplay))//ok
{
found = true; break;
}

countTimeCommand++;
}

if(found == true)
{
Serial.println("OYI");
countTrueCommand++;
countTimeCommand = 0;
}

if(found == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}

39
found = false;
}

Program to receive data using Raspberry Pi:

import network
import socket
import time

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("A54","12345678")

# rgb led
led1=machine.Pin(2,machine.Pin.OUT)
led2=machine.Pin(3,machine.Pin.OUT)

# Wait for connect or fail


wait = 10
while wait > 0:
if wlan.status() < 0 or wlan.status() >= 3: break
wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error

if wlan.status() != 3:
raise RuntimeError('wifi connection failed') else:
print('connected')
ip=wlan.ifconfig()[0]
print('IP: ', ip)

localIP = wlan.ifconfig()[0]
localPort = 1234
bufferSize = 1024

40
# Create a datagram socket
UDPServerSocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

# Bind to address and ip


UDPServerSocket.bind((localIP,
localPort)) print('waiting. ')

while True:
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
m=str(message.decode()) m=m.strip()
print(m)

OUTPUT:

RESULT:
Thus the communication between Arduino and Raspberry PI using wireless
medium - ESP8266 (WiFi Module) has been done.

41
EXPT NO: 12
SETUP A CLOUD PLATFORM TO LOG
DATE :
THE DATA

AIM:
To setup a cloud platform to log the data

THEORY:

ThingSpeak is a cloud space owned by Matlab. Initally, we have to get an


account and create a new channel with say one field and save the channel.
Then next screen appears in which write and read api keys are available.
These keys are noted and used later in the program.

In this experiment, temperature is read and it is stored in the ThingSpeak


cloud space.

Step 1: Sign up ThingSpeak


It is simple just enter your email id and verify your account.

Step 2: Configuring ThingSpeak


Configuration is just few clicks job
Open the ThingSpeak
Step 2.1: Create New Channel
Click on New Channel

42
It creates a new channel in Thing speak for ESP8266

Enter Name and Field. You may have multiple Fields depending on number
of sensor create multiple fields such as Light, Temperature, Humidity, etc.
Enter Name and Label thing speak esp8266

Keep everything else as it is. Blank or default values. and click on Save
Channel. Thing Speak save channel

43
Step 2.2: Getting API Key
Click on API Keys Tab and look for these two fields Write Api Key and
Update channel feed line.

Note Write api key and update a channel feed

This line is important for data upload to cloud server


GET https://api.thingspeak.com/update?api_key=akjshfajkhfowei&field1=0

44
AT commands:
The following are the AT commands used in the program

AT – Attention
AT+ RST - Reset
AT+CWMODE – 1- station , 2 – Access point , 3 - both
AT+ CWJAP+ SSID+PW – join network
AT+CIPMUX – 0 single , 1 – multi
AT+CIPSTART+type+host+port – 0 single, 1 – multiple – ( TCP/UDP)
AT+CIPSEND+datalength+bytes – 0 –single , 1 - multiple
AT+CIPCLOSE – 0 – single , 1 – multiple

Program:

#include <DHT.h> // Including library for dht

#include <ESP8266WiFi.h>

String apiKey = " "; // Enter your Write API key from ThingSpeak

const char *ssid = " "; // replace with your wifi ssid and wpa2 key
const char *pass = " ";
const char* server = "api.thingspeak.com";

#define DHTPIN 0 //pin where the dht11 is connected

DHT dht(DHTPIN, DHT11);

WiFiClient client;

void setup()
{
Serial.begin(115200);
delay(10);
dht.begin();

Serial.println("Connecting to ");
Serial.println(ssid);

45
WiFi.begin(ssid, pass);

while (WiFi.status() != WL_CONNECTED)


{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

void loop()
{
float h = dht.readHumidity();
float t = dht.readTemperature();

if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}

if (client.connect(server,80)) // "184.106.153.149" or api.thingspeak.com


{

String postStr = apiKey;


postStr +="&field1=";
postStr += String(t);
postStr +="&field2=";
postStr += String(h);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");


client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form
-urlencoded\n");
client.print("Content-Length: ");
46
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(h);
Serial.println("%. Send to Thingspeak.");
}
client.stop();

Serial.println("Waiting...");

// thingspeak needs minimum 15 sec delay between updates


delay(1000);
}

OUT PUT:

RESULT:
Thus the cloud platform to log the data using Raspberry Pi has been done
successfully.

47
EXPT NO : 13
LOG DATA USING RASPBERRY PI AND
DATE :
UPLOAD TO THE CLOUD PLATFORM

AIM:
To log data using Raspberry PI and upload to the cloud platform.
APPARATUS REQUIRED:
1. Raspberry Pi 4
2. USB Keyboard & USB Mouse
3. Monitor Cable
4. Ethernet Cable
5. Patch Chords

THEORY:
INTRODUCTION TO IoT
Today the Internet has become ubiquitous, has touched almost every corner
of the globe, and is affecting human life in unimaginable ways.
• We are now entering an era of even more pervasive connectivity where a
very wide variety of appliances will be connected to the web.
• One year after the past edition of the Cluster book 2012 it can be clearly
stated that the Internet of Things (IoT) has reached many different players and
gained further recognition. Out of the potential Internet of Things application
areas, Smart Cities (and regions), Smart Car and mobility, Smart Home and
assisted living, Smart Industries, Public safety, Energy & environmental
protection, Agriculture and Tourism as part of a future IoT Ecosystem have
acquired high attention.

We are entering an era of the “Internet of Things” (abbreviated as IoT).


There are 2 definitions:
First one is defined by Vermesan and second by Pe˜na-L´opez
1. The Internet of Things as simply an interaction between the physical and
digital worlds. The digital world interacts with the physical world using a
plethora of sensors and actuators.

2. Another is the Internet of Things is defined as a paradigm in which


computing and networking capabilities are embedded in any kind of
48
conceivable object.

• We use these capabilities to query the state of the object and to change its
state if possible.
• In common parlance, the Internet of Things refers to a new kind of world
where almost all the devices and appliances that we use are connected to a
network.
• We can use them collaboratively to achieve complex tasks that require a
high degree of intelligence.
• For this intelligence and interconnection, IoT devices are equipped with
embedded sensors, actuators, processors, and transceivers.
• IoT is not a single technology; rather it is agglomeration of various
technologies that work together in tandem.
• Sensors and actuators are devices, which help in interacting with the
physical environment.
• The data collected by the sensors has to be stored and processed
intelligently in order to derive useful inferences from it.
• Note that we broadly define the term sensor; a mobile phone or even a
microwave oven can count as a sensor as long as it provides inputs about its
current state (internal state + environment).
• An actuator is a device that is used to effect a change in the environment
such as the temperature controller of an air conditioner.
• The storage and processing of data can be done on the edge of the network
itself or in a remote server.
• If any preprocessing of data is possible, then it is typically done at either the
sensor or some other proximate device.
• The processed data is then typically sent to a remote server.
• The storage and processing capabilities of an IoT object are also restricted
by the resources available, which are often very constrained due to limitations
of size, energy, power, and computational capability.
• As a result the main research challenge is to ensure that we get the right
kind of data at the desired level of accuracy.
• Along with the challenges of data collection, and handling, there are
challenges in communication as well.
• The communication between IoT devices is mainly wireless because they
are generally installed at geographically dispersed locations.
• The wireless channels often have high rates of distortion and are unreliable.
• In this scenario reliably communicating data without too many
retransmissions is an important problem and thus communication
49
technologies are integral to the study of IoT devices.
• We can directly modify the physical world through actuators or we may do
something virtually. For example, we can send some information to other
smart things.

PROGRAM :

import httplib
import urllib
import time
key = "4IX9VESM09B9MQ7H" # 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 the log data was performed using Raspberry PI and uploaded to
the cloud platform.

50
EXPT NO : 14
DESIGN AN IOT BASED SYSTEM USING
DATE :
RASPBERRY PI PROGRAM

AIM:
To design an IoT based system with Raspberry Pi and Python program in IoT.

PROGRAM:
import sys
import Adafruit_DHT
import time
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4) # GP4 input
print ('Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature,
humidity))
time.sleep(1)

THEORY:

Designing an IoT (Internet of Things) system with an embedded C


program involves several components and steps. In this example, let us
outline a basic IoT system for monitoring environmental conditions
(temperature and humidity) and controlling a connected device (a smart light)
using an python program. Real-world IoT projects can be much more
complex.

COMPONENTS:

 SENSORS:

51
1. Temperature and humidity sensor (e.g., DHT22)
2. Microcontroller (e.g., ESP8266 or ESP32) to interface with the
sensor and connect to Wi-Fi

 ACTUATORS:

Smart light bulb (e.g., a smart bulb with Wi-Fi connectivity)

 COMMUNICATION:

1. Wi-Fi for connecting the microcontroller to the Internet

2. MQTT (Message Queuing Telemetry Transport) protocol for


communication between the IoT devices and a cloud-based broker

 CLOUD SERVER:

A cloud server for receiving sensor data, controlling the smart light,
and storing historical data (e.g., AWS IoT, Google Cloud IoT, or a
custom server)

Python Program:

The Python program will run on the microcontroller and perform the
following tasks:

➢ Read data from the temperature and humidity sensor.


➢ Connect to the Wi-Fi network.
➢ Establish an MQTT connection to the cloud broker.
➢ Publish sensor data to a specific MQTT topic.
➢ Subscribe to an MQTT topic to receive control commands for the
smart light.
➢ Control the smart light based on incoming MQTT messages.

Python Program Flow:

1. Initialize the microcontroller and sensor.

2. Connect to the Wi-Fi network using Wi-Fi credentials.


52
3. Establish an MQTT connection to the cloud broker using MQTT
credentials (username, password, and broker address).

4. Create a loop to periodically read sensor data (temperature and


humidity).
5. Publish the sensor data to an MQTT topic (e.g.,
"sensor/environment").

6. Subscribe to an MQTT topic (e.g., "light/control") to receive control


commands for the smart light.

7. When a control command is received, interpret it (e.g., "turn on,"


"turn off"), and control the smart light accordingly.

8. Repeat the loop to continue monitoring and controlling as needed.

9. Handle error conditions and re-establish connections if necessary.

Cloud Server:

1) Set up an MQTT broker (e.g., Mosquitto) on your cloud server.

2) Create an MQTT topic for receiving sensor data (e.g.,


"sensor/environment") and another for sending control commands to
the smart light (e.g., "light/control").

3) Develop a backend application on the cloud server to:

✓ Receive and store incoming sensor data.


✓ Forward control commands to the smart light.
✓ Implement security measures to ensure data privacy and
authentication.

User Interface:

To interact with your IoT system, you can create a web or mobile
app that connects to the cloud server. This app can display real-time sensor
data, allow users to control the smart light remotely, and provide historical
data analysis.

53
Remember that this is a high-level overview, and implementing an
IoT system involves detailed hardware integration, security considerations,
and scalability planning. Additionally, you may choose different
microcontrollers, sensors, and cloud platforms based on your specific
project requirements.

RESULT:
Thus an IOT based system with Raspberry Pi platform and Python program
has been designed.

54

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy