You are on page 1of 61

Department of Artificial Intelligence & Data Science

Lab Manual

Internet of Things Laboratory


(217531)

Second Year of Engineering


Semester II
Academic Year 2021-22
Vision
To create globally recognized AI&DS Engineers for sustainable
development.

Mission
To meet the current & future demands of the nation in the area of AI&DS.

To produce high-quality students technically superior, professionally &


ethically strong.

To inculcate the interdisciplinary skillset required to fulfil a societal need.

Program Education Objectives (PEOs)

PEO1:Graduates will have the capabilities to apply AI&DS knowledge to


develop feasible systems.
PEO2:Graduates will be able to handle the challenges of rapidly changing
technology.

PEO3:Equip the graduates with strong technical knowledge, competency


in soft skills, lifelong learning skills that allow them to contribute ethically
to the need of society.

Program Specific Outcomes (PSOs)


PSO1 Problem Solving and Programming Skills:Graduates will be able
to practically apply the knowledge of various programming languages
and data analytics tools and techniques.
PSO2 Professional Skills:Graduates will be able to apply the knowledge
of software engineering principles and practices to the multidisciplinary
areas of AI&DS to meet the needs of the industry and society.
PSO3 Successful Career:Graduates will be able to become
entrepreneur and to pursue higher studies / career in software
industries. Program Outcomes (POs)
Graduates will be able to

1. Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering


specialization to the solution of complex engineering problems. [Engineering knowledge]
2. Identify, formulate, research literature, and analyse complex engineering problems reaching
substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences. [Problem analysis]
3. 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. [Design/development of solutions]
4. 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. [Conduct
investigations of complex problems]
5. 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. [Modern tool usage]
6. 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.
[The engineer and society]
7. Understand the impact of the professional engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for sustainable development. [Environment
and sustainability]
8. Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice. [Ethics]
9. Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings. [Individual and team work]
10. 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.
[Communication]
11. 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. [Project management and finance]
12. 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. [Life-long learning]
Sr Group Title of Assignment CO PO PSO
.
No
Bridge the gap: Introduction of 8086, 8088
1 A
microprocessor and 8051 microcontroller.
Study of Raspberry-Pi/ Beagle board/ and other
2 A microcontroller ( History & Elevation) C203.1 1,2,3,4,5,8,9,10 1,2

Study of different operating systems for Raspberry-Pi


3 A /Beagle board/. Understanding the process of OS C203.2 1,2,3,4,8,9,10 1,2
installation
Study of different GATES (AND, OR, XOR), Sensors and 1,2,3,4,5,
4 A C203.3 1,2
basic binary operations. 8,9,10
Study of Connectivity and configuration of Raspberry-
5 A Pi /Beagle board/ circuit with basic peripherals like LEDS. C203.4 1,2,3,4,8,9,10 1,2
Understanding GPIO and its use in the program.
Write a program using Raspberry Pi to control LED (One
6 B C203.5 1,2,3,4,8,9,10 1,2
or more ON/OFF). Or Blinking
Write a program that asks the user for a number and
7 B C203.5 1,2,3,4,8,9,10 1,2
outputs the number squared that is entered
Write a program read the temperature sensor and send the
8 B C203.6 1,2,3,4,5,8,9,10 1,2
values to the serial monitor on the computer
Write a program so it displays the temperature in
1,2,3,4,5,
9 B Fahrenheit as well as the maximum and minimum C203.6 1,2,3
8,9,10
temperatures it has seen
10 Write a program to show the temperature and shows a 1,2,3,4,5, 1,2,3
B C203.6
graph of the recent measurements 8,9,10
Write a program using piezo element and use it to play a 1,2,3,4,5, 1,2,3
11 B C203.6
tune after someone knocks 8,9,10
Understanding the connectivity of Raspberry-Pi /Beagle
1,2,3,4,5, 1,2,3
12 B board circuit / with IR sensor. Write an application to C203.6
8,9,10
detect obstacle and notify user using LEDs
Create a program so that when the user enters ‘b’ the green
1,2,3,4,5, 1,2,3
13 B light blinks, ‘g’ the green light is illuminated ‘y’ the yellow C203.6
8,9,10
light is illuminated and ‘r’ the red light is illuminated
Write an application to control the operation of hardware
1,2,3,4,5, 1,2,3
14 C simulated traffic signals. (Mini Project: Same can be done C203.6
8,9,10
parallel with PBL)
15 C Content Beyond syllabus:
Case study of any computes/Control Application on
Raspberry Pi.
Assignment No. : 1
Title
BRIDGE THE GAP: Introduction of 8086, 8088 microprocessor and 8051 microcontroller.

Objectives

Outcomes
Students will be able to study the interfacing of 8086,8085 & 8051
Software
8085Microprocessor, 8051 Microcontroller.
Theory
8085: (1977)
1. 8-bit microprocessor - upgraded version of the 8080.
2. 64KB main memory.
3. 1.3 microseconds clock cycle time; 769,230 instructions/sec.
4. 246 instructions.
5. Intel sold 100 million copies of this 8-bit microprocessor.
a. 8086: (1978) 8088 (1979)
6. 16-bitmicroprocessor.
7. 1MB main memory. o 2.5 MIPS (400 ns).
8. 4- or 6-byte instruction cache.
9. Other improvements included more registers and additional instructions.
a. 80286: (1983)
10. 16-bit microprocessor very similar in instruction set to the 8086.
11. 16MB main memory.
12. 4.0 MIPS (250 ns/8MHz).
Bus Interface Unit (BIU)

The Bus Interface Unit (BIU) manages the data, address and control buses.

The BIU functions in such a way that it:

● Fetches the sequenced instruction from the memory,


● Finds the physical address of that location in the memory where the instruction is stored and
● Manages the 6-byte pre-fetch queue where the pipelined instructions are stored.
An 8086 microprocessor exhibits the property of pipelining the instructions in a queue while
performing decoding and execution of the previous instruction. This saves the processor time of
operation by a large amount. This pipelining is done in a 6-byte queue. Also, the BIU contains 4
segment registers. Each segment register is 16-bit. The segments are present in the memory and these
registers hold the address of all the segments. These registers are as follows:

1.Code segment register: It is a 16-bit register and holds the address of the instruction or program
stored in the code segment of the memory.
Also, the IP in the block diagram is the instruction pointer which is a default register that is used by
the processor in order to get the desired instruction. The IP contains the offset address of the next byte
that is to be taken from the code segment.
2. Stack segment register: The stack segment register provides the starting address of the stack
segment in the memory. Like in stack pointer, PUSH and POP operations are used in this segment to
give and take the data to/from it.
3. Data segment register: It holds the address of the data segment. The data segment stores the data
in the memory whose address is present in this 16-bit register.
4. Extra segment register: Here the starting address of the extra segment is present. This register
basically contains the address of the string data.
It is to be noteworthy that the physical address of the instruction is achieved by combining the
segment address with that of the offset address.

8086 microprocessor Intel 8086

o Intel 8086 microprocessor is the enhanced version of Intel 8085 microprocessor. It was
designed by Intel in 1976.
o The 8086 microprocessor is a16-bit, N-channel, HMOS microprocessor. Where the HMOS is
used for "High-speed Metal Oxide Semiconductor".
o Intel 8086 is built on a single semiconductor chip and packaged in a 40-pin IC package. The
type of package is DIP (Dual Inline Package).
o Intel 8086 uses 20 address lines and 16 data- lines. It can directly address up to 220 = 1 Mbyte
of memory.
o It consists of a powerful instruction set, which provides operation like division and
multiplication very quickly.
o 8086 is designed to operate in two modes, i.e., Minimum and Maximum mode.

Conclusion:

_________________________________________________________________________________

_________________________________________________________________________________
Assignment No. : 2
TITLE

Study of Raspberry-Pi, Beagle board, .


OBJECTIVES

To study IoT platforms such as Raspberry-Pi/Beagle board/.


PROBLEM STATEMENT

OUTCOME

Students will be able to understand IoT platforms such as Raspberry-Pi/Beagle board/


SOFTWARE & HARDWARE REQUIREMENTS

Software Compatibility
● Debian
● Android
● Ubuntu
● Cloud9 IDE on Node.js w/ BoneScript library
THEORY-CONCEPT

Internet of Things: - IoT is short for Internet of Things. The Internet of Things refers to the ever- growing
network of physical objects that feature an IP address for internet connectivity, and the communication that
occurs between these objects and other Internet-enabled devices and systems. The Internet of Things (IoT)
refers to the use of intelligently connected devices and systems to leverage data gathered by embedded
sensors and actuators in machines and other physical objects. In other words, the IoT (Internet of Things)
can be called to any of the physical objects connected with network.
Examples of IoT: -
● Apple Watch and Home Kit.
● Smart Refrigerator.
● Smart Refrigerator.
● Smart cars.
● Google Glass.
● Smart thermostats.
Raspberry-Pi:- The Raspberry Pi is a series of small single-board computers developed in the United
Kingdom by the Raspberry Pi Foundation to promote teaching of basic computer science in schools and in
developing countries. It does not include peripherals (such as keyboards and mice). The Raspberry Pi is a
low cost, credit-card sized computer that plugs into a computer monitor or TV, and uses a standard
keyboard and mouse. It is a capable little device that enables people of all ages to explore computing, and to
learn how to program in languages like Scratch and Python. The Raspberry Pi is a credit-card-sized
computer that costs between $5 and $35. It's available anywhere in the world, and can function as a proper
desktop computer or be used to build smart devices. A Raspberry Pi is a general-purpose computer, usually
with a Linux operating system, and the ability to run multiple programs. Raspberry Pi is like the brain. Its
primary advantage comes in processing higher level processing capability. It’s a single board computer.

Fig.A.1: - Raspberry-Pi Fig. A.2: -Raspberry-Pi Architecture

Here are the various components on the Raspberry Pi board:


● ARM CPU/GPU -- This is a Broadcom BCM2835 System on a Chip (SoC) that's made up of an
ARM central processing unit (CPU) and a Video core 4 graphics processing unit (GPU). The CPU
handles all the computations that make a computer work (taking input, doing calculations and
producing output), and the GPU handles graphics output.
● GPIO -- These are exposed general-purpose input/output connection points that will allow the real
hardware hobbyists the opportunity to tinker.
● RCA -- An RCA jack allows connection of analog TVs and other similar output devices.
● Audio out -- This is a standard 3.55-millimeter jack for connection of audio output devices such as
headphones or speakers. There is no audio in.
● LEDs -- Light-emitting diodes, for your entire indicator light needs.
● USB -- This is a common connection port for peripheral devices of all types (including your mouse
and keyboard). Model A has one, and Model B has two. You can use a USB hub to expand the
number of ports or plug your mouse into your keyboard if it has its own USB port.
● HDMI -- This connector allows you to hook up a high-definition television or other compatible
device using an HDMI cable.
● Power -- This is a 5v Micro USB power connector into which you can plug your compatible power
supply.
● SD card slot -- This is a full-sized SD card slot. An SD card with an operating system (OS) installed
is required for booting the device. They are available for purchase from the manufacturers, but you
can also download an OS and save it to the card yourself if you have a Linux machine and the
wherewithal.
● Ethernet -- This connector allows for wired network access and is only available on the Model B.

B) Beagle board:- The Beagle Board is a low-power open-source single-board computer produced by
Texas Instruments in association with Digi-Key and Newark element14. The Beagle Board was also
designed with open source software development in mind, and as a way of demonstrating the Texas
Instrument's OMAP3530 system-on-a-chip.]The board was developed by a small team of engineers as
an educational board that

C) could be used in colleges around the world to teach open source hardware and software capabilities. It is
also sold to the public under the Creative Commons share-alike license. The board was designed using
Cadence OrCAD for schematics and Cadence Allegro for PCB manufacturing; no simulation software
was used. Beagle

D) Bone Black is a low-cost, open source, community-supported development platform for ARM®
Cortex™-A8 processor developers and hobbyists. Boot Linux in under 10-seconds and get started on
Sitara™ AM335x ARM Cortex-A8 processor development in less than 5 minutes with just a single
USB cable.
Fig.B.1: -Beagle Board Black Fig.B.1: - Beagle Board Black architecture

Here are the various components on the Beagle board:

Processor:

1. AM335x 1GHz ARM® Cortex-A8

2. 512MB DDR3 RAM

3. 4GB 8-bit eMMC on-board flash storage

4. 3D graphics accelerator

5. NEON floating-point accelerator

6. 2x PRU 32-bit microcontrollers

Connectivity

1. USB client for power & communications

2. USB host

3. Ethernet

4. HDMI

5. 2x 46 pin headers
Software Compatibility

● Debian

● Android

● Ubuntu

● Cloud9 IDE on Node.js w/ BoneScript library

● plus, much more

:- is an open-source hardware and software company, project and user community that designs and
manufactures single-board microcontrollers and microcontroller kits for building digital devices and interactive
objects that can sense and control objects in the physical and digital world. board designs use a variety of
microprocessors and controllers. The boards are equipped with sets of digital and analog input/output (I/O)
pins that may be interfaced to various expansion boards or breadboards (shields) and other circuits. The boards
feature serial communications interfaces, including Universal Serial Bus (USB) on some models, which are
also used for loading programs from personal computers. The microcontrollers are typically programmed using
a dialect of features from the programming languages C and C++. In addition to using traditional compiler tool
chains, the project provides an integrated development environment (IDE) based on the Processing language
project. is open-source hardware. The hardware reference designs are distributed under a Creative Commons
Attribution Share-Alike

2.5 license and are available on the website. Layout and production files for some versions of the hardware are
also available.

Fig.C.1: - Board Fig.C.1: - Architecture.


Diecimila and early Duemilanove) ATmega8 (used on some older board) on the board:
● Microcontrollers

● ATmega328P (used on most recent boards) Here are the various components

● ATmega168 (used on most

Digital Pins
In addition to the specific functions listed below, the digital pins on an board can be used for
general purpose input and output via the pinMode(), digitalRead(), and digitalWrite() commands.
Each pin has an internal pull-up resistor which can be turned on and off using digitalWrite() (w/ a
value of HIGH or LOW, respectively) when the pin is configured as an input. The maximum
current per pin is 40 mA.

Analog Pins
In addition to the specific functions listed below, the analog input pins support 10-bit analog-to-
digital conversion (ADC) using the analogRead() function. Most of the analog inputs can also be
used as digital pins: analog input 0 as digital pin 14 through analog input 5 as digital pin 19.
Analog inputs 6 and 7 (present on the Mini and BT) cannot be used as digital pins.

Power Pins

● VIN (sometimes labelled "9V"). The input voltage to the board when it's using an external
power source (as opposed to 5 volts from the USB connection or other regulated power
source). You can supply voltage through this pin, or, if supplying voltage via the power
jack, access it through this pin. Note that different boards accept different input voltages
ranges, please see the documentation for your board. Also note that the LilyPad has no VIN
pin and accepts only a regulated input.

Other Pins
● AREF. Reference voltage for the analog inputs. Used with analogReference().
● Reset. (Diecimila-only) Bring this line LOW to reset the microcontroller. Typically used
to add a reset button to shields which block the one on the board.
● Analog Reference pin (orange)
● Digital Ground (light green)
● Digital Pins 2-13 (green)
● Digital Pins 0-1/Serial In/Out - TX/RX (dark green) - These pins cannot be used for
digital i/o (digitalRead and digitalWrite) if you are also using serial
communication (e.g. Serial.begin).
● Reset Button - S1 (dark blue)
● In-circuit Serial Programmer (blue-green)
● Analog In Pins 0-5 (light blue)
● Power and Ground Pins (power: orange, grounds: light orange)
● External Power Supply In (9-12VDC) - X1 (pink)
● Toggles External Power and USB Power (place jumper on two pins closest to desired
supply) - SV1 (purple)
● USB (used for uploading sketches to the board and for serial communication between
the board and the computer; can be used to power the board) (yellow)
Conclusion: -
Assignment No. : 3
Title
Study of different operating systems for Raspberry-Pi/Beagle board/. Understanding the process of
OS installation on Raspberry-Pi/Beagle board
Objectives
To study operating systems for platforms such as Raspberry-Pi/Beagle board/
Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Theory
Theory:
1) Raspberry-Pi: - The Pi can run the official Raspbian OS, Ubuntu Mate, Snappy Ubuntu Core,
the Kodi- based media centers OSMC and LibreElec, the non-Linux based Risc OS (one for
fans of 1990s Acorn computers). It can also run Windows 10 IoT Core, which is very different
to the desktop version of Windows, as mentioned below.
● OS which install on Raspberry-Pi: Raspbian, Ubuntu MATE, Snappy Ubuntu, Pidora, Linutop,
SARPi, Arch Linux ARM, Gentoo Linux, etc.

⮚ How to install Raspbian on Raspberry-Pi:

Step 1: Download Raspbian

Step 2: Unzip the file. The Raspbian disc image is compressed, so you’ll need to unzip it. The file
uses the ZIP64 format, so depending on how current your built-in utilities are, you need to use
certain programs to unzip it.

Step 3: Write the disc image to your microSD card. Next, pop your microSD card into your
computer and write the disc image to it. The process of actually writing the image will be slightly
different across these programs, but it’s pretty self-explanatory no matter what you’re using. Each of
these programs will have you select the destination (make sure you’ve picked your microSD card!)
and the disc image (the unzipped Raspbian file). Choose, double-check, and then hit the button to
write.

Step 4: Put the microSD card in your Pi and boot up. Once the disc image has been written to the
microSD card, you’re ready to go! Put that sucker into your Raspberry Pi, plug in the peripherals
and power source, and enjoy. The current edition to Raspbian will boot directly to the desktop. Your
default credentials are username pi and password raspberry.
2) BeagleBone Black: - The BeagleBone Black includes a 2GB or 4GB on-board eMMC flash
memory chip. It comes with the Debian distribution factory pre-installed. You can flash new
operating systems including Angstrom, Ubuntu, Android, and others.
1. Os which install on BeagleBone Black: Angstrom, Android, Debian, Fedora, Buildroot,
Gentoo, Nerves Erlang/OTP, Sabayon, Ubuntu, Yocto, MINIX 3

⮚ How to install Debian on BeagleBone Black:

Step 1: Download Debian img.xz file.

Step 2: Unzip the file.

Step 3: Insert your MicroSD (uSD) card into the proper slot. Most uSD cards come with a full-sized
SD card that is really just an adapter. If this is what you have then insert the uSD into the adapter,
then into your card reader.

Step 4: Now open Win32 Disk imager, click the blue folder icon, navigate to the debian img
location, and double click the file. Now click Write and let the process complete. Depending on your
processor and available RAM it should be done in around 5 minutes.

Step 5: Alright, once that's done, you'll get a notification pop-up. Now we're ready to get going.
Remove the SD adapter from the card slot, remove the uSD card from the adapter. With the USB
cable disconnected insert the uSD into the BBB.

Step 6: Now, this next part is pretty straight forward. Plug the USB cable in and wait some more. If
everything is going right you will notice that the four (4) leds just above the USB cable are doing the
KIT impression. This could take up to 45 minutes, I just did it again in around 5 minutes. Your
mileage will vary. Go back and surf reddit some more.

Step 7: If you are not seeing the leds swing back and forth you will need to unplug the USB cable,
press and hold down the user button above the uSD card slot (next to the 2 little 10 pin ICs) then
plug in the USB cable. Release the button and wait. You should see the LEDs swinging back and
forth after a few seconds. Once this happens it's waiting time. When all 4 LEDs next to the USB slot
stay lit at the same time the flash process has been completed.

Step 8: Remove the uSD card and reboot your BBB. You can reboot the BBB by removing and
reconnecting the USB cable, or hitting the reset button above the USB cable near the edge of the
board.

Step 9: Now using putty, or your SSH flavor of choice, connect to the BBB using the IP address
192.168.7.2. You'll be prompted for a username. Type root and press Enter. By default, there is no
root password. I recommend changing this ASAP if you plan on putting your BBB on the network.
To do this type password, hit enter, then enter your desired password. You will be prompted to enter
it again to verify.

Conclusion:

Assignment No. : 4
Title
Study of different GATES (AND, OR, XOR), Sensors and basic binary operations.

Objectives
● To understand the concept of Logic gates, sensors
● To understand the common anode & common cathode configuration.

Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro USB
Cable
Theory

Logic Gates are the building blocks of Digital Systems. They are basically used to perform logical
operations by acting as a switch. Boolean Functions are implemented using Logic Gates. A Logic
Gate accepts the input and operates on a required condition. If a certain condition is true, it turns
“ON” and goes “OFF” when the condition is false.

Types of Logic Gates

There are seven types of Logic Gates. They are:

● NOT Gate (Inverter)


● AND Gate (Multiplication)
● OR Gate (Addition)
● NAND Gate
● NOR Gate
● XOR Gate
● XNOR Gate

NOT Gate (Inverter)

The output of NOT Gate is ‘High’ if the input is ‘Low’ and Vice versa.

AND Gate (Multiplication)

The output of AND Gate is ‘High’ if both the inputs are High and the output is ‘Low’ if both or either
of the inputs is low.

OR Gate (Addition)

The output of OR Gate is ‘High’ if both the inputs are ‘High’ or one of the inputs is ‘High’. The
output is ‘Low’ if both the inputs are ‘Low’.
Fig. 5 – Symbol and Truth Table of OR Gate

NAND Gate

The output of NAND Gate is ‘High’ if both the inputs are ‘Low’ and if either of the input is ‘Low’.
The output is ‘Low’ if both the inputs are ‘High’

Fig. 6 – Symbol and Truth Table of NAND Logic Gates

NOR Gate

The output of NOR Gate is ‘High’ if both the inputs are ‘Low’. The output is ‘Low’ if both the inputs
are ‘High’ or either of the input is ‘High’

Fig. 7 – Symbol and Truth Table of NOR Logic Gates

XOR Gate

The output of XOR Gate is ‘High’ if either of the input is ‘High’. The output is ‘Low’ if both the
inputs are ‘High’ or if both the inputs are ‘Low’.
Fig. 8 – Symbol and Truth Table of XOR Gate

XNOR Gate

The output of XNOR Gate is ‘High’ if both the inputs are ‘High’ or if both the inputs are ‘Low’. The
output is ‘Low’ if either of the input is ‘Low’

Fig. 9 – Symbol and Truth Table of XNOR Gate

Working Principle of Logic Gates

To understand the working principle of Logic Gates, let us consider the example of Street Lighting
System. Fig below shows the Circuit Diagram of Street Lighting System which mainly consists of
Logic Gate (s) (NOT and OR Gate), Switch and Light Sensor. The operational condition for the street
light to function is as follows:

Based on this, we can prepare a Truth Table as shown in Fig. 10

Fig. 10 – Circuit Diagram of Street Lighting System and Truth Table


Applications of Logic Gates

The applications of Logic Gates are:

● NAND Gates are used in Burglar alarms and buzzers.

● They are basically used in circuits involving computation and processing.

● They are also used in push button switches. E.g. Door Bell.

● They are used in the functioning of street lights.

● AND Gates are used to enable/inhibit the data transfer function.

● They are also used in TTL (Transistor Transistor Logic) and CMOS circuitry.

Advantages of Logic Gates

The advantages of Logic Gates are:

● Logical Operations are performed using Boolean Algebra which makes the circuit design more
economical and simple.

● Logic ‘1’ and Logic ‘0’ can be easily distinguished.

Disadvantages of Logic Gates

The disadvantages of Logic Gates are:

● Operating Voltage is limited.

● Time delay occurs between input and output.

Conclusion:
Assignment No. : 5
Title
Study of Connectivity and configuration of Raspberry-Pi /Beagle board/ circuit with basic peripherals
like LEDS. Understanding GPIO and its use in the program.
Objectives
● To understand the concept of Led bar
● Generate various patterns on LED bar.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro
USB Cable
Theory
Algorithm:
1. Import GPIO and Time library
2. Set mode i.e. GPIO.BOARD
3. Set GPIO 8 pins as a Output pin
4. Print message “ON”
5. After 1 second time delay, Make all the leds ON one by one
6. Print message “OFF”
7. After 1 second time delay, Make all the leds OFF one by one.

Observation:
∙ See output on Command prompt or Python shell
Write a program using to control LED (One or more ON/OFF). Or Blinking:
1. import RPi.GPIO as GPIO
2. import time
3. LED_PIN = 17
4. GPIO.setmode(GPIO.BCM)
5. GPIO.setup(LED_PIN, GPIO.OUT)
6. GPIO.output(LED_PIN, GPIO.HIGH)
7. time.sleep(1)
8. GPIO.output(LED_PIN, GPIO.LOW)
9. GPIO.cleanup()
This program will power on the LED for one second, and then power it off. Let’s break the program
down line by line.

1. import RPi.GPIO as GPIO


2. import time

First we import the RPi.GPIO Python module which will allow us to control all GPIOs from the
Raspberry Pi’s GPIO header. You’ll see that this module is quite easy to use.

We also import the time module which we’ll use later to wait for 1 second.

1. LED_PIN = 17

As a best practice, we create a “constant” global variable containing the GPIO number for the LED.
This will allow you to use the variable name instead of the number directly. You will make less
mistakes, and in the future if you want to change the LED’s GPIO, you just have to update this
variable.

1. GPIO.setmode(GPIO.BCM)

This line should be the first line you execute with the RPi.GPIO module. This will allow you to use
the GPIO numbers instead of the “standard” pin numbers.

For example, you can see here that GPIO 17 corresponds to pin number 11. And the pin number 17
is a 3.3V power pin.

If you don’t set the mode to BCM, then you might end up controlling the wrong pin for your LED.

1. GPIO.setup(LED_PIN, GPIO.OUT)

OK, now we can start setting up the GPIO for the LED. We need to use the GPIO.setup() function
and provide the mode of the GPIO: either GPIO.OUT for output, or GPIO.IN for input. As we want
to tell the LED what to do, instead of reading its state, we have to use GPIO.OUT.

1. GPIO.output(LED_PIN, GPIO.HIGH)
2. time.sleep(1)
3. GPIO.output(LED_PIN, GPIO.LOW)

All the setup is finished, we can power on/off the LED. To do that you just have to use one simple
command: GPIO.output(), with either GPIO.HIGH to power on the LED, or GPIO.LOW to power off
the LED.

1. GPIO.cleanup()

And we finish the program by cleaning up the GPIOs, with GPIO.cleanup(). This line is super
important. It will reset all states and modes for all GPIOs, which can prevent you from having errors
in future programs. Or even worse, fry your Raspberry Pi (if now you put a push button in GPIO 17
and try to read from it, and the GPIO hasn’t been cleaned up, then you’ll have a problem).

Note: in this situation, writing GPIO.output(LED_PIN, GPIO.LOW) was not mandatory because
GPIO.cleanup() will do that automatically.

Make sure the LED GPIO is cleaned up every time


To be sure that the LED GPIO (and all other GPIOs) is cleaned up every time we kill the Python
program, we’ll use a try/catch structure, to be able to “catch” the CTRL+C, so we can do an action
just before the program exits.

2. import RPi.GPIO as GPIO


3. import time
4. LED_PIN = 17
5. GPIO.setmode(GPIO.BCM)
6. GPIO.setup(LED_PIN, GPIO.OUT)
7. try:
8. while True:
9. GPIO.output(LED_PIN, GPIO.HIGH)
10. time.sleep(1)
11. GPIO.output(LED_PIN, GPIO.LOW)
12. time.sleep(1)
13. except KeyboardInterrupt:
14. GPIO.cleanup()
Conclusion:
Assignment No. : 06
Title
Write a program using Raspberry Pi to control LED (One or more ON/OFF). Or Blinking
Objectives
To perform the controlling operation LED.
Outcomes
Studied with small application interface to raspberry pi.
Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro USB
Cable.
Theory

RGB LEDs consist of three LEDs, one red, one green and one blue. These three colored LEDs are capable of
producing any color. Tri-color LEDs with red, green, and blue emitters, in general using a four-wire
connection with one common lead (anode or cathode). These LEDs can have either common anode or common
cathode leads.

What we used in this experiment is the common anode RGB LED. The longest pin is the common
anode of three LEDs. The pin is connected to the +3.3V pin of the Raspberry Pi, and the three
remaining pins are connected to the Raspberry Pi‘s pin11, pin12, pin13 through a current limiting
resistor.
In this way, we can control the color of RGB LED by 3-channel PWM signal.
Key function:
● int softPwmCreate (int pin, int initialValue, int pwmRange)
This creates a software controlled PWM pin. You can use any GPIO pin and the pin numbering will
be that of the wiringPiSetup() function you used. Use 100 for the pwmRange, then the value can be
anything from 0 (off) to 100 (fully on) for the given pin.
The return value is 0 for success. Anything else and you should check the global errno variable to see
what went wrong. - 39 -
● void softPwmWrite (int pin, int value)
This updates the PWM value on the given pin. The value is checked to be in-range and pins that haven‘t
previously been initialised via softPwmCreate will be silently ignored.
Procedures
1. Build the circuit

By learning this lesson, I believe that you have already known the principle and the programming of RGB
LED. I hope you can use your imagination to achieve even more cool ideas based on this lesson.

Conclusion:

Assignment No. : 07
Title
Write a program that asks the user for a number and outputs the number squared that is entered

Objectives
● To understand the concept of Python IDE for squaring any number.
● To interface LED bar with Raspberry Pi.
∙ Generate various patterns on LED bar.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro USB Cable.

Theory

Before heading to code, let’s start with the basics to get everyone on the same page.

6² – Here 6 is the base and 2 is the exponent. So, it equals to 6 times 6 (6 * 6). We can also read it like
6 raised to 2.
But more generally, we generally refer it as Square.

How to calculate the square of any number?


We just need to multiply the value with itself.
e.g.
5² = 5 * 5 = 25
6² = 6 * 6 = 36

Note
-> No matter, if the value is positive or negative, the square of any number is always positive.
Python – Code to Calculate Square Of any Number – All Methods
What is a Square of Number?
Before heading to code, let’s start with the basics to get everyone on the same page.

6² – Here 6 is the base and 2 is the exponent. So, it equals to 6 times 6 (6 * 6). We can also read it like
6 raised to 2.
But more generally, we generally refer it as Square.

How to calculate the square of any number?


We just need to multiply the value with itself.
e.g.
5² = 5 * 5 = 25
6² = 6 * 6 = 36

Note
-> No matter, if the value is positive or negative, the square of any number is always positive.
Python 3 – Function to get Square of a number
1 # Take the number as input   
2 number = int(input('Enter a number to get its square '))
3  
4 # Define a function to calculate Square
5 def calculateSquare(num):
6     return num*num
7  
8 # print the output
9 print("Square of ",number, "is ", calculateSquare(number))
Output

number = int(input('Enter a number to get its square '))


First Of all, we are taking input from the user. And then typecasting it into an Integer. Because by
default, input() function returns the String.

def calculateSquare(num):
return num*num

This is the function that takes the Integer and returns the Square of that Integer.

print("Square of ",number, "is ", calculateSquare(number))

Finally, we are passing the number calculateSquare(number) and simultaneously printing the output


as well.

Python 3 – Function to get Square of a number

1 # Take the number as input   


2 number = int(input('Enter a number to get its square '))
3  
4 # Define a function to calculate Square
5 def calculateSquare(num):
6     return num*num
7  
8 # print the output
9 print("Square of ",number, "is ", calculateSquare(number))

Conclusion:

Assignment No. : 8
Title
Write a program read the temperature sensor and send the values to the serial monitor on the
computer.
Objectives
● To understand the concept of Piezo element.
● To interface LED bar with Raspberry Pi.
∙ Generate various patterns on LED bar.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro
USB Cable.

Theory

Piezo buzzer
is an electronic device commonly used to produce sound. Light weight, simple construction
and low price make it usable in various applications like car/truck reversing indicator, computers, call
bells etc. • Piezo buzzer is based on the inverse principle of piezo electricity discovered in 1880 by
Jacques and Pierre Curie.

Temperature Sensor – DHT11


The DHT11 temperature and humidity sensor is a nice little module that provides digital temperature
and humidity readings. It’s really easy to set up, and only requires one wire for the data signal. •
These sensors are frequently used in remote weather stations, soil monitors, and home environment
control systems. The programming is simple too, and many libraries and example code in both
Python and C already exist.
The DHT11 contains a surface mounted NTC thermistor and a resistive humidity sensor. An IC on
the back of the module converts the resistance measurements from the thermistor and humidity sensor
into digital outputs of degrees Celsius and Relative Humidity.

Fact sheet – DHT11


• Ultra low cost
• 3 to 5V power and I/O
• 2.5mA max current use during conversion (while requesting data)
• Good for 20–80% humidity readings with 5% accuracy • Good for 0–50°C temperature readings
±2°C accuracy
• No more than 1 Hz sampling rate (once every second)
• Body size 15.5mm x 12mm x 5.5mm
• 4 pins with 0.1" spacing

Temperature Sensor – DHT11


• There are two variants of the DHT11 you’re likely to come across. One is a four pin stand alone
module, and the other is a three pin, PCB mounted module. The pinout is different for each one, so
connect the DHT11 according to which one you have:

Circuit Diagram – DHT11


• VCC of DHT11 -> 5v Pin of Raspberry Pi 3
• GND of DHT11 -> GND Pin of Raspberry Pi 3
• Signal pin of DHT11 -> GPIO 4 Pin of Raspberry Pi3

Programming the DHT11 in Python


• We will be using the Adafruit DHT11 Python library. We can download the library using Git, so if
you don’t have Git installed on your Pi already, enter this at the command prompt: sudo apt-get
install git-core
• Note: If you get an error installing Git, run sudo apt-get update and try it again

Install the Adafruit DHT11 library


Enter this at the command prompt to download the library:
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
Change directories with:
cd Adafruit_Python_DHT
Enter this:
sudo apt-get install build-essential python-dev
Install the library with:
sudo python setup.py install

Program:
Import Adafruit_DHT
while True:
hum temp= adafruit_DHT.read_retry(11,4)
Print “ temperature:”, temp
Print “ humidity: “, hum

Conclusion:

Assignment No. : 9
Title
Write a program so it displays the temperature in Fahrenheit.
Objectives
● To understand the concept of Temperature sensor.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS, Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD
Card with Raspbian ∙ Micro USB Cable.

Theory

Temperature Sensor – DHT11


• There are two variants of the DHT11 you’re likely to come across. One is a four pin stand alone
module, and the other is a three pin, PCB mounted module. The pinout is different for each one, so
connect the DHT11 according to which one you have:

Circuit Diagram – DHT11


• VCC of DHT11 -> 5v Pin of Raspberry Pi 3
• GND of DHT11 -> GND Pin of Raspberry Pi 3
• Signal pin of DHT11 -> GPIO 4 Pin of Raspberry Pi3

Programming the DHT11 in Python


• We will be using the Adafruit DHT11 Python library. We can download the library using Git, so if
you don’t have Git installed on your Pi already, enter this at the command prompt: sudo apt-get
install git-core
• Note: If you get an error installing Git, run sudo apt-get update and try it again

Install the Adafruit DHT11 library


Enter this at the command prompt to download the library:
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
Change directories with:
cd Adafruit_Python_DHT
Enter this:
sudo apt-get install build-essential python-dev
Install the library with:
sudo python setup.py install

Program:
Import Adafruit_DHT
while True:
hum temp= adafruit_DHT.read_retry(11,4)
Print “ temperature:”, temp
Print “ humidity: “, hum
Conclusion:

Assignment No. : 10
Title
Write a program to show the temperature and shows a graph of the recent measurements
Objectives
● To understand the concept of Temperature sensor.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS, Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with
Raspbian ∙ Micro USB Cable. Humidity or Temperature sensor.

Theory

Imagine you are measuring temperature in weather stations in a particular city or region. From my
research, albeit limited, this weather is often measured to tenths of a degree (for whatever reason).
You start collecting data over a ten year period, measuring daily and monthly maximum and
minimum temperatures and this data is compiled on an excel spreadsheet.

A new year passes, let's assume its 2015 and you continue measuring the temperature as you always
do. You have been observing record highs and lows and heatwaves around the country during 2015.
You start wondering how temperatures of this year are measuring against temperatures over the
previous 10 years. You want to answer the question; how do the record highs and lows for each
month that has passed this year measure against record highs for each month set over the last 10
years.
You decide that the best way to present these findings is through a visualization of a line chart that
will show the record highs and lows of each month over the last 10 years. To answer your current
question you also want to superimpose a scatterplot of the record highs and lows from 2015 that
either exceed the record lows or highs set over the last 10 years. So now you have a question and you
know what you need to develop to answer your question. You decide to write out the code in Python.
In order to help with your visualization you will need to import certain libraries that will help you
perform many complex actions without writing lengthy and complex code.
import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#read data from a csv
df =
pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd0
75c2700843b89.csv')

For this visualization we would want to use the datetime library to stipulate a cut-off date so that we
can divide the data into 2 tables; i.) temperature measurements between 2005 and the 31st of
December 2014 and ii.) measurements occurring after the cutoff date.

Numpy which is short for numerical python will allow us to carry out mathematical functions on
multi-dimensional matrices and arrays.

The pandas and library will allow us to carry out manipulations and calculations on the dataframes we
will be interacting with. While matplotlib will be used for plotting our graphs. We use the aliases pd
and plt (and np for numpy) to interact with these libraries for ease of reference.

The next line of code then uses the read_csv module included in the pandas library to read the data
we want from our csv. This is automatically saved as a pandas dataframe — we named this dataframe
'df'.

At this point I like to use the head method to read the top 5 rows of our dataframe. This helps me
understand what columns the dataframe has and just get a better feel of what the data looks like
df.head()

Output

Now we know that the dataframe has 4 columns; ID, Date, Element, and Data_Value. There is also an
index column listing the row number starting from zero. The dataframe contains a total of 165 085
rows

You notice from this that the measurements are categorised as either TMAX (the maximum
temperature) and TMIN (the minimum temperature). The ID shows the station identification code
which presumably shows which station took the measurements.
Removing leap year data

Since 2015 is not a leap year, we want to remove all leap year data. In the event that a leap year had
record high/low temperatures over the 10 year period as this could have an impact on record high/low
temperature measurements. Since 2015 would have 1 less day than years with leap years (2008 and
2012) this wouldn’t be an accurate comparison.
#converting date to date timestamp
df['Date'] = pd.DatetimeIndex(df['Date']).date
lis = ['2922008','2922012'] #list of 29 Febs appearing in each leap year
dates = [datetime.datetime.strptime(i, '%d%m%Y').date() for i in lis] #converting into list of
datetime.date objects
df = df[~df['Date'].isin(dates)] #remove all 29 February dates

In this code we convert the entire Date column using the DatetimeIndex module. This converts the
Date column into a timestamp object. We then specify with .date that we want to return a
datetime.date object (‘the date time of the timestamp without the timezone information’).

Using the datetime.date library, we convert our list of leap year dates into a datetime.date object. We
then only select the dates that are not listed as leap year dates (under the list ‘lis’) and filter out all
leap year dates from our dataframe.

Dates, cutoff dates and dividing dataframe into 2 tables

Next, since we have ensured that all the Dates in the date column are the same data type (that they are
all dates and not string for example), we want to divide the data into two tables based on whether the
measurements occurred before or after the cutoff date.
#creating a separate column for the month
df['Month'] = pd.DatetimeIndex(df['Date']).month
#we are colleting dates between 2005 - 2014, so want to remove any data from dates after 31 Dec
2014
#creating datetime.date format of cutoff date
a= '31122014'
#converting a string into datetime.date object
cutoff_date = datetime.datetime.strptime(a,'%d%m%Y').date()
#dataframe for values after 31 Dec 2014
df2 = df[df['Date'] <= cutoff_date]
#returning dates before cutoff date
df3 = df[df['Date'] > cutoff_date]

Since we want our table to show us monthly highs over a ten year period we also want to create a
month column. Listing only the month of the Date column as an integer.
For the cutoff date we added the date as an integer and used the datetime.date module to convert the
string into a datetime.date object (similar to our Date column), in 'date/month/year' format.

We then proceed to create 2 new dataframes; df2- which contains all the measurements before or on
the cutoff date and df3- which contains all the measurements after the cutoff date.

Finding record highs and lows

Now we need to answer the question, how do we find the record high and low temperatures over the
ten years between 2005 and 2014 by month.

From looking at our dataframe with the head method we already know that there is a column that
specifies whether a measurement is recorded as a minimum of maximum temperature. Additionally,
since we have created a month column, we know that this contains the month in which the
measurement was recorded. In order to help us carry out this computation we will use groupby. This
is a pandas module that allows us to split data into groups based on one or more criterions. This can
be combined with the aggregation method, 'aggregate' which lets us carry out aggregations on our
data such as returning the maximum or minimum values. Combined with groupby we can identify the
maximum and minimum values between the groups we have created grouped by month.
df_min = df2[df2['Element'] =='TMIN'].groupby('Month').aggregate({'Data_Value':np.min})
df_max = df2[df2['Element'] == 'TMAX'].groupby('Month').aggregate({'Data_Value':np.max})

In this code, we created 2 dataframes; df_min- here we filtered measurements classified as minimum
temperatures, grouped them by month and found the lowest temperature for each month over the ten
year period and df_max- we filtered measurements classified as maximum temperatures, grouped
them by month and found the highest temperature for each month.

The Visualization process

Now we want to start making use of the matplotlib library to visualize our data.
plt.plot(df_max, '-o',df_min,'-o')
plt.show() output

We start off by plotting the record highs and lows over the ten year period as a line chart. These two
will automatically be plotted in different colours. We used '-o' to identify each data value plotted on
this chart, this is represented as a circle on our line chart.

For visualization purposes we want to shade the area between the highest and lowest point grey. I
believe this will make the data easier on the eye, helping you focus on the highest and lowest
temperatures and the variability of record temperatures over the ten year period.
x = df_max.index.values
plt.fill_between(x,df_min.values.flatten(),df_max.values.flatten(), color='grey',alpha='0.5')

plt.show() output

We use the fill_between module to fill the area between the two lines. For fill_between to function
you need to have the length of the x coordinates that you want to fill and the coordinates/values from
both df_min and df_max.
To find the length of the x coordinates we have created an x variable that contains the values of the
index of df_max. This will return an numpy array containing the numbers 1–12 corresponding with
the months of the year.

Since df_min and df_max are dataframes and we only want the values in the dataframes (the
temperatures) of both df_min and df_max. However, this will return an array of arrays whereas we
need a one dimensional array to use the fill_between module. We then opt to flatten the array into a
one dimensional array. Color and alpha simply allow us to specify the colour and hue of the
fill_between.

Super imposing scatterplot

To answer our central question we need to start looking at the recordings after the cutoff date. In
order to do this we need to group the data by month and look for measurements that exceed the
lowest and highest recorded temperatures on our line chart.
#superimpose scatterplot
df3_max = df3[df3['Data_Value'] > df3['Month'].map(df_max['Data_Value'])]
df4_min = df3[df3['Data_Value'] < df3['Month'].map(df_min['Data_Value'])]
plt.scatter(df3_max.Month.tolist(),df3_max['Data_Value'],s=10,c='red') #values over max
plt.scatter(df4_min.Month.tolist(),df4_min['Data_Value'],s=10,c='black') #values under min

plt.show() output

In order to compare each temperature grouped my month to the lowest and highest temperatures of
each month, we use the map function to iterate through the df3 database, identify the month of each
column and compare the temperature listed under the Data_Value column to the value listed for that
particular month in the df_min and df_max dataframes (depending on whether we are looking at the
minimum or maximum temperatures). If the value is higher or lower than the highest and lowest
temperatures recorded over the ten year period, we add that row to our new dataframes; df3_max and
df4_min.
Now we want to superimpose our scatterplot over our line chart. For the scatter plot we need to
specify the x (months) and y axis (data values). We also want to specify the size of the circle
representing each value and the colour to differentiate it from the line chart circles.

Making the chart easier to interpret

If you are planning on showing this chart to anyone else, it is important to make sure that the chart is
easy to interpret and shows what you want it to show without misleading your audience.

The first problem with the chart as it stands is that the x-axis incrementing in 2s skipping odd number
months.
plt.xticks(list(df_max.index),['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec']) #we
want to show all the x values and rename according to the month

In order to rectify this I specify the xticks and rename them as abbreviations of the months they
represent.

The next issue pertains to how the temperature is recorded. We would want to show the temperature
in degrees celsius and no as tenths of a degree.
df_max['Data_Value'] = df_max['Data_Value']/10
df_min['Data_Value'] = df_min['Data_Value']/10
df4_min['Data_Value'] = df4_min['Data_Value']/10
df3_max['Data_Value'] = df3_max['Data_Value']/10

plt.show() output — I mistakenly left out April bur corrected this error

I then divide all the temperature values by ten to convert tenths of a degree to degrees celsius.
The final issue is that the graph is not labelled, and the size makes it difficult for us to know how
many days in were recorded as exceeded the monthly high or low temperature.
plt.title('Min and Max temperatures in Ann Arbor Michigan United States between 2005-2015',
fontsize=20)
plt.xlabel('Years', fontsize=20)
plt.ylabel('Temperatures', fontsize=20)
fig = plt.gcf()
fig.set_size_inches(20,10)
plt.tick_params(labelsize=20)
plt.show()

plt.show() output

I then proceed to enlarge the chart by first getting the current figure (gcf), saving it as fig and setting
the size of fig in inches. Since this will only enlarge the figure I need to also enlarge the x and y tick
parameters and the font size of both the y and x label.

From this chart we get identify that we had about 6 days in February were the minimum temperatures
dropped below the lowest minimum temperature recorded between 2005 and 2014 for the month of
February and 2 other days that occurred in November and December were the temperatures exceeded
any high that had been previously recorded over a ten year period. The meaning of this interpretation
will be largely dependant on the question you are trying to answer with this visualization.

This is not the only way to represent this data as you may opt to show the highest recorded
temperature for each individual day over the course of ten years and use that to identify individual
days after 2015 that have exceeded those previously set record highs and lows. If anything doing this
would probably give you a clearer picture of how the year 2015 is measuring up in terms of records
temperatures (the solution shouldn't be too different).

Conclusion:

Assignment No. : 11
Title
Write a program using piezo element and use it to play a tune after someone knocks
Objectives
● To understand the concept of Piezo element.
● To interface LED bar with Raspberry Pi.
∙ Generate various patterns on LED bar.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro
USB Cable.

Theory

A piezo is an electronic device that generates a voltage when it's physically deformed by a vibration, sound
wave, or mechanical strain. Similarly, when you put a voltage across a piezo, it vibrates and creates a tone.
Piezos can be used both to play tones and to detect tones.

The sketch reads the piezo output using the analogRead() command, encoding the voltage range from 0 to 5
volts to a numerical range from 0 to 1023 in a process referred to as analog-to-digital conversion, or ADC. If
the sensors output is stronger than a certain threshold, your board will send the string "Knock!" to the
computer over the serial port.

Hardware Required

1. Board

2. Piezo electric disc

3. 1 Megaohm resistor

4. solid surface

Circuit

Piezos are polarized, meaning that voltage passes through them (or out of them) in a specific direction.
Connect the black wire (the lower voltage) to ground and the red wire (the higher voltage) to analog pin 0.
Additionally, connect a 1-megohm resistor in parallel to the Piezo element to limit the voltage and current
produced by the piezo and to protect the analog input.

It is possible to acquire piezo elements without a plastic housing. These will look like a metallic disc, and are
easier to use as input sensors. PIezo sensors work best when firmly pressed against, taped, or glued their
sensing surface.
/*
Knock Sensor

This sketch reads a piezo element to detect a knocking sound. It reads an analog pin and compares
the result to a set threshold. If the result is greater than the threshold, it writes "knock" to the serial
port, and toggles the LED on pin 13.
The circuit:
- positive connection of the piezo attached to analog in 0
- negative connection of the piezo attached to ground
- 1 megohm resistor attached from analog in 0 to ground
// these constants won't change:
const int ledPin = 13; // LED connected to digital pin 13
const int knockSensor = A0; // the piezo is connected to analog pin 0
const int threshold = 100; // threshold value to decide when the detected sound is a knock or not
// these variables will change:
int sensorReading = 0; // variable to store the value read from the sensor pin
int ledState = LOW; // variable used to store the last LED status, to toggle the light
void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as as OUTPUT
Serial.begin(9600); // use the serial port
}
void loop() {
// read the sensor and store it in the variable sensorReading: sensorReading =
analogRead(knockSensor);
// if the sensor reading is greater than the threshold:
if (sensorReading >= threshold) // toggle the status of the ledPin:
ledState = !ledState; // update the LED pin itself:
digitalWrite(ledPin, ledState) // send the string "Knock!" back to the computer, followed by
newline
Serial.println("Knock!");
}
delay(100); // delay to avoid overloading the serial port buffer
Schematic

Conclusion:

Assignment No. : 12
Title
Understanding the connectivity of Raspberry-Pi /Beagle board circuit / with IR sensor. Write an application to
detect obstacle and notify user using LEDs
Objectives
● To understand the concept of IR sensor.
● To interface LED bar with Raspberry Pi.
∙ Generate various patterns on LED bar.
Outcomes

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro
USB Cable.

Theory
1. Infra-Red (IR) LED Transmitter and Receiver.
An Infrared light emitting diode (IR LED) is a special purpose LED emitting infrared rays ranging
from 700 nm to 1 mm wavelength. Different IR LEDs may produce infrared light of differing
wavelengths, just like different LEDs produce light of different colors. IR LEDs are usually made
of gallium arsenide or aluminum gallium arsenide. Along with IR receivers, these are commonly
used as sensors.

The appearance of IR LED is same as a common LED. Since the human eye cannot see the
infrared radiations, it is not possible for a person to identify if an IR LED is working. A camera on
a cell phone camera solves this problem. The IR rays from the IR LED in the circuit are shown in
the camera.

It is necessary to modulate the emission from IR diode to use it in electronic application to prevent
spurious triggering. Modulation makes the signal from IR LED stand out above the noise. Infrared
diodes have a package that is opaque to visible light but transparent to infrared. The IR receiver
that we are using is TSOP1738 which is set to receive a modulating frequency of 38KHz.

IR Receiver: TSOP1738.
TSOP1738 is a very commonly used IR receiver . It has only 3 pins, Vcc, GND and Output. It can
be powered using a 5V power supply and its active low output can be directly connected to a
microcontroller or microprocessor. It has high immunity against ambient light and other electrical
disturbances. It is able to transfer data up to 2400 bits per second. The PCM carrier frequency of
TSOP1738 is 38KHz.

We use a 555 timer IC to generate this 38KHZ signal which we feed to the IR transmitter.
For receiving signals send by the transmitter you need only TSOP1738. Connect 5V to Vs and
Ground to GND pin of TSOP1738. The output will be active low. Output of TSOP1738 will be
HIGH when no signals fall on it and the output will be LOW when 38KHz infrared rays fall on it.

Key Points in the source code:


import time #import time module for delay functions import
RPi.GPIO as GPIO #import rpi-gpio module to access gpio
RUNNING = True
HIGH = 1
LOW = 0
DetectPin = 5 #use pin 5 as IR Receiver input to rpi def
InitSystem():
#pin definitions between processor and raspberry pi GPIO.
GPIO.setmode(GPIO.BCM)

#set 5 as input so that the output state of IR receiver is detected


GPIO.setup(DetectPin,GPIO.IN,pull_up_down=GPIO.PUD_UP) return

def DetectPerson():
while True:
input_state = GPIO.input(DetectPin) #detect pin state time.sleep(0.3)
if input_state == 0: #if state is LOW then no obstacle return LOW
else:
return HIGH #if state is HIGH then obstacle present
try:
print "\nCounting using IR LED\n"
print "\n"
InitSystem()
count =0; while RUNNING:
state = DetectPerson()
if state == HIGH:
count+=1
print "person count =%d" %count
Conclusion:
Assignment No. : 13
Title
Create a program so that when the user enters ‘b’ the green light blinks, ‘g’ the green light is illuminated ‘y’
the yellow light is illuminated and ‘r’ the red light is illuminated.
Objectives
● To interface LED bar with Raspberry Pi.
∙ Generate various patterns on LED bar.
Outcomes
Students are able to write a program so that when the user enters ‘b’ the green light blinks, ‘g’ the green
light is illuminated ‘y’ the yellow light is illuminated and ‘r’ the red light is illuminated.

Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro
USB Cable.

Theory
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 in this experiment will be a 12mm button as shown in the following pictures. Pins pointed
out by the arrows of same color are meant to be connected.

The button we used is a normally open type button. The two contacts of a button is in the off state
under the normal conditions, only when the button is pressed they are closed.
The schematic diagram we used is as follows:
The button jitter must be happen in the process of using. The jitter waveform is as the flowing:

Each time you press the button, the Raspberry Pi will think you have pressed the button many times
due to the jitter of the button. We must to deal with the jitter of buttons before we use the button. We
can remove the jitter of buttons through the software programming, besides, we can use a capacitance
to remove the jitter of buttons. Here we introduce the software method. First, we detect whether the
level of button interface is low level or high level. When the level we detected is low level, 5~10 MS
delay is needed, and then detect whether the level of button interface is low or high. If the signal is
low, we can confirm that the button is pressed once. You can also use a 0.1uF capacitance to clean up
the jitter of buttons. The schematic diagram is shown in below:

● GPIO.input(channel)
This is used for reading the value of a GPIO pin. Where channel is the channel number based on the
numbering system you have specified (BOARD or BCM)). This will return either 0 / GPIO.LOW /
False or 1 / GPIO.HIGH / True.
● GPIO.add_event_detect(channel, mode)
The event_detected( ) function is designed to be used in a loop with other things, but unlike polling it
is not going to miss the change in state of an input while the CPU is busy working on other things.
This could be useful when using something like Pygame or PyQt where there is a main loop listening
and responding to GUI events in a timely basis.

Conclusion:
Assignment No. : 14
Title
Write an application to control the operation of hardware simulated traffic signals. (Mini Project: Same can be
done parallel with PBL)
Objectives
To make a smart traffic system using Raspberry Pi and Python.
Outcomes
To use the GPIO pins on your Raspberry Pi to interface with electronic components, such as LEDs, Buzzer
and buttons.
Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro USB Cable.

Theory

Raspberry Pi needs NOOBS OS. NOOBS is a way of making setting up a Raspberry Pi for the first
time much, much easier. You won't need network access, and you won't need to download imaging
software. Just head to the download page, grab a copy of the NOOBS zip file and unpack it onto a
freshly formatted 4GB (or larger) SD card. Once you have installed an operating system, your Pi will
boot as normal.
 
 
GPIO pins 
 
One powerful feature of the Raspberry Pi is the row of GPIO pins along the top edge of the board.
GPIO stands for General-Purpose Input/Output. These pins are a physical interface between the
Raspberry Pi and the outside world.
 
If you don't have a pin label, then this can help you to identify the pin numbers
 
3.3 volts           
    
Anything connected to these pins will always get 3.3 v of power.
 
5 volts 
   
Anything connected to these pins will always get 5 v of power.
 
GND
 
Zero volts, used to complete a circuit
 
GPIO
   
These pins are for general-purpose use and can be configures as input or output pins
 
ID_SC/ID_SD/DNC
 
Special purpose pins. 
 
Lighting an LED 
 
LEDs are delicate little things. if you put too much current through them they will pop. To limit the
current going through the LED, you should always use a register in series with it.
 
Long leg an LED to the Pi 3.3v and the short leg to a GND pin. Automatically LED will turn ON
 
 
If you connect special purpose(GPIO) pin are connect to a long leg, make sure to write the import
code.
  
Switching an LED on and off
 
GPIO Zero is a new Python library which provides a simple interface to everyday GPIO component.
It comes installed by default in Rasbian.
 
Open IDLE(Integrated Development Environment), which you can use to write and run code.
 
Raspbian Menu Icon >> Programming >> Python 3 (IDLE). 

● To create a new file in IDLE, You can click on File and then New File in IDLE's menu bar. 
● Create a new file by clicking File >> New File
● Save the new file by clicking File >> Save. Save the file as trffic.py
● You'll need the LED Class, and to tell it that the LED is on pin 17. Write the following code in
your new file.
1. from gpiozero import LED    
2. led = LED(17)  

● To make the LED switch on, type the following and press Enter
1. led.on()  
● To make it switch off you can type 
1. led.off()  
  Your LED should switch on and then off again. But that's not all you can do. Similarly checks the
Buzzer and Button. Just import a Buzzer and Button for the header file.
 
Making Traffic Light
 
We need a breadboard, three LEDs, a button, a buzzer, and the necessary jumper cables and registers.
 
Wiring
 
First, you need to understand how each component is connected.
● A push-button requires 1 ground pin and 1 GPIO pin
● An LED requires 1 ground pin and 1 GPIO pin, with a current limiting register
● A buzzer requires 1 ground pin and 1 GPIO pin
Place the components on the breadboard and connect them to the Raspberry Pi GPIO pins, according
to the following diagram.
 

 
Component GPIO pin 
 
   Button                           21
   Red LED                       25
   Yellow LED                    8
   Green LED                    7
   Buzzer                           15
 
This is the same as the Switching and LED on and off step
● Open Python 3 from the main menu
● Create a new file just save with the project name.py
Add TrafficLight, Button and Buzzer Code
1. from gpiozero import Button, TrafficLights, Buzzer    
2. from time import sleep    
3.     
4. buzzer = Buzzer(15)    
5. button = Button(21)    
6. lights = TrafficLights(25, 8, 7)    
7.     
8. while True:    
9.            button.wait_for_press()   
10.            buzzer.on()   
11.            light.green.on()    
12.            sleep(1)    
13.            lights.amber.on()    
14.            sleep(1)    
15.            lights.red.on()    
16.            sleep(1)    
17.            lights.off()   
18.            buzzer.off()  
OUTPUT
 
Run your Powershell coding (F5)
 

Finally, we have successfully created a smart traffic system using a Raspberry Pi.

Conclusion:
Assignment No. : 15
Title
Case study of any computes/Control Application on Raspberry Pi.
Objectives
To perform the controlling operation.
Outcomes
Studied with small application interface.
Software
Raspberry Pi Kit, Raspbian OS,
Required devices: ∙ Ethernet Cable ∙ Laptop/ PC ∙ SD Card with Raspbian ∙ Micro USB
Cable.

Theory:
The Raspberry Pi is being increasingly adopted as a suitable platform in both research and applications of the
Internet of Things (IoT). This study presents a novel project-based teaching and learning approach devised in
an Internet of Things course for undergraduate students in the computer science major, where the Raspberry Pi
platform is used as an effective vehicle to greatly enhance students’ learning performance and experience. The
devised course begins with learning simple hardware and moves to building a whole prototype system. This
paper illustrates the outcome of the proposed approach by demonstrating the prototype IoT systems designed
and developed by students at the end of one such IoT course. Furthermore, this study provides insights and
lessons regarding how to facilitate the use of the Raspberry Pi platform to successfully achieve the goals of
project-based teaching and learning in IoT. The Internet of Things (IoT) has been envisioned as the next wave
in the era of cyber technology, in which millions of smart devices (including various sensors and actuators) are
wirelessly connected and integrated via the Internet. This emerging paradigm will fundamentally create and
boost a number of new applications across many fields, including environmental monitoring, precision
agriculture smart grids smart cities and e-health systems. It is of critical importance to provide the next
generation of computer scientists and engineers an opportunity to not only understand the concepts and
principles of IoT, but also to study the practical development of IoT solidly, so that students can learn how to
apply theories to real applications. Many universities have started to introduce IoT courses into their
undergraduate curriculum. Project-based learning (PBL) can provide great opportunities for students to
enhance their engineering understanding and skills. Students can not only gain theoretical knowledge from
lectures, but also obtain valuable hands-on experience in real-world project practice, where they can actively
improve their abilities in self-motivated learning, self-efficacy problem solving, adaptation to interdisciplinary
thinking and collaborative learning. The PBL approach also helps with improving the achievement of low-
performing students. Real-world projects demand real resources. For example, wireless communication-
enabled tiny computers are essential for students to program and experiment with in any IoT project. The
invention of the Raspberry Pi, an inexpensive, tiny and relatively powerful computer board, not only provides
a great building block to facilitate research and various IoT application developments, but also provides a
desirable hardware platform for the project-based learning paradigm in computer science and engineering
education. Educators have exploited Raspberry Pi either as a single device. For most students, the Raspberry Pi
is a totally new computation platform, which is quite different from their own computers, smart phones or
tablets. It is a necessity to then make students familiar with the hardware platform and the basic software
development environment; this is the main purpose of the first project. In the first step of this project, students
are asked to go through the Raspberry Pi system installation and configuration guide, and to run the Blink
application, toggling an LED through a GPIO pin. In Step 2, by learning the code logic and circuit of the Blink
application, students are asked to build an application with four LEDs and two buttons, in which buttons are
used to increase/decrease the frequency of the LED’s blinking, and three LEDs are used to display the
frequency level. In Step 3, students are required to use a temperature sensor and turn on/off an LED if the
temperature is above/below a threshold. Students are encouraged to mimic the example code to build their own
application, once they learn the usage of GPIO pins in both directions. Upon the successful completion of
Project 1, students will have learned how to build a simple single-node (i.e., smart device) system with
sensors/actuators based on the Raspberry Pi platform.
. Raspberry Pi Stock Ticker The Raspberry Pi stock ticker system tracks selected stock prices in real time and
notifies the user in multiple ways when the stock price changes within a certain amount. It was a client/server
model: the server side was written in Python, while the client side was written in Java. The system consists of
the following major electronic elements: • 16 × 2 LCD: Displays two lines of information. The top line
displays the stock symbol and the price difference, with an up or down arrow indicating the increase or
decrease in price as compared to the previous day’s close. The bottom line displays the latest stock price. • A
red LED: Turned on if a stock’s price has decreased from the previous day’s closing price. • A green LED:
Turned on if a stock’s price has increased from the previous day’s closing price. • A piezo buzzer: Makes a
sound when a stock’s price has fallen below a predefined threshold. • Potentiometer: Adjusts the contrast of the
LCD screen. The stock ticker system monitors the dynamics of selected stocks and generates alert signals. The
user of the stock ticker system can register an email to receive notifications when the stock price has reached a
level of interest. Figure 2 shows the prototype of the system. projects for students in an incremental way. The
first project only focused on a single-node system, where students learned how to connect sensors and
actuators to the CPU, how to use sensors and actuators and how to program the node to make it smart. After
students could work with a singlenode system confidently, they were allowed to move on to the second project,
which focuses on the networking aspect. In the second project, students learned communications and protocols
through their hands-on project and understood where and how IoT protocols are different from the
corresponding traditional Internet protocols. Having acquired some basic understanding of the IoT concept and
system after the first two projects, students started to work on an IoT system that can be applied to the real
world in a creative and comprehensive way, which is the goal of the third project in the project series. Indeed,
we feel that the design of this series of three projects is the key to our PBL approach, which greatly enhanced
the effectiveness of PBL for our students. Second, our experience indicates that sufficient support related to the
project platform and environment is very helpful for undergraduates. Though the Raspberry Pi community is
very active and numerous online materials are freely available, several difficulties exist for beginners. First, it
is hard to find an entry point of necessary background knowledge and learning materials to Raspberry Pi. The
Raspberry Pi official website [32] does not have a systematic tutorial to guide the beginners; for example, the
“Getting Started Guide” only shows how to install the system for the first time. What to do next is not clear. In
this regard, we provided various supports for our students during their projects, including a detailed CoAP
tutorial and a detailed tutorial on how to work on Raspberry Pi with the laptop screen.
Conclusion:

You might also like