You are on page 1of 29

Government Engineering College

Ajmer

Lab Manual

DEPARTMENT: COMPUTER SCIENCE AND ENGINEERING

SUBJECT: WEB DEVELOPMENT


Internet LAB
Of Things Lab

SUBJECT CODE: 7CS7A


7CS4-21

Submitted To: Submitted By:


Mr. Deepak Gupta Gaurav Rathore
(20EEACS036)

1
COURSE OUTCOME

After completion of this course, students will be able to –

 Understand the concept of Internet of Things


 Implement interfacing of various sensors with Arduino/Raspberry Pi.
 Demonstrate the ability to transmit data wirelessly between
different devices.
 Show an ability to upload/download sensor data on cloud and
server.
 Examine various SQL queries from MySQL database.
Vision and Mission of Institute
Vision: “To foster harmonious value oriented environment for all in an efficient innovative

manner to contribute nation through excellence in academics and research.”

Mission:

M1: To nurture value oriented competent professionals through conceptual, analytical and
technical knowledge for overall sustainable societal development.

M2: To achieve academic excellence in engineering, technology and science by imparting


quality based education.

M3: To strengthen managerial and entrepreneurial skills to start new ventures.

M4:To inculcate inquisitive and research oriented approach.

Vision and Mission of COMPUTER Department

Vision: “To produce competent professionals in the field of computer science.”

Mission: M1: Prepare the students with strong fundamental concepts, analytical

capability, programming, problem solving skills and strong ethics.

M2: Provide opportunities to promote organizational and leadership skills in students.

M3: To disseminate digital innovation among society.

2
Program Educational Objectives (PEOs)

PEO1: Provide graduates to design and implement solutions for rapidly changing computing problems

and information system environments.

PEO2: To provide the imperative knowledge of science, mathematics and engineering fundamentals for

a computer professional for competent problem solving ability.

PEO3: To exhibit leadership capability, social and economic commitment and responsibility to protect

environment.

PEO4: To prepare the students for pursuing higher studies and develop research orientation.

Program Specific Outcomes (PSOs)

PSO1: Demonstrate understanding of the principles and working of the hardware and software aspects

of computer systems.

PSO2: Understand, analyze and develop computer programs in the areas related to algorithms, system

software, multimedia, web design, big data analytics and networking for efficient design of

computer-based systems of varying complexity.

PSO3: Be acquainted with the contemporary issues, latest trends in technological development and

thereby innovate new ideas and solutions to existing problems.

3
Program outcomes (POs)

Engineering Graduates will be able to:

PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering

fundamentals, and an engineering specialization to the solution of complex engineering

problems.

PO2: Problem analysis: Identify, formulate, review research literature, and analyze complex

engineering problems reaching substantiated conclusions using first principles of mathematics,

natural sciences, and engineering sciences.

PO3: Design/development of solutions: Design solutions for complex engineering problems and

design system components or processes that meet the specified needs with appropriate

consideration for the public health and safety, and the cultural, societal, and environmental

considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and research

methods including design of experiments, analysis and interpretation of data, and synthesis of the

information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern

engineering and IT tools including prediction and modeling to complex engineering activities

with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess

societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to

the professional engineering practice.

4
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions

in societal and environmental contexts, and demonstrate the knowledge of, and need for

sustainable development.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms

of the engineering practice.

PO9: Individual and team work: Function effectively as an individual, and as a member or leader in

diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex engineering activities with the

engineering community and with society at large, such as, being able to comprehend and write

effective reports and design documentation, make effective presentations, and give and receive

clear instructions.

PO11 Project management and finance: Demonstrate knowledge and understanding of the engineering

and management principles and apply these to one’s own work, as a member and leader in a

team, to manage projects and in multidisciplinary environments.

PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in

independent and life-long learning in the broadest context of technological change.

5
Table Of Content

Sr. List of Experiments Page Number


No.
1 Start Raspberry Pi and try various Linix commands in 1
command terminal window:
ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more,
less, ps, sudo, cron, chown, chgrp, ping etc.

2 Run some python programs on Pi like: 3


2.1 Read your name and print Hello message with name 3
2.2 Read two numbers and print their sum, difference, 3
product and division
2.3 Word and character count of a given string. 4
2.4 Area of a given shape (rectangle, triangle and circle) 5
reading shape and
appropriate values from standard input.
3 Run some python programs on Pi like: 6
3.1 Print a name 'n' times, where name and n are read 6
from standard input, using for and while loops.
3.2 Handle Divided by Zero Exception. 6

3.3 Print current time for 10 times with an interval of 10 7


seconds.
3.4 Read a file line by line and print the word count of 8
each line.
4 4.1 Light an LED through Python program 9
4.2 Get input from two switches and switch on 11
corresponding LEDs
4.3 Flash an LED at a given on time and off time cycle, 14
where the two times are taken from a file
5 5.1 Flash an LED based on cron output (acts as an alarm) 17
5.2 Switch on a relay at a given time using cron, where 19
the relay's contact terminals are connected to a load.
5.3 Get the status of a bulb at a remote place (on the 21
LAN) through web.
1. Start Raspberry Pi and try various Linix commands in command
terminal window:
ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps,
sudo, cron, chown, chgrp, ping etc.

Solution:
1) touch: Create a new file or update its timestamp.
Syntax: touch [OPTION]…[FILE]
Example: Create empty files called ‘file1’ and ‘file2’
$ touch file1 file2

2) cat: Concatenate files and print to stdout.


Syntax: cat [OPTION]…[FILE]
Example: Create file1 with entered cotent
$ cat > file1
Hello
^D

3) cp: Copy files


Syntax: cp [OPTION]source destination
Example: Copies the contents from file1 to file2 and contents of file1 is retained
$ cp file1 file2

4) mv: Move files or rename files


Syntax: mv [OPTION]source destination
Example: Create empty
files called ‘file1’ and ‘file2’
$ mv file1 file2

1
5) rm: Remove files and directories
Syntax: rm [OPTION]…[FILE]
Example: Delete file1
$ rm file1

6) mkdir: Make directory


Syntax: mkdir [OPTION] directory
Example: Create directory called dir1
$ mkdir dir1

7) rmdir: Remove a directory


Syntax: rmdir [OPTION] directory
Example: Create empty files called ‘file1’ and ‘file2’
$ rmdir dir1

8) cd: Change directory


Syntax: cd [OPTION] directory
Example: Change working directory to dir1
$ cd dir1

9) pwd: Print the present working directory

Syntax: pwd [OPTION]


Example: Print ‘dir1’ if a current working directory is dir1
$ pwd

2
2. Run some python programs on Pi like:

(a) Read your name and print Hello message with name .
Solution:

(b) Read two numbers and print their sum, difference, product and division.
Solution:

# An addition
5+5
# A subtraction
5-5
# A multiplication
3*5
# A division
(5 + 5) / 2

3
OutPut:
# An addition
>5+5
[1] 10
> # A subtraction
>5-5
[1] 0
> # A multiplication
>3*5
[1] 15
> # A division
> (5 + 5) / 2
[1] 5

(c) Word and character count of a given string .


Solution:

def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('google.com'))

Output:
{'o': 3, '.': 1, 'g': 2, 'l': 1, 'e': 1, 'c': 1, 'm': 1}

4
(d) Area of a given shape (rectangle, triangle and circle) reading shape and
appropriate values .
Solution:

from standard input


# Python Program to find the area of triangle
a=5
b=6
c=7

# Uncomment below to take inputs from the user


# a = float(input('Enter first side: '))
# b = float(input('Enter second side: '))
# c = float(input('Enter third side: '))

# calculate the semi-perimeter


s = (a + b + c) / 2

# calculate the area


area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print('The area of the triangle is %0.2f' %area)

Output:
The area of the triangle is 14.70

5
3. Run some python programs on Pi like:

(a) Print a name 'n' times, where name and n are read from standard input, using for
and while loops.
Solution:
#include
<iostream>
using namespace std;
int main() {
int i, n;
cin >> n;
for (i=0; i<n; i++) {
cout << "hello world\n";
}
return 0;
}

(b) Handle Divided by Zero Exception.


Solution:
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)

6
Output:

The entry is a
Oops! <class 'ValueError'> occured.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError' > occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5

(c) Print current time for 10 times with an interval of 10 seconds.


Solution:

time = float(input("Input time in seconds: "))


day = time // (24 * 3600)
time = time % (24 * 3600)
hour = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
print("d:h:m:s-> %d:%d:%d:%d" % (day, hour, minutes, seconds))

Output:

Input time in seconds: 1234565


d:h:m:s-> 14:6:56:5

7
(d): Read a file line by line and print the word count of each line.
Solution:

fname = input("Enter file name: ")


num_lines = 0
with open(fname, 'r') as f:
For in f:
num_lines += 1
print("Number of lines:")
print(num_lines)

Output: Runtime Test Cases

Case 1:
Contents of file:
Hello world

Output:
Enter file name: data1.txt

Number of lines:
1

Case 2:
Contents of file:
This programming language is
Python

Output:
Enter file name: data2.txt
Number of lines:
2

8
4 (a) Light an LED through Python program.

Solution:

Create a new text file “LED.py” by typing the following:


nano LED.py

Type in the following code:


import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)
Once you have typed all the code and checked it, save and exit the text editor with
“Ctrl + x”
then “y” then “enter”.

To run this code type:


sudo python LED.py

You will see the LED turn on for a second and then turn off.
If your code does not run and an error is reported, edit the code again using nano
LED.py.

9
Explanation:

import RPi.GPIO as GPIO The first line tells the Python interpreter
(the thing that runs the Python code it
will be using a ‘library’ that will tell it
how to work with the Raspberry Pi’s
GPIO pins. programming language extra
commands that used to do something
different that it previously did not know
how to do. This is like adding a new
channel to your TV so you can watch
something different.

import time Imports the Time library so that we can


pause the script later on.

GPIO.setmode(GPIO.BCM) Each pin on the Raspberry Pi has several


different names, so you need to tel
program which naming convention is to
be used.
GPIO.setwarnings(False)

This tells Python not to print GPIO


warning messages to the screen.

GPIO.setup(18,GPIO.OUT) This line tells the Python interpreter that


pin 18 is going to be used for outpu
information, which means you are going
to be able to turn the pin ‘on’ and ‘o’
print "LED on" This line prints some information to the

10
terminal.

GPIO.output(18,GPIO.HIGH) This turns the GPIO pin ‘on’. What this


actually means is that the pin is made
provide power of 3.3volts. This is enough
to turn the LED in our circuit on.

time.sleep(1) Pauses the Python program for 1 second

print "LED off" This line prints some information to the


terminal.

GPIO.output(18,GPIO.LOW) This turns the GPIO pin ‘off’, meaning


that the pin is no longer supplying an
power.

4 (b) Get input from two switches and switch on corresponding LEDs
Controlling an LED by a Button
Solution:
Components:
- 1* Raspberry Pi
- 1* Breadboard
- 1* LED
- 1* Button
- 1* Resistor
- Jumper wires

11
Principle:

Buttons are a common component used to control electronic devices. They are
usually used as switches to connect or disconnect circuits. Although buttons come in
a variety of sizes and shapes, the one used here is a6mmmini-button as shown in
the following pictures. Pins pointed out by the arrows of same color are meant to be
connected.

When the button is pressed, the pins pointed by the blue arrow will connect to the
pins pointed cby the red arrow (see the above figure), thus closing the circuit.

Experimental Procedures:

Step 1: Build the circuit

Step 2: Change directory


cd /home/pi/Sunfounder_SuperKit_ Python_code_for_RaspberryPi/

write the program in Python

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

LedPin = 11 # pin11 --- led


BtnPin = 12 # pin12 button
Led_status = 1

def setup():

12
GPIO.setmode(GPIO.BOARD) # Numbers GPIOs byphysical location
GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output
GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Set BtnPin's mode is input, and pull up to high level(3.3V)
GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led

def swLed(ev=None):
global Led_status
Led_status = not Led_status
GPIO.output(LedPin, Led_status) # switch led status(on>off; off>o
if Led_status == 1:
print 'led off...'
else:
print '...led on'

def loop():
GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed,
bouncetime=200)
# wait for falling and set bouncetime to prevent the callback function from
being called multiple times when the button is pressed
while True:
time.sleep(1) # Don't do anything

def destroy():
GPIO.output(LedPin, GPIO.HIGH) # led off
GPIO.cleanup() # Release resource
if __name__ == '__main__': # Program start from here
setup()
try:
loop()

13
except KeyboardInterrupt:
# When'Ctrl+C' is pressed, the child program destroy() will be
# executed.
destroy()

Step 3: Run
sudo python 02_btnAndLed.py

Now, press the button, and the LED will light up; press the button again,and the LED
will go out.

At the same time, the state of the LED will be printed on the screen.

4 (c) Flash an LED at a given on time and off time cycle, where the two
times are taken from a file.

Solution:
Components required:
 One led
 100 ohm resistor
 Jumper cables

Raspberry Pi GPIO Specifications:

 Output Voltage : 3.3V


 Maximum Output Current : 16mA per pin with total current from all pins not exceeding
50mA

14
For controlling a Led using Raspberry Pi, both python and the GPIO libraryis needed.

Installing Python GPIO Library:


Note: Python and GPIO library are preinstalled if you are using Raspbian.

 Make sure your Rasperry Pi is connected to the internet using either a LAN cable or a
WiFi adapter.
 Open the terminal by double clicking the LXTerminal icon
 Type the following command to download the GPIO library as a tarball

wget http://raspberry-gpio-python.googlecode.com/files/RPi.GPIO-0.4.1a.tar.gz

 Unzip the tarball

tar zxvf RPi.GPIO-0.4.1a.tar.gz

 Change the directory to unzipped location

cd RPi.GPIO-0.4.1a

 Install the GPIO library in python

sudo python setup.pyinstall

 Raspberry Pi GPIO Pin Out:


Raspberry Pi has 17 GPIO pins out of 26 pins

 Python Programming:

Open Terminal
Launch IDLE IDE by typing
sudo idle

15
This launches IDLE with superuser privileges which is necessary execute scripts for
controlling the GPIO pins

After the IDLE launches, open a new window by FILE>OPEN or Ctrl+N

Type the code below in the window

import time
import RPi.GPIO as GPIO ## Import GPIO library
GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
GPIO.setup(11, GPIO.OUT) ## Setup GPIO Pin 11 to OUT
while True:
GPIO.output(11,True) ## Turn on Led
time.sleep(1) ## Wait for one second
GPIO.output(11,False) ## Turn off Led
time.sleep(1) ## Wait for one second

Save the code by FILE>SAVE or Ctrl+S

To run your code RUN>RUN or Ctrl+F5

The Led will start blinking now.

16
5 (a) Flash an LED based on cron output (acts as an alarm)
Solution :

import RPi.GPIO as GPIO


import time

# Define LED pin


LED_PIN = 11

# Define blink duration


BLINK_DURATION = 1

def setup():
# Set GPIO mode to BOARD
GPIO.setmode(GPIO.BOARD)

# Configure LED pin as output


GPIO.setup(LED_PIN, GPIO.OUT)

def blink():
while True:
# Turn LED on
GPIO.output(LED_PIN, GPIO.HIGH)
time.sleep(BLINK_DURATION)

# Turn LED off


GPIO.output(LED_PIN, GPIO.LOW)
time.sleep(BLINK_DURATION)

def cleanup():
# Turn LED off

17
GPIO.output(LED_PIN, GPIO.LOW)

# Release GPIO resources


GPIO.cleanup()

if __name__ == "__main__":
setup()
try:
blink()
except KeyboardInterrupt:
cleanup()

18
5 (b) Switch on a relay at a given time using cron, where the relay's
contact terminals are connected to a load.

Solution :

Add the following cron entry to run the script at the desired alarm time:

@alarm_time python /path/to/blink.py

Switch on a relay at a given time using cron:


import RPi.GPIO as GPIO
import time

# Define relay pin


RELAY_PIN = 18

# Define switch-on time


SWITCH_ON_TIME = "10:00"

def setup():
# Set GPIO mode to BOARD
GPIO.setmode(GPIO.BOARD)

# Configure relay pin as output


GPIO.setup(RELAY_PIN, GPIO.OUT)

def switch_on():
# Turn relay on
GPIO.output(RELAY_PIN, GPIO.HIGH)

19
def switch_off():
# Turn relay off
GPIO.output(RELAY_PIN, GPIO.LOW)

def is_time_to_switch_on():
# Get current time
current_time = datetime.datetime.now().strftime("%H:%M")

# Compare current time with switch-on time


if current_time == SWITCH_ON_TIME:
return True
else:
return False

def cleanup():
# Turn relay off
GPIO.output(RELAY_PIN, GPIO.LOW)

# Release GPIO resources


GPIO.cleanup()

if __name__ == "__main__":
setup()

if is_time_to_switch_on():
switch_on()
else:
switch_off()

# Keep the script running


while True:
time.sleep(60) # Check time every minute

20
cleanup()
5 (c) Get the status of a bulb at a remote place (on the LAN) through web
Solution :
import requests
# Define bulb's IP address
BULB_IP = "192.168.1.100"

# Define bulb's status URL


BULB_STATUS_URL = f"http://{BULB_IP}/status"

def get_bulb_status():
try:
response = requests.get(BULB_STATUS_URL)

if response.status_code == 200:
# Check for "on" in response data
if "on" in response.text:
return True
else:
return False
else:
raise Exception("Failed to get bulb status")
except Exception as e:
print(f"Error: {e}")
return None

if __name__ == "__main__":
bulb_status = get_bulb_status()

if bulb_status is True:

21
print("Bulb is on")
elif bulb_status is False:
print("Bulb is off")
else:
print("Failed to get bulb status")

22

You might also like