You are on page 1of 87

Master Lab Manual

Course Name Embedded Systems Workshop

Course Code CPE345

Department of Electrical and Computer Engineering

CUI Attock Campus

Program: Computer Engineering

Prepared by: Engr. Iram Shahzadi

Verified by: Dr. Farman Ullah

Session: FA20
COMSATS University Islamabad
Attock Campus

Embedded Systems Workshop (CPE345)


Lab Course Catalog Description
This lab course helps students to overview and understanding the concepts of real time embedded systems. The course is
designed to equip the students with the fundamental concepts of embedded system organization, microprocessor and
microcontroller programming, and real time systems requirements. It focuses on practical implementation exercises with
emphasis on real-time embedded systems applications design, interfacing various devices such as sensors and actuators
with microcontrollers using C and Assembly language programing, and scheduling algorithms to assign task based on their
priorities. Various hardware interfacing and programming languages/tools will be covered in this course to interface real
world application to access it remotely, compare the performance and evaluate tools. It will also cover how the constrained
resources can be scheduled and utilized to improve systems performance.

Course Details
Credit Hours 01
Core BS CE

Course Prerequisite(s)/Co-Requisite(s)
Pre-requisites: Programming Fundamentals, Computer Organization and Architecture

Course Offering Details


Lecture(s) No. of Lec(s) Per Week 2 Duration 1.5 hrs
No. of Session(s) Per Week
Lab (if any ) per week 1 Duration 3 hrs

Course Instructors Details:


Course Instructor Dr. Farman Ullah
Office No.
Office Hours 8:30 – 4:30
Email farmankttk@ciit-attock.edu.pk
Lab Instructor Engr. Iram Shahzadi
Lab Conducting Place DSP and Embedded Lab
Lab Timing As per TimeTable
Lab Instructor Email iram@cuiatk.edu.pk

Course Learning Outcomes


CLO1: Conduct lab experiments following the instructions and using the concepts of embedded systems, including their
architecture, interfaces, and processes
CLO2: Measure and Analyze various outputs of real-time embedded systems hardware and software components to verify their
working and theories
CLO3: Design and Develop different real-time embedded systems for a real-world complex problem
CLO4: Investigate and Use various developing and programing tools for the implementation of embedded systems considering
real world scenarios
CLO5: Commit to work in a team to perform lab experiments and technical projects.
CLO6: Demonstrate their technical projects and lab activities to a diverse audience through lab reports, viva, presentations, and
posters
COMSATS University Islamabad
Attock Campus

Mapping of CLOs to PLOs:


CLO Attainment
CPE345 LAB Related Level of Teaching Methods
Mechanism
CLOs PLOs Learning
CLO1 PLO1 Psy-2 Tutorials, Instruction, Lab Manuals and In Lab, Post Lab and Lab
Demos Exams
CLO2 PLO2 Psy-3 Tutorials, Instruction, Lab Manuals and In Lab, Post Lab and Lab
Demos Exams
CLO3 PLO3 Psy-5 Tutorials, Instruction, Lab Manuals and In Lab, Post Lab and Lab
Demos Exams
CLO4 PLO5 Psy-4 Tutorials, Instruction, Lab Manuals and In Lab, Post Lab and Lab
Demos Exams
CLO5 PLO9 Aff-3 Tutorials, Instruction, Lab Manuals and In Lab, Post Lab and Lab
Demos Exams
CLO6 PLO10 Aff-4 Tutorials, Instruction, Lab Manuals and In Lab, Post Lab and Lab
Demos Exams

Recommended
Week Topics
Readings (if any)
1. Introduction to the Arduino
2. Interfacing Sensors (Analog and Digital) with Arduino
3. Obstacle Detection Using Sensors (Interfacing Proximity Sensors with Arduino)
4. Interfacing Actuators with Arduino (High Voltage Devices, and Servo Motors)
5. Serial Communication (Control LED Dimmer using Serial, and Interfacing GPS Sensor as
RS232)
6. Sessional Exam I
7. RFID based Access Control System (Using RFID and Servo Motor)
8. Interfacing Bluetooth with Arduino and Android Bluetooth APP
9. Arduino External Interrupts (An interrupts-based Devices Control)
10. Arduino-Controlled Smart Home Internet-of-Things Platform (Web-Controlled Smart Home
Appliances)
11. Sessional Exam II
12. Data Transfer of Arduino-Controlled Smart Home to Thingspeak Cloud
13. Introduction of Raspberry PI, Installation of RTOS/Raspbian Operating System
14. Basic Interfacing (LDR, Proximity Sensors, Camera) with Raspberry Pi using Python
15. Terminal Project

Important Note: Students will be required to submit their Lab work and Lab handout.
Textbook(s)/Supplementary Readings
[1]. A lab manual will be provided to the students at the beginning of the each labthat carries the details of the experiments and related instructions
to perform those experiments.

Grading Breakup and Policy


Lab Project: 50 %
Lab Sessions (12): 25 %
Lab Exams (3): 25 %
Lab Viva (Oral Exam): 0%
Rubrics for Assessments of Lab Reports and Lab Exams
Rubrics for PLO#1 (Engineering Knowledge)
Exceeds expectations [9-10] Meets expectations[7-9) Average [5-7) Unsatisfactory [1-5)

.
R1: Lab Safety Rules: While working in the lab, the While working in the lab, the While working in the lab, the While working in the lab, the
Ability to observe safety, be student demonstrates student is attentive to safety, student is mostly attentive to student is unattentive to safety,
courteous to others, attentive exemplary behavior in respectful to instructors and safety, respectful to instructors disrespectful to others, and
to safety, and tidy in the lab. courtesy and safety, and leaves peers, and neat, cleaning the and peers, and neat, Might messy, leaving the area untidy
the area spotless. area before leaving. need reminders to leave the even after being reminded.
area clean.
R2: Use of Engineering
Knowledge and follow The procedure is efficiently The procedure is well The procedure could be better The procedure is inadequately
Engineering Experiment Procedures: followed and student skillfully followed and student followed, but student controls followed, and student does not
Knowledge Ability to follow experimental controls all chosen variables. demonstrates control of all all chosen variables. Most control chosen variables. Many
procedures, control variables, Know all procedural steps, and chosen variables. All procedural steps are recorded procedural steps are not entered
and record procedural steps are clearly and concisely procedural steps are on the lab report. on the lab report.
on lab report. recorded on lab report recorded on the lab report.
R3: Interpretation of Demonstrates a skillful ability Demonstrates an ability to Demonstrates some ability Demonstrates minimal or no
Subject Knowledge: to provide rational provide rational to provide explanations of ability to provide explanation of
Ability to interpret and explanations, and on the basis explanations of mathematical and/or visual mathematical
explain mathematical and/or of that information, can make mathematical and/or forms, and makes occasional and/or visual forms. Frequently
visual forms, including fitting inferences. visual forms. mistakes. misinterprets
equations,
diagrams, graphics, figures
and tables.
Rubrics for PLO#2 (Problem Analysis)
Exceeds expectations [9-10] Meets expectations[7-9) Average [5-7) Unsatisfactory [1-5)

.
R4: Limitations and Point out all significant Point out many significant Point out some limitations Minimal or no ability to identify
Implications: limitations and limitations and implications. and implications. limitations or implications. Has
Ability to point out implications. Demonstrates Demonstrates recognition Demonstrates some no knowledge of hardware or
limitations and implications skillful recognition and and consideration of recognition and software implementation
of Hardware and software consideration of important important assumptions, Consideration of important requirements for the problem
Components. assumptions, hardware or hardware or software requirements of hardware or solution. Didn’t mention about
software requirements requirements when solving software. .Has mentioned assumption and constraints.
Problem when solving a problem. a problem. some of the assumptions.
Analysis
R5: Data/Evidence Raw data/evidence, as well as Raw data/evidence, as well Raw data/evidence, as well as Raw data/evidence, as well as
Measurements: units, are skillfully recorded. as units, are appropriately units, are recorded although units, are not recorded suitably.
Ability to record raw data / The data table is clearly and and clearly recorded. The not as clearly or suitably as The data table is not labeled
evidence. concisely, and/or creatively data table is appropriately they might be. The data table and/or formatted.
labeled and formatted. labeled and formatted. may lack appropriate labels
and/or format.
R6: Experimental Data Accurately analyze the Accurately analyze the Analyze the collected data and Analysis and interpretation of the
Analysis: collected data and interpret the collected data and interpret interpret the findings with findings is illogical, and the
Ability to interpret findings, findings insightfully, and the findings. Correlates minor errors. Correlates findings. No attempt to correlate
compare them to values in the skillfully. Correlates experimental results to experimental results to known experimental results with known
literature, identify weaknesses experimental results to known known theoretical values; theoretical values; accounts for theoretical values; incapable of
and limitations. theoretical values; accounts for accounts for measurement measurement errors and explaining measurement errors or
measurement errors and errors and parameters that parameters that affect parameters that affect the
parameters that affect affect experimental results. experimental results. experimental results.
experimental results.

Rubrics for PLO#3 (Design)


Exceeds expectations [9-10] Meets expectations[7-9) Average [5-7) Unsatisfactory [1-5)

R7: Implementing .
Design Strategy: Ability Demonstrates a skillful Demonstrates an ability Demonstrates some ability Demonstrates minimal or no
to execute a solution (thorough/insightful/creative) to execute a solution to execute a solution that ability to execute a solution.
taking into consideration ability to execute a solution taking into consideration attends to the problem, but Solution does not directly
design requirements and taking into consideration all design requirements and omits some design attend to the problem.
pertinent contextual design requirements and some contextual requirements and/or
elements. pertinent contextual elements. elements. pertinent contextual
[Block Diagram/Flow elements.
Engineering chart/Circuit Diagram]
Design R8: Best Coding Standards: Coding standards, best Coding standards, best Coding standards, best Coding standards, best
Ability to follow the coding programming practices are programming practices are programming practices are programming practices are not or
standards and programming followed extensively. followed appropriately not appropriately followed. rarely followed.
practices.

Rubrics for PLO#5 (Modern Tools Usage)


Exceeds expectations [9-10] Meets expectations[7-9) Average [5-7) Unsatisfactory [1-5)

R9: Understand Tools: .


Ability to describe and Demonstrates skillful ability to Demonstrates ability to Demonstrates some ability to Demonstrates minimal or no
explain the principles behind describe and explain the describe and explain the describe and/or explain the ability to describe and/or
and applicability of principles behind and principles behind and principles behind and explain the principles behind
engineering tools. applicability of engineering applicability of engineering applicability of engineering and applicability of
tools. tools. tools. engineering tools.
R10: Realization of Selects relevant equipment Mostly select relevant Need guidance to select Incapable to select relevant
Hardware and Software to the experiment, develops equipment to the experiment, relevant equipment to the equipment to the experiment,
Modern Tools for Experiments: setup diagrams of develops setup diagrams of experiment, develops setup develops setup diagrams of
Tools Usage Ability to select relevant equipment connections or equipment connections or diagrams of equipment equipment connections or
hardware tools or software wiring. Or Select relevant wiring. Or Mostly select connections or wiring. Or wiring. Incapable to select
components (P3) software libraries, relevant software libraries, Need guidance to select relevant software libraries,
functions, and directive to functions, and directive to relevant software libraries, functions, and directive to
develop the code. develop the code. functions, and directive to develop the code.
develop the code.
R11: Tools Evaluation: Demonstrates skillful ability to Ability to simulate and Demonstrates some ability to Incapable to simulate and
Ability to simulate the simulate and evaluate the evaluate the limitations of simulate and evaluate the evaluate the limitations of tools
experiment and then using limitations of tools and tools and discusses the limitations of tools and and discusses the assumptions.
hardware tools to verify the discusses the assumptions. assumptions. discusses the assumptions.
results (P4)
Rubrics for PLO#9 (Individual and Teamwork)
Exceeds expectations [9-10] Meets expectations[7-9) Average [5-7) Unsatisfactory [1-5)

R12: Individual Work .


Contributions: Designated jobs are Designated jobs are Designated jobs are Some designated jobs are
Ability to carry out accomplished by deadline; accomplished by deadline; accomplished by deadline; accomplished by deadline;
individual responsibilities. completed work is carefully completed work meets completed work meets most completed work meets some
and meticulously prepared requirements. requirements. requirements.
Individual and meets all requirements.
and
Teamwork R13: Management of Team Has great appreciation for and Has appreciation for and Has some appreciation for and Has no appreciation for or
Work: understanding of disciplines understanding of disciplines understanding of disciplines understanding of disciplines
Ability to appreciate, outside of own. Works outside of own. Works outside of own, but works less outside of own. Is unable to
understand and work with profitably with other effectively with team effectively with other team work effectively with team
multidisciplinary team members. members. members. members.
members.
Embedded Systems Workshop (CPE345)

Lab #

Lab Title:

Submitted by:

Names Registration # Marks

Rubrics name & number Marks

In-Lab Post-Lab

Engineering R3: Interpretation of Subject Knowledge:


Knowledge Ability to interpret and explain mathematical and/or visual forms,
including equations, diagrams, graphics, figures and tables.

Problem R5: Data/Evidence Measurements:


Analysis Ability to record raw data / evidence

R6: Experimental Data Analysis:


Ability to interpret findings, compare them to values in the literature,
identify weaknesses and limitations

R7: Implementing Design Strategy:


Ability to execute a solution taking into consideration design requirements
Design and pertinent contextual elements.
[Block Diagram/Flowchart/Circuit Diagram]

R8: Best Coding Standards:


Ability to follow the coding standards and programming practices

Modern R11: Tools Evaluation:


Tools Usage Ability to simulate the experiment and then using hardware tools to
verify the results

Individual R12: Individual Work Contributions:


and Ability to carry out individual responsibilities.
Teamwork

Rubrics to follow

Rubrics # R3 R5 R6 R7 R8 R11 R12

In –Lab

Post- Lab
Lab-1: Introduction to the Arduino
Arduino is an open-source single-board microcontroller, designed to make the process of
using electronics in multidisciplinary projects more accessible. The hardware consists of a simple
open hardware board with an Atmel AVR processor. It has on-board analog and digital
input/output support. The software consists of a standard programming language compiler
and the boot loader that runs on the board. Knowledge of the Arduino gives a tangible
application of Embedded systems.

Lab Objective
The objective of this lab is to explore the basic capabilities of the Arduino
and its programming structure, and the Atmel AVR Atmeg328p details.

Lab Background and Getting Knowledge of:


1. Basic Computer Skills. Student should be comfortable starting applications,
opening, closing and saving files, cutting and pasting text, and locating
files/folders.
2. Overview of the Arduino. After this lab, Student should have a basic
knowledge of the components and capabilities of the Arduino board (Uno—
R3).
3. Overview of the AVR Atmeg328P. After this lab, students should be
familiar of the AVR microcontroller features and PINs descriptions.
4. Basic Programming Skills. Student should be familiar with creating simple
programs in C/C++ as well as working in a programming development
environment.

Laboratory Pre-Exercise Tasks Overview:


1.1 Overview of Arduino:
Arduino is a circuit board containing an ATMEL ATmega microcontroller
preloaded with a boot loader program. A boot loader is a tiny program (e.g., 2 Kbytes on
the Arduino) stored in non-volatile memory at a location such that when power is applied
or the reset button is pressed the CPU jumps into it and executes its instructions. When you
create an application, an embedded program you create to do something meaningful, you
can send it to the target processor by uploading it. When you start the upload process, a
special signal on the Arduino hardware causes the microcontroller to reset which forces
the boot loader to run. It performs several steps to configure the controller to listen for
incoming data on its serial communications port. Because the host computer initiated an
upload of the application program which caused the reset, there is data being sent via the
serial port. So the boot loader sees this data and responds by saving it to the non-volatile
memory at a special location. When finished, the boot loader jumps to that application
location in the flash and starts executing program instructions. In the event that the
Arduino is manually reset or when power is first applied, the boot loader will not see any
data on the serial port, and it will just jump to the application location in flash.
1.1.1 Components View of Arduino UNO R3.0:
The components view of the Arudino (UNO 3.0) circuit board is shown in the Fig.1 below:

Figure 1: Arduino UNO Circuit Board and Components are labeled.


The details of components are below:
 Analog input pins – pins (A0-A5) that take-in analog values to be converted to be
represented with a number range 0-1023 through an Analog to Digital Converter
(ADC).
 ATmega328 chip – 8-bit microcontroller that processes the sketch you programmed.
 Built-in LED – in order to gain access or control of this pin, you have to change the
configuration of pin 13 where it is connected to.
 Crystal Oscillator – clock that has a frequency of 16MHz
 DC Jack – where the power source (AC-to-DC adapter or battery) should be
connected. It is limited to input values between 6-20V but recommended to be
around 7-12V.
 Digital I/O pins – input and output pins (0-13) of which 6 of them (3, 5, 6, 9, 10 and
11) also provide PWM (Pulse Width Modulated) output by using the analogWrite()
function. Pins (0 (RX) and 1 (TX)) are also used to transmit and receive serial data.
 ICSP Header – pins for “In-Circuit Serial Programming” which is another method
of programming.
 ON indicator – LED that lights up when the board is connected to a power source.
 Power Pins – pins that can be used to supply a circuit with values VIN (voltage from
DC Jack), 3.3V and 5V.
 Reset Button – a button that is pressed whenever you need to restart the sketch
programmed in the board.
 USB port – allows the user to connect with a USB cable the board to a PC to upload
sketches or provide a voltage supply to the board. This is also used for serial
communication through the serial monitor from the Arduino software.

1.1.2 Schematic Diagram of Arduino:


Fig.2 shows the schematic diagram of the Arduino UNO R3.

Figure 2: Schematic Diagram of Arduino UNO R3.


1.2 Overview of Atmeg328p Microcontroller:
The ATmega328P is a low-power CMOS 8-bit microcontroller based on the AVR
enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the
ATmega328P achieves throughputs approaching 1 MIPS per MHz allowing the system
designer to optimize power consumption versus processing speed.
1.2.1 Key features of Atmeg328p Microcontroller:
 High Performance, Low Power Atmel®AVR® 8-Bit Microcontroller
 Advanced RISC Architecture
o 131 Powerful Instructions – Most Single Clock Cycle Execution
o 32 x 8 General Purpose Working Registers – Fully Static Operation
o Up to 20 MIPS Throughput at 20MHz
 High Endurance Non-volatile Memory Segments
o 32KBytes of In-System Self-Programmable Flash program memory
o 1KBytes EEPROM
o 2KBytes Internal SRAM
 Peripheral Features
o Two 8-bit Timer/Counters with Separate Prescaler and Compare Mode
o One 16-bit Timer/Counter with Separate Prescaler, Compare Mode
o and Capture Mode – Real Time Counter with Separate Oscillator
o Six PWM Channels
o 8-channel 10-bit ADC in TQFP and QFN/MLF package
o 6-channel 10-bit ADC in PDIP Package
o Programmable Serial USART
o Master/Slave SPI Serial Interface
o Byte-oriented 2-wire Serial Interface (I2C compatible)
o Programmable Watchdog Timer with Separate On-chip Oscillator
o Interrupt and Wake-up on Pin Change
 Power Consumption at 1MHz, 1.8V, 25°C
o Active Mode: 0.2mA
o Power-down Mode: 0.1µA
o Power-save Mode: 0.75µA (Including 32kHz RTC)

1.2.2 PINS of Atmeg328p Microcontroller:


Fig.3 shows description of the 28 pins PDIP of ATmega328p microcontroller. These pins
are similar to the pins on the Arduino UNO R3 boards. It is simply extended on the circuit
board to easily interface with other system.
Figure 3: PINs description of ATmega328p Microcontroller installed at Arduino Circuit Board.

1.3 Setup and Installation of Arduino (IDE):


1.3.1 Installation of Arduino (IDE):
This part will guide you through the set up and installation process of the Integrated
Development Environment (IDE) that will be used throughout the development and
experiments of labs.
 Open your default internet browser and access the Arduino website. Download the
latest Arduino IDE version. The software is compatible with Linux, Mac and Windows
so just choose the one that matches your OS. The Arduino download page is at
http://arduino.cc/en/Main/Software.

Figure 4: A part of Arduino Website’s download page. Arduino allows you to install
its IDE on several platforms (see encircled).
 After downloading the compressed file, extract its contents to your preferred directory
(C:\Program Files, your Desktop or etc…). Note that the whole folder size is around 200MB
when completely extracted.
Figure 4: Screenshot of attempt to extract the zipped Arduino folder.
Make sure you have an archive utility such as 7zip or WinRAR.
 Congratulations! Arduino IDE is installed on your computer. To use it, just navigate to
your main folder directory and run the Arduino application.

Figure 5: Screenshot of what’s inside the Arduino folder. The application icon looks like an infinity symbol.

1.3.2 Installation of Arduino Drivers:


This part will guide you through the set-up and installation process of the Arduino Uno
board driver for the device to be recognized by the IDE.
 Connect the Arduino UNO to the computer via USB Cable (on Fig. 6) . Check if it is
properly connected by observing the green LED labeled ON (on Fig. 6) on the board.
Figure 6: Photo of Arduino Uno board connected to a Computer. Note that the board’s USB-B port.
 Wait for Windows to try and install the device’s driver until it fails. Navigate to the Device
Manager through Start > Control Panel > Device Manager. Locate the Arduino Uno Device.
Right-click it to choose Update Driver Software.

Figure 7: Screenshot of the Device Manager. The Arduino Uno should have an exclamation point.
 Choose to browse your computer for the driver by clicking Browse my computer for
driver software.

Figure 7: Screenshot of the options for searching the device driver.


 A new window will open for you to indicate the location of the driver. Click Browse…

Figure 8: Screenshot of the browse option menu. Choose the first option which is to look manually for
the folder that contains the Arduino Uno board’s driver.
 A Windows Security window sometimes pops up to confirm if you want to continue
the installation. Just click, Install this driver software anyway.
Figure 9: Screenshot of pop-up window. Windows can’t verify the publisher of the device software but
we know that the software’s publisher is Arduino.
 Wait for Windows to finish installing the device driver. Upon completion, you should
see an installation successful message.

Figure 10: Screenshot of successful completion of the Arduino Drivers.

1.4 Comparison of the Programming Structure of ANSI C and Arduino C:


In any kind of C programming, a program is comprised primarily of subroutines. The
ANSI C program structure is shown below (Fig. 11).

Figure 11: ANSI C Program Structure Overview


Every ANSI C program follows this structure, even the most simple. In the simple cases,
some of the parts might be missing. Indeed, the simplest program in ANSI C is shown. In this
case, there are no declarations, no subroutines etc.

Figure 12: ANSI C Simple Program with no subroutine


For the Arduino, we have a structure similar to that shown above, but we always have
at least two subroutines. Te minimal Arduino program is shown below (Fig.13).

Figure 13: ANSI C Simple Program with no subroutine


1.5 Writing an Example Program (Blinking of an LED) Using Arduino IDE
and Circuit Board:
This example aims to familiarize the student with the basic operation of the Arduino Uno
board, and Integrated Development Environment (IDE). By the end of the exercise, the student
should be able to know the basic functionalities of the IDE. The students will be able to answer
the following:
 How do you compile and upload a sketch file into the Arduino Board using the IDE?
 How can the configuration of the pins be specified in the programming?
 What functions are always required in a sketch?
Equipment required performing this task:
 1 x Arduino Uno board and USB cable
 1 x 5mm/3mm Red LED
 1 x 470Ω resistor
 1 x breadboard
1.5.1 Writing Program using Arudino IDE:
 Proceed to the Arduino Folder and double-click the arduino application to open the
Arduino IDE which is also shown below:

Figure 14: Screenshot of the Arduino IDE. The workspace is very simple and
frequently used buttons are easy to access
 Type the following lines of code on the front panel.
// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn LED on (HIGH voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn LED off (making voltage LOW)
delay(1000); // wait for a second
}
 Press Ctrl + S or Icon on the IDE to save your sketch (the term for a source code in
Arduino).
 Click the Verify Button (A shown on Fig. below) to check if the sketch has no errors. At
the bottom of the screen you should see if the sketch was successfully scanned free of
problems (B on Fig. below). Moreover, the size of the sketch file (C on Fig. below) is also
indicated on the black screen at the bottom to shows that it fits the flash memory of the
Arduino Uno.

Figure 15: Screenshot of the Blink code after compilation. The verify button looks just like a play button and is
located at the upper left corner. Successful compiling will be indicated at the bottom. If an error or problem
occurred, it will be shown in the black screen.
1.5.2 Test your Program:
 Connect an LED to a 470Ω resistor. Note: that the longer leg of the LED is the positive
(connected to one end of resistor and the shorter one is the negative (connected to the

ground). The other end of the resistor should then be connected to the specified pin
which is 13.
Figure 15: Schematic Diagram of blinking LED circuit
 Check if the board selected in the IDE is the one you are using, the Arduino Uno board.
Figure 16: Screenshot showing Arduino Uno as selected board. If you have a different type of Arduino

board, just select it from this list


 Next, make sure that the Arduino board’s COM port is properly identified by the IDE.
To do this, connect the board to the computer then from the IDE front panel go to Tools
> Serial Port (A on Fig. 17). A list of COM’s should be there, choose the COM number
associated with the microcontroller board. Note: the microcontroller board’s COM no.
is found near the name of the device’s driver in Device Manager (B on Fig. 17)
Figure 17: Screenshot of both the Device Manager and Arduino IDE windows. Note that the COM
number selected as Serial Port must be the same one found beside the device’s name
 Finally, upload the sketch made earlier into the board by clicking the icon in the IDE.
The status of the upload can be found near the bottom of the program

Figure 17: Screenshot showing a successful upload. Sometimes an error occurs because the COM port
of the Arduino UNO was not properly specified.
1.6 In Lab Tasks to Perform:
 Control the LED ON/OFF operation using a push button or a switch
 Control the light bulb (LED) installed in Stairway using the following two buttons
(switches) combinations
Switch-1 Switch-2 LED Status
0 0 OFF
1 0 ON
0 1 ON
1 1 OFF

1.7 Post Lab Tasks to Perform:


 Draw the schematic diagram of Arduino Nano Circuit Board (Handwritten Only)
 Compare the features of AVR Atmega328p, PIC, and 8051 microcontrollers (at least
20 features
Notes for In Lab Tasks Report:
Your lab report should have the following bullets:
-Title of the task
-Task Objective (what are you doing and what you will get)
-Flow chart of the Task
-Block Diagram (Schematic Diagram)
-Code of the task
-Results
Lab-2: Interfacing Sensors (Analog and Digital) with Arduino
In this lab, you will connect a digital input circuit and a digital output circuit (Sensor having
digital output) and an analog output circuit (analog sensor) to Arduino. Though this lab is
about sensors interfacing with arduino. However, this interfacing concept and principles can
be applied to any microcontroller having digital input (for digital sensor interfacing) and
analog input (for analog sensor interfacing).

Digital input and output are the most fundamental physical connections for any
microcontroller. The pins to which you connect the digital circuits are called General Purpose
Input-Output, or GPIO, pins. The arudino has only analog inputs and there are no analog
outputs. In mostly microcontrollers, the analog inputs and outputs are unavailable such as the
8051 microcontroller.

Lab Objectives
The objective of this lab is to explore the analog-to-digital convertor (ADC),
various configurations of the built-in ADC of Arduino for various levels of
resolutions, interfacing analog sensors with Arduino, and interfacing digital
sensors with Arduino.

Lab Background and Getting Knowledge of:


5. Basic Signals Conversion. Student will learn different type of signals and how
an analog signal will be converted into encoded digital numbers (binary string).
6. Configuration Built-in ADC of Arduino. After this lab, Student should be
able to configuration the ADC for 5 Volts, and how to measure smaller voltages
with greater accuracy using the analogue input pins on your Arduino in
conjunction with the AREF pin. Students will also learn how to acquire a signal
if it is greater than 5 Volt.
7. Interfacing an Analog Sensor. Student will learn how to interface analog
sensors with Arduino. We will use the IR sensor analog output and measure the
distance between transmitter and obstacle.
8. Interfacing a Digital Sensor with Arduino. In this lab, student will learn
how to interface digital sensor (single bit output) with Arduino. In this lab we
will interface an IR sensor (digital sensor) to detect an obstacle.

Laboratory Pre-Exercise Tasks Overview:


1.1 Basics of Signals Conversion:
A signal as referred to in communication systems, signal processing,
and electrical engineering is a function that "conveys information about the behavior or
attributes of some phenomenon". The IEEE Transactions on Signal Processing states that
the term "signal" includes audio, video, speech, image, communication, geophysical, sonar,
radar, medical and musical signals. We categorize the signal into four main types.
However, the two main types are analog signal and digital signal. The analog signal has
both real number values on x-axis (time) and y-axis(amplitude), while the digital signal has
discrete values. In computing systems, we can’t store the analog real number infinite values
due to limited storage capabilities. So the analog is converted to digital using the
mechanism of analog-to-digital conversion. The ADC has the following steps:
 Sampling:
In signal processing, sampling is the conversion/reduction of a continuous-time to a
discrete-time. Sampling is the process of recording an analog signal at regular discrete
moments of time. The sampling rate (f_s) is the number of samples per second. The time
interval between samples is called the sampling interval T_s=1/f_s. To sample a signal the
f_s should be at least or greater the twice of the maximum frequency (f_max) of analog
signal in order to recover the signal back to analog from the digital. Fig. 1 shows an analog
signal. Fig. 2a and Fig.2b shows the sampling of the signal in Fig.1 at T_s=0.5 and T_s=0.1
seconds respectively.

Figure 2: Pictorial Overview of an analog signal (y=sin(2*pi*f*t))

(a) (b)
Figure 2: Pictorial Overview Sampling Phenomena (a). Sample interval is 0.5 seconds (b). Sample interval is 0.1
seconds.
 Quantization:
Quantization, in mathematics and digital signal processing, is the process of
mapping input values from a large set (often a continuous set) to output values in a
(countable) smaller set. Rounding and truncation are typical examples of quantization
processes. In our scenario, we define as the conversion of y-axis (Amplitude) real value
into a discrete (integer) value is called as quantization. Eq. 1 is used to convert the real
amplitude value into integer value.

𝑉−𝑉𝑚𝑖𝑛
𝑋 = ⌊(2𝑁 − 1) ⌋ (1)
𝑉𝑚𝑎𝑥−𝑉𝑚𝑖𝑛

Where N is number of bits used to store the digital value, V is the desired amplitude value
to change. However, using ADC the V_min value should be greater than or equal to zero.

(a) (b)
Figure 3: A portion of the sampled signal and its conversion to the discrete values (a). Sampled Signal (b). The
quantized signal using Eq. (1)

 Encoding of the Quantized Signal:


Encoding is the process of representing the quantized value in a binary sequence in which
the number of bits will be equal to the ADC bits. For example, the value in Fig. 3b at point#1
is 860 and if we use an ADC of 10-bits its corresponding encoded value will be
(1101011100).

1.2 Configuration of the Arduino Built-in ADC:


The Arduino has six ADC channels marked as (A0-A5, as shown on Fig. 4) and the default
signal measured by these PINs are in range of 0~5 volts. The Arudino (AVR Atmega) has
the following features :
Figure 4: Arduino Circuit Board showing the Analog (ADC) PINs (A0~A5)

 The ATmega328P features a 10-bit successive approximation ADC.


 ± 2 LSB Absolute Accuracy
 15 k samples per second (kSPS) at Maximum Resolution, to 76.9 kSPS (13 μs
Conversion Time) ● 6 Multiplexed Single Ended Input Channels
1.2.1 Default Configuration of the Arduino Built-in ADC:
Arudino rely on ADCs to obtain continuously variable (analog0 input data. By default, the
reference voltage for the converter is the on-board five volt DC source. This represents the
maximum input level that may be digitized. The minimum level is ground or zero volts (if
negative signals are needed, some form of offset bias will be required). A 10 bit converter
yields 1024 discrete levels. This means that each step will be slightly less than five
millivolts.
To use the ADC, a reference voltage/operating voltage must be set during the initialization
routine. However, in default configuration case we do not set that. After this, whenever a
value is needed, simply call the analogRead() function. The only argument to the function is
the input channel desired (zero through five for the Uno). The function returns the digitized
value as an integer in the range of 0 to 1023.
And when we say the operating voltage – this is the voltage available to the Arduino after the
power supply circuitry. For example, if you have a typical Arduino Uno board and run it from
the USB socket – sure, there is 5V available to the board from the USB socket on your computer
or hub – but the voltage is reduced slightly as the current winds around the circuit to the
microcontroller – or the USB source just isn’t up to scratch.
This can easily be demonstrated by connecting an Arduino Uno to USB and putting a
multimeter set to measure voltage across the 5V and GND pins. Some boards will return as
low as 4.8 V, some higher but still below 5V. So if you’re gunning for accuracy, power your
board from an external power supply via the DC socket or Vin pin – such as 9V DC.
1.2.1.1 Schematic Diagram of connecting analog circuit (voltage source with
variable resistor) to Arduino:
Fig. 5 shows the schematic diagram of connecting an analog circuit to the arduino and blink
an LED using a condition if the ADC output is greater that some threshold value.

Figure 5: Schematic Diagram of Connecting Analog Circuit to Arduino and Blink an LED

1.2.1.2 Source Code of connecting analog circuit (voltage source with variable
resistor) to Arduino:

int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
If (sensorValue >=500)
digitalWrite(ledPin, HIGH);
Serial.println(sensorValue);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
}

1.2.2 Configuration of the Arduino Built-in ADC using AREF PIN:

When your Arduino takes an analogue reading, it compares the voltage measured at the
analogue pin being used against what is known as the reference voltage. In normal analogRead
use, the reference voltage is the operating voltage of the board. For the more popular Arduino
boards such as the Uno, Mega, Duemilanove and Leonardo/Yún boards, the operating voltage
of 5V. So if you have a reference voltage of 5V, each unit returned by analogRead() is valued at
0.00488 V. (This is calculated by dividing 1024 into 5V). What if we want to measure voltages
between 0 and 2, or 0 and 4.6? our signal has very low range and we want a resolution of less
than 0.00488 V? How would the ADC know what is 100% of our voltage range?

And there in lies the reason for the AREF pin. AREF means Analogue REFerence. It allows us
to feed the Arduino a reference voltage from an external power supply. For example, if we
want to measure voltages with a maximum range of 3.3V, we would feed a nice smooth 3.3V
into the AREF pin – perhaps from a voltage regulator IC. Then the each step of the ADC would
represent around 3.22 millivolts (divide 1024 into 3.3).

Note that the lowest reference voltage you can have is 1.1V. There are two forms of AREF –
internal and external, so let’s check them out.

1.2.2.1 Configuration using External AREF PIN:

An external AREF is where you supply an external reference voltage to the Arduino board.
This can come from a regulated power supply, or if you need 3.3V you can get it from the
Arduino’s 3.3V pin. If you are using an external power supply, be sure to connect the GND to
the Arduino’s GND pin. Or if you’re using the Arduno’s 3.3V source – just run a jumper from
the 3.3V pin to the AREF pin.

To activate the external AREF, use the following in void setup().

analogReference(EXTERNAL); // use AREF for reference voltage

This sets the reference voltage to whatever you have connected to the AREF pin – which of
course will have a voltage between 1.1V and the board’s operation voltage.
Very important note – when using an external voltage reference, you must set the analogue
reference to EXTERNAL before using analogRead(). This will prevent you from shorting the
active internal reference voltage and the AREF pin, which can damage the microcontroller on
the board.

If necessary for your application, you can revert back to the board’s operating voltage for AREF
(that is – back to normal) with the following:

analogReference(DEFAULT);

Fig. 6 shows the schematic diagram for interfacing the low-level analog circuit (0~3.3
Volt) with Arduino. For a signal less than 3.3 Volt and greater/equal to 1.1 volt, we have
to connect this AREF pin to an external source and the Arduino ground PIN to that
external source.

Figure 6: Schematic Diagram of Connecting Analog Circuit to Arduino Using AREF PIN as an External
Reference for measure signal (0~3.3 Volts)

The source code for the schematic of Fig. 6 is below:


int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
analogReference(EXTERNAL);
Serial.begin(9600);
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
If (sensorValue >=500)
digitalWrite(ledPin, HIGH);
Serial.println(sensorValue);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
}

1.2.2.2 Configuration using Internal AREF:


The microcontrollers on our Arduino boards can also generate an internal reference
voltage of 1.1V and we can use this for AREF work. Simply use the line:

analogReference(INTERNAL);

and we don’t need to connect the AREF pins to any voltage source.

1.3 Interfacing an Analog Sensor with Arduino:


Transducer is a device that converts a primary form of energy into a corresponding
signal with a different energy form. Primary Energy Forms: mechanical, thermal,
electromagnetic, optical, chemical, etc. It takes form of a sensor or an actuator. In this section
of the Lab, we will focus how to interface the IR Sensor for obstacle detection and measuring
the distance between obstacle and transmitter.
The list of hardware requirements are:
 Arduino
 Sensors having analog output with 1 IR LED receiver (photodiode with 2 pins, not the phototransistor
with 3 pins) and IR LED emitters
 100K resistor (brown black yellow)
 Jumper wires
 Breadboard

1.3.1 Schematics of Interfacing an IR Sensor using its Analog Output with


Arduino:
Fig. 7 shows the schematic diagram of interfacing the IR sensor (Transmitter (White LED

Figure 7: Schematic Diagram of Connecting Analog Output IR Sensor with Arduino


shown)/Receiver (Black LED)). The emitter is connected with the +5V and Ground pins, and
the receiver is connected with analog input pin A0.

1.4 Interfacing an Digital Sensor (Single Bit Output) with Arduino:


The purpose of this exercise is for you to get familiar to interface the digital and physical
worlds, by connecting sensors. We will interface the KY033 (IR Sensor) with the Arduino. The
list of hardware requirements are:
 Arduino
 Sensor (KY033) having digital output
1.4.1 Schematics of Interfacing an IR Sensor using its Digital Output with
Arduino:
Fig. 8 shows the schematic diagram of interfacing the Digital IR sensor with the Arduino.

Figure 7: Schematic Diagram of Connecting Analog Output IR Sensor with Arduino


1.5 Lab-2 Tasks:
 In-Lab Task
o Interface an analog circuit (potentiometer/variable resistor based voltages)
with Ardiuno and provide a table for default, internal and external
configuration of ADC. Each table must show a variation of input voltages
from (0~5), digital value calculated through mathematical equation, digital
value given by Arduino ADC, Error of digital values, converted value into
voltage, and error in input and value (which is called quantization error). For
each configuration you have to provide schematic, and also code.

Input Formula ADC Dec ADC Error


Voltage Value Converted
Value

o Interface a digital sensor (IR Sensor) with Arduino.


o Interface an analog sensor (using potentiometer as a temperature sensor with
sensitivity 1●C/0.1 V).
For all these tasks you should provide in report:
-Task Title
-Task Objectives
-Schematic Diagram
-Flow Chart if possible and you think there is a condition checking
-Code of the Task
-Results in presentable way (Tables etc. ) and Discussion
 Post-Lab Task
o Interface an analog circuit having an output of 0~10V with Arduino. Change the
input in the range of 0~5V which is acceptable by Arudino. Show the calibration
process how the high range is converted in acceptable range, and what will the
sensitivity factor.
o Interface one analog and one digital sensor.
Lab-3: Obstacle Detection Using Sensors (Interfacing
Proximity Sensors with Arduino)

This lab will be focused on interfacing proximity sensors specifically the ultrasonic and infra-
red sensors with Arduino. A proximity sensor is a sensor able to detect the presence or
distance of nearby objects without any physical contact. It emits a beam of signal and looks
for return signal. The object being sensed is often referred to as the proximity sensor's target.
Different proximity sensor targets demand different sensors. For example, a capacitive
proximity sensor or photoelectric sensor might be suitable for a plastic target; an inductive
proximity sensor always requires a metal target. There are many application of proximity
sensors from domestic use to industrial use such as Obstacle avoidance robot, Robotics,
object detection, distance measurement, liquid level monitoring system, Height
measurement, Agriculture, and vehicle collision protection. In this lab, we are mainly
focusing on Ultrasonic sensor.

Lab Objectives
The objectives of this lab is to explore how the Ultrasonic sensor can be interfaced with
Arduino. The working principles of ultrasonic sensor, detection of an obstacle, and measuring
the distance of an obstacle from the transmitter. We will able to understand how we can
measure that the time when a pin of Arduino become high.
Lab Background and Getting Knowledge of:
1. Basic Understanding Proximity Sensor interfacing. Student will learn the
interfacing of proximity sensors with Arduino. How, we have to trigger the sensor
to transmit a signal and then listen for the echo.
2. Finding the obstacle Position from the Received Single. After this lab, you
will know the mathematical model to calculate the distance of an obstacle from
the transmitting source.
3. Interfacing an Ultrasonic Sensor with Arduino. Student will learn the

Laboratory Pre-Exercise Tasks Overview:


1.1 Overview of Ultrasonic Sensor
Ultrasonic sensor is distance measurement sensor which use ultrasonic sound waves to
measure distance. Ultrasonic sensor use high frequency sound waves of 40 KHz. Ultrasonic
sensor consists of two basic modules transmitter and receiver. Transmitter acts as speaker and
receiver acts as a microphone. Speaker emits ultrasonic waves and Microphone detect
ultrasonic waves which is produced by speaker. The HC-SR04 is a long range ultrasonic sensor
module for measuring the distance or we can also use it for detecting the objects. The range of
the ultrasonic sensor is around 2cm to 400cm. The sensor module has an
Figure 3: Overview of Object Detection and Working of Ultrasonic Sensor

ultrasonic transmitter and receiver. Ultrasonic sensor working principle is similar to bats and
dolphins. Fig. 1 illustrates the working principles of an ultrasonic sensor.

1.2 Pin-Outs and Other specifications of ultrasonic sensor


Ultrasonic sensor price is very low and can be used easily by doing some arduino
programming. Fig. 2 shows the pinouts configuration of HC-SR04. Table 1 shows the
parameters(specification) of HC-SR04.

Pin Description
No.
Vcc +5V

Trig Trigger(Input)

Echo Echo(Output)
Figure 2: HC-SR04 PINOUT Configuration
GND GND
Table 1: HC-SR04 Specifications
1.3 Mathematical Model of Calculating the Distance of Obstacle from the
Transmitter
The speed of sound is 340.29 m/s or 0.034 cm/µs.
Distance = Time * Speed
As we know the ultrasound signal travels to the object and bounce back so the travel path, as
well as time, will be double. So to get the exact calculation we use this formula:
Distance = Time * Speed / 2
Distance = Time * 340 / 2 (m)
1.4 Source Code for Interfacing Ultrasonic Senor with Arduino

// defines pins numbers


const int trigPin = 9;
1. const int echoPin = 10;
2.
3. // defines variables
4. long duration;
5. int distance;

6. void setup() {

pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output


pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication

7. }
8. void loop() {

// Clears the trigPin


digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds


digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH)
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);}
1.5 Lab Tasks for Proximity Sensors Interfacing with Arduino
1.5.2 In-Lab Tasks (Complete the Following Table)

S.No Time in Actual Measured Error in


Microseconds Distance in Distance in Distance
feet/inches feet/inches

-Use the ultrasonic sensor to detect the presence of a person, generate an alarm (turn buzzer
ON), and turn ON LED

1.5.3 Post-Lab Task


-Use the ultrasonic sensors to find the water level in a water-tank, and control a water pump
to automatically maintain a desired level of water in the water-tank.
Lab-4: Interfacing Actuators with Arduino (High Voltage
Devices, and Servo Motors)

This lab will be focused on interfacing different actuators. Actuators are hardware devices that
convert a controller command signal into a change in a physical parameter. An actuator is a
component of a machine that is responsible for moving or controlling a mechanism or system,
for example by actuating (opening or closing) a valve or (Turning ON or OFF) a light. In this
lab, we are focusing on interfacing a high voltage device (light) using Relay, and also the servo
motor.

Lab Objectives
The objectives of this lab is to explore how we can control the high voltage devices from the
microcontroller (Arduino). The Arduino has limitation of voltages i.e. 5volt and 40 mA is
available. However, the high voltage devices need high voltages and current. For high voltage
devices, we are focusing only on the ON/OFF actuation using a Relay. Movement of objects
can be controlled by controlling motion of motors. In this lab, we are going to interface the
servo motor with Arduion.
Lab Background and Getting Knowledge of:
1. Basic Understanding Actuator interfacing. Student will learn the various
actuators interfacing. More specifically, we are focusing on interfacing the high
voltages sources with Arduino and moving objects control using servo motor.
2. Interfacing High voltage sources. After this lab, Student should be able to
interface high voltage sources as an ON/OFF actuation control. The students will
able to use Relay for controlling devices.
3. Interfacing an Ultrasonic Sensor with Arudino. Student will learn how to
interface servo motors with Arduino. Students will be able to generate different
pulse width modulation (PWM) to control the movement of servo motor.

Laboratory Pre-Exercise Tasks Overview:


1.1 High Voltage Sources Interfacing with Arduino
We can control High Voltage electronic devices using relays. A Relay is actually a
switch which is electrically operated by an electromagnet. The electromagnet is activated
with a low voltage, for example 5 volts from a microcontroller and it pulls a contact to make
or break a high voltage circuit. Fig. 1 illustrate the deactivated and activated status of the
relay.
Figure 4: Overview Relay Deactivation and Activation
For better understanding let’s see the circuit schematics of the relay module in this
configuration. So we can see that the 5 volts from our microcontroller connected to the Vcc
pin for activating the relay through the Optocoupler IC are also connected to the JDVcc pin
which powers the electromagnet of the relay. So in this case, we got no isolation between
the relay and the microcontroller.

Figure 2: Overview Relay Deactivation and Activation

1.2 Schematic for High Voltage Sources Interfacing with Arduino

Figure 3: Schematic of Interfacing High Voltage Source with Arduino


1.3 Code for Relay Actuation and LED using Arduino
/*
Actuate the Relay if the button is pressed
*/
int pinButton = 8;
int LED = 2;
int Relay = LOW;
int stateButton;
void setup() {
pinMode(pinButton, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
int stateButton = digitalRead(pinButton); //read the state of the button
if(stateButton == 1) { //if is pressed
digitalWrite(Relay, HIGH); //write 1 or HIGH to led pin
}
else{
digitalWrite(Relay, LOW); //write 0 or LOW to led pin
}
}

2.1 Servo Motors Interfacing with Arduino


Servo motor is position controlled motor. It can easily control physical movement
of objects due to its position controlled feature. Servo motor cannot move
continuously. servo motors rotate in angel ranging from 0 to 180 degree. Servo motor have
many applications in robotics and industry for position based motion control system.
Unlike other motors, servo motor is very easy to interface with Ardino or any other
microcontroller due to its built-in controllers.

Figure 4 : Schematic of Interfacing Servo Motor with Arduino


Servo motor on analog signal. However, the microcontroller do not have analog output, so the fake analog
(Pulse Width Modulation) is used to control the servo motor. Pulse Width Modulation, or PWM, is a
technique for getting analog results with digital means. Digital control is used to create a square wave, a
signal switched between on and off. This on-off pattern can simulate voltages in between full on (5 Volts) and
off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends
off. The duration of "on time" is called the pulse width. To get varying analog values, you change, or
modulate, that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the result
is as if the signal is a steady voltage between 0 and 5v controlling the brightness of the LED.
In the graphic below, the green lines represent a regular time period. This duration or period is the
inverse of the PWM frequency. In other words, with Arduino's PWM frequency at about 500Hz, the green
lines would measure 2 milliseconds each. A call to analogWrite() is on a scale of 0 - 255, such that
analogWrite(255) requests a 100% duty cycle (always on), and analogWrite(127) is a 50% duty cycle (on half
the time) for example.

Figure 5 : PWM Duty Cycle for Servo Motor Rotation Control

2.2 Code for Servo Control using Arduino


#include <Servo.h>

Servo myservo; // create servo object to control a servo


int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}

3. Lab Tasks:
In-Lab Tasks:
 Interface relay with microcontroller: use a push button to actuate the relay and turn
on/off LED
 Interface the servo motor and change its angle from 0-180 and vice versa.
Post-Lab Task:
 Interface a 12v light bulb with microcontroller using the mobile charger adapter
 Using servo motor design automatic door lock system
Lab-5: Serial Communication (Control LED Dimmer using
Serial, and Interfacing GPS Sensor as RS232)

This lab will be focused on interfacing various sensors with Arduino using various types of
serial communication. In order to make two devices communicate, whether they are desktop
computers, microcontrollers, or any other form of computer, you need a method of
communication and an agreed-upon language. Serial communication is one of the most
common forms of communication between computers. Communicating serially involves
sending a series of digital pulses back and forth between devices at a mutually agreed-upon
rate. The two types of serial communication are 1). Asynchronous Serial Communication, and
2). Synchronous Communication.

Lab Objectives
The objectives of this lab is to explore how we can communicate between two devices (PC-PC),
Sensor-Microcontroller (GPS Serial Out), and Microcontroller-PC. The communication can be
done in various ways. However, we are focusing on serial communication between sensors
and microcontroller.
Lab Background and Getting Knowledge of:
1. Basic Understanding of Communication. Student will learn the basic of
communication, serial and parallel communication.
2. Interfacing Asynchronous Serial Communication based Sensor with
Arduino. After this lab, Student should be able to understand the type of
Asynchronous serial communication. Student will be able to configure the
Asynchronous serial port, and we are focusing on GPS (Global Positioning
System) sensor as Asynchronous Serial Communication Sensor in this lab.
Laboratory Pre-Exercise Tasks Overview:
1.1 What is Communication and what are Principles of Communication?
The word communication arises from the Latin word “commūnicāre”, which
means “to share”. Communication is the basic step for the exchange of information. For
example, a baby in a cradle, communicates with a cry that she needs her mother. A cow
moos loudly when it is in danger. A person communicates with the help of a language.
Communication is the bridge to share. Communication can be defined as the process of
exchange of information through means such as words, actions, signs, etc., between two
or more individuals. Any system which provides communication, consists of the three
important and basic parts as shown in the Fig. 1.
Figure 5: Overview of Communication System and Parts of Communication System

 The Sender is the person who sends a message. It could be a transmitting station from
where the signal is transmitted.
 The Channel is the medium through which the message signals travel to reach the
destination.
 The Receiver is the person who receives the message. It could be a receiving station
where the signal transmitted is received.
The communication between sender and receiver can be parallel or serial. In
telecommunication and data transmission, serial communication is the process of sending
data one bit at a time, sequentially, over a communication channel or computer bus. This is
in contrast to parallel communication, where several bits are sent as a whole, on a link with
several parallel channels.

(a). Serial Communication with MSB First


(b). Parallel Communication Interface Example

Figure 2: Overview of Serial and Parallel


Communication

1.2 Interfacing Asynchronous Serial


Communication based Sensor with
Arduino Asynchronous serial
communication, is a common way for two computers to communicate. Both computers must
have their own clock, and keep time independently of each other. This works well for personal
computers, mobile devices, and microcontrollers because they all have their own clock crystal
that acts as the processor’s heartbeat. The Asynchronous serial communication is also termed
as UART which stands for Universal Asynchronous Receiver/Transmitter. UART is
commonly used to communicate with a computer using a simple USB connection. The default
Arduino board and terminal is using the Asynchronous serial communication. Other than that,
we can configure any digital PIN as a Serial Tx and Rx using the other serial libraries such as
SoftwareSerial.
1.2.1 Interfacing GPS with Arduino using UART:
GPS is a very useful device which is used in many electronics projects and
applications like vehicle tracking system, GPS Clock, Accident Detection Alert System, traffic
navigation and surveillance system etc. But question is how to use the GPS and read the data
from GPS? We can easily get the GPS data directly into our computer using Arduino.
GPS stands for Global Positioning System and used to detect the Latitude and
Longitude of any location on the Earth, with exact UTC time (Universal Time Coordinated).
This device receives the coordinates from the satellite for each and every second, with time
and date. GPS offers great accuracy and also provides other data besides position coordinates,
we will into look it shortly. GPS modules typically put out a series of standard strings of
information, under something called the National Marine Electronics Association (NMEA)
protocol. The different string out by the GPS receiver are:

 $GPGGA: Global Positioning System Fix Data


 $GPGSV: GPS satellites in view
 $GPGSA: GPS DOP and active satellites
 $GPRMC: Recommended minimum specific GPS/Transit data

Fig.3 shows the various strings output by the GPS receiver.

Figure 3: Overview of GPS Strings in NMEA Standard Format


1.2.2 UART (Serial Port) Configuration Requirements:
The following are the configuration for Serial Port:
 Speed
Serial ports use two-level (binary) signaling, so the data rate in bits per second is equal to
the symbol rate in baud. The capability to set a bit rate does not imply that a working
connection will result. Not all bit rates are possible with all serial ports. Some special-purpose
protocols such as MIDI for musical instrument control, use serial data rates other than the
teleprinter series. Some serial port systems can automatically detect the bit rate.
The speed includes bits for framing (stop bits, parity, etc.) and so the effective data rate is
lower than the bit transmission rate. For example, with 8-N-1 character framing only 80% of
the bits are available for data (for every eight bits of data, two more framing bits are sent).
Bit rates commonly supported include 75, 110, 300, 1200, 2400, 4800, 9600, 19200, 38400, 57600
and 115200 bit/s.
 Data bits
The number of data bits in each character can be 5 (for Baudot code), 6 (rarely used), 7 (for true
ASCII), 8 (for most kinds of data, as this size matches the size of a byte), or 9 (rarely used). 8
data bits are almost universally used in newer applications. 5 or 7 bits generally only make
sense with older equipment such as teleprinters.
 Parity
Parity is a method of detecting errors in transmission. When parity is used with a serial port,
an extra data bit is sent with each data character, arranged so that the number of 1 bits in each
character, including the parity bit, is always odd or always even. If a byte is received with the
wrong number of 1s, then it must have been corrupted. However, an even number of errors
can pass the parity check.
 Stop bits
Stop bits sent at the end of every character allow the receiving signal hardware to detect the
end of a character and to resynchronize with the character stream. Electronic devices usually
use one stop bit. If slow electromechanical teleprinters are used, one-and-one half or two stop
bits are required.
 Flow control
In many circumstances a transmitter might be able to send data faster than the receiver is able
to process it. To cope with this, serial lines often incorporate a "handshaking" method, usually
distinguished between hardware and software handshaking.
Hardware handshaking is done with extra signals, often the RS-232 RTS/CTS or DTR/DSR
signal circuits. Generally, the RTS and CTS are turned off and on from alternate ends to control
data flow, for instance when a buffer is almost full. DTR and DSR are usually on all the time
and, per the RS-232 standard and its successors, are used to signal from each end that the other
equipment is actually present and powered-up. However, manufacturers have over the years
built many devices that implemented non-standard variations on the standard, for example,
printers that use DTR as flow control.
1.2.3 Serial Port Syntax in Arudino:
Serial.begin(speed)
Serial.begin(speed, config)
config: sets data, parity, and stop bits. Valid values are :
SERIAL_5N1, SERIAL_6N1, SERIAL_7N1, SERIAL_8N1 (the default), SERIAL_5N2,
SERIAL_6N2, SERIAL_7N2, SERIAL_8N2, SERIAL_5E1, SERIAL_6E1,
SERIAL_7E1,SERIAL_8E1, SERIAL_5E2, SERIAL_6E2, SERIAL_7E2, SERIAL_8E2,
SERIAL_5O1, SERIAL_6O1, SERIAL_7O1, SERIAL_8O1, SERIAL_5O2,
SERIAL_6O2SERIAL_7O2, SERIAL_8O2

1.2.4 LED DIMMER Control

Figure 4: Remote LED Control using RS-232 Serial Communication

1.2.5 CODE FOR LED DIMMER Control

const int ledPin = 9; // the pin that the LED is attached to


void setup() {
// initialize the serial communication:
Serial.begin(9600);
// initialize the ledPin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
byte brightness; // check if data has been sent from the computer:
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
brightness = Serial.read();
// set the brightness of the LED:
analogWrite(ledPin, brightness);
}
}
1.2.6 Schematic Diagram of Interfacing GPS:

Figure 5: Schematic Diagram of Interfacing GPS Receiver with Arduino

2. Lab Tasks:
In-Lab Tasks:
 Design LED dimmer control, and observe the brightness level
 Acquire different sensors data on Arduino, and then using RS232 send the data to
another (remote) Arduino for display.
Post-Lab Task:
 Interface a GPS receiver as shown in Figure.5 with Arduino and extract the latitude,
longitude, and altitude from the GPS string. If the receive is not available, the use
Hyper Terminal and send the GPS data file and receive it on Arduino.
Lab-6: RFID based Access Control System (Using RFID and
Servo Motor)

This lab will be focused on interfacing Radio Frequency Identification (RFID) and Servo
Motor to make an access control system. The Basic necessity of security can be attained by
designing various door locks such as mechanical locks or electrical locks. These kind of door
locks are designed with one or more keys, but for locking a large area and by a number of
people’s various locks are needed. Generally, traditional locks are heavy and that are not
strong as they can damage simply by using some tools. Electronic locks are better over
mechanical locks, to resolve the security problems that are connected with the mechanical
locks. In recent days every device uses digital technology. For example, identification of digital
device using token, door lock system using digital technology, automatic door opening and
closing, automatic door lock systems, etc. This kind of systems is used for controlling the
movement of a door without using a key.

Figure 6: Overview of RFID based Door Access Control System


Lab Objectives
The objectives of this lab is to explore how the RFID and Servo motor work. How the
information from the RFID tag is transferred from the tag to the reader. How the servo motor
work on the PWM equivalent signal.
Lab Background and Getting Knowledge of:
1. Basic Understanding of Communication. Student will learn the basic of access
control technologies and motors actuation.
2. Interfacing RFID Sensor with. After this lab, Student should be able to
understand how the RFID works. Interfacing RC522 with Arduino and how the
RC522 transfer data on SPI Bus.
3. Interfacing Servo Motor. After this lab, Student should be able to understand
the various types of motors. The student will be able to interface a specific type
i.e. Servo Motor with Arduino.
Laboratory Pre-Exercise Tasks Overview:
1.1 What is RFID Technology
RFID is a non-contact, automatic identification technology that uses radio signals to
identify, track, sort and detect a variety of objects including people, vehicles, goods and
assets without the need for direct contact or line-of-sight contact (as found necessary in bar
code technology). RFID technology can track movement of objects through a network of
radio-enabled scanning devices over a distance of several metres.
The RFID reader is a wireless device used to transfer data for recognizing and tracking
tags connected to objects. The tag includes electronically stored information. Some kind of
tags is run by electromagnetic induction from magnetic fields formed near the reader. RFID
reader includes an RF module and it acts as a both TX and RX of radio frequency signals.
The transmitter of this module contains an oscillator to make the carrier frequency. A
modulator to intrude data commands upon this carrier s/L and an amplifier to increase the
signal enough to wake the tag. The receiver of this module includes a demodulator to
extract the reverted information and also holds an amplifier to support the signal for
processing. A microprocessor is used to form the control unit, which employs an OS and
memory of this module filter and stores the information.

Figure 2: Overview of RFID Working


1.1.2 Interfacing Synchronous Serial Communication based Sensor with Arduino:
Simpler integrated circuits that have only one function, such as to read a sensor or to
control a digital potentiometer or an oscillator to drive a PWM circuit. These ICs have no clock
crystal of their own. They consist of a few memory registers and the minimal circuitry needed
to connect these memory registers to the circuit that they control. To communicate with these
ICs, you need to use synchronous serial communication.
Synchronous serial communication protocols feature a controller device which sends a
clock pulse to one or more peripheral devices. The devices exchange a bit of data every time
the clock changes. There are two common forms of synchronous serial, Inter-Integrated
Circuit, or I2C (sometimes also called Two-Wire Interface, or TWI), and Serial Peripheral
Interface, or SPI.
1.3.1 Interfacing RFID-RC522 with Arduino:
RC522 is very simple yet effective module. It is an RFID module and is used for scanning
RFID cards. Its a new technology and is expanding day by day. Now-a-days it is extensively
used in offices where employees are issued an RFID card and their attendance is marked when
they touch their card to rfid reader.
RFID is the abbreviation of Radio frequency identification. RFID modules use
electromagnetic fields to transfer data between card and the reader. Different tags are attached
to objects and when we place that object in front of the reader, the reader reads that tags.
Another benefit of RFID is that it doesn’t require to be in a line of sight to get detected. As in
barcode, the reader has to be in the line of sight to the tag and then it can scan but in RFID
there’s no such restriction.
1.3.2 Schematic Diagram:

Figure 2: Schematic Diagram of Interfacing RFID Reader with Arduino


Figure 3: PINs connections of Interfacing RFID Reader with Arduino

1.3.3 Code for Interfacing RFID Reader with Arduino using SPI Synchronous Serial

#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9
#define SS_PIN 10
MFRC522 mfrc522(SS_PIN, RST_PIN);
void setup()
{

SPI.begin();
mfrc522.PCD_Init();
}
void loop() {
RfidScan();
}

void dump_byte_array(byte *buffer, byte bufferSize) {


for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? ” 0″ : ” “);
Serial.print(buffer[i], HEX);
}
}
void RfidScan()
{
if ( ! mfrc522.PICC_IsNewCardPresent())
return;

if ( ! mfrc522.PICC_ReadCardSerial())
return;
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
}
2. Lab Tasks:
In-Lab Tasks:
 Design RFID reader system that store three RFID tags, and provide access if the tag
match otherwise display access not allowed.
Post-Lab Task:
 Design an RFID and motors based door lock system that allows access to only
registered RFID tags and no access to authorized user Tags. You can use below
information about motors and Lab.4 about servo motor control.
o Familiarize yourself with the basics of permanent magnet DC motors
http://www.pcbheaven.com/wikipages/How_DC_Motors_Work/
http://en.wikipedia.org/wiki/Brushed_DC_electric_motor
o Familiarize yourself with the basics of Stepper Motors
http://homepage.cs.uiowa.edu/~jones/step/
http://www.pcbheaven.com/wikipages/How_Stepper_Motors_Work/
http://en.wikipedia.org/wiki/Stepper_motor
http://learn.adafruit.com/adafruit-motor-shield/faq

.
Lab-7: Interfacing Bluetooth with Arduino and Android
Bluetooth APP

This lab will be focused on interfacing Bluetooth module with the Arduino and an android
APP to control the LED lights connected with Arduino. Bluetooth was invented by a telecom
specialist Ericsson in1994. It is an alternate of the RS-232 cables. It created above mentioned
body which is supported by Intel and takes care of development and licensing. Any company
who want to use the standards or market products with the technology is required to become
the member of above committee. The name comes from an epithet of a tenth-century King of
Denmark and Norway named Harald “Bluetooth” Gormsson. In the local language, he was
called Blåtand or Blåtann, which translated in English, became ‘Bluetooth’.

Figure 7: Overview of LED control system using Smartphone Bluetooth Based App
Lab Objectives
The objectives of this lab is to explore how the Bluetooth works. How the information is
transferred from the Smartphone App to the Arduino using the smart phone Bluetooth and
the Bluetooth interfaced with the Arduino.

Lab Background and Getting Knowledge of:


1. Basic Understanding of Communication. Student will learn the basic of
Bluetooth communication and how it works.
2. Interfacing Bluetooth with Arduino. After this lab, Student should be able
to understand how the Bluetooth module
3. can be interfaced with arduino.
4. Interfacing the Arduino Bluetooth with Android App:
Laboratory Pre-Exercise Tasks Overview:
1.2 How Bluetooth Works
Bluetooth operates in the standard Industrial, Scientific and Medical (ISM) short range
frequency band of 2.4 GHz. Specifically, it operated in the 2400–2483.5 MHz frequency band,
which includes guard bands as well. It uses something called Frequency Hopping Spread
Spectrum (FHSS), which is basically a multiple access method in which data packets are
divided based on frequency over 79 designated Bluetooth channels. Each channel has a
bandwidth of 1 MHz. The newer Bluetooth 4.0 standard, however, uses 2 MHz steps and thus
has 40 designated channels. It uses a variation of FHSS called Adaptive Frequency-hopping
spread spectrum (AFH), which theoretically skips channels with interference and results in
better communication.

Figure 2: Channel Distributions for Bluetooth in S-Band for Frequency Hopping

Bluetooth is essentially a protocol with a master-slave architecture, which means that one
master device can communicate with up to 7 devices. This was and is a huge advantage to
earlier wired communication protocols which could work only with a 1 to 1 configuration.
Essentially creating a new standard called Personal Area Networks (PANs),
Bluetooth brought about far more effective ad-hoc networks and allows communication
without traditional host based networking. For Master-Salve configuration you can follow:
http://howtomechatronics.com/tutorials/arduino/how-to-configure-pair-two-hc-05-bluetooth-module-master-slave-
commands/

Figure 3: Clustering (Master-Salve) Configuration for multiple Bluetooth connecting to Single Bluetooth
1.3 Pin Configuration of HC-05 Bluetooth module
There are 6 pins available at the output of module. Facing back side, from left to right these
are as follows:

 EN Used for AT commands. In normal usage it is not required to be connected.


 VCC Power supply +5V
 GND Power supply ground
 TxD Transmitting pin
 RxD Receiving Pin
 STATE Gives digital output shoeing status whether module is connected or not.
1.4 Circuit Diagram of HC-05 Bluetooth module interfacing with Arduino
Connect the circuit as follows:

 Bluetooth Tx with Arduino UNO Rx (D0)


 Bluetooth Rx with Arduino UNO Tx (D1)
 Bluetooth VCC with Arduino UNO +5V
 Bluetooth GND with Arduino UNO GND
 No need to connect any other pin as given in figure.
NOTE: Make shore you plug out the Tx and Rx pins out of Arduino before uploading the program.
After uploading the program connect them back. Otherwise you can get an error.

1.5 Code for HC-05 Bluetooth module interfacing with Arduino and Control LED
using Mobile Bluetooth APP

 Download BT (Bluetooth) Serial Terminal monitor from smartphone APP Store


 Send 1 for turning ON an LED and 0 vice versa.

1. #define ledPin 7
2. int state = 0;
3.
4. void setup() {
5. pinMode(ledPin, OUTPUT);
6. digitalWrite(ledPin, LOW);
7. Serial.begin(38400); // Default communication rate of the Bluetooth module
8. }
9.
10. void loop() {
11. if(Serial.available() > 0){ // Checks whether data is comming from the serial port
12. state = Serial.read(); // Reads the data from the serial port
13. }
14.
15. if (state == '0') {
16. digitalWrite(ledPin, LOW); // Turn LED OFF
17. Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
18. state = 0;
19. }
20. else if (state == '1') {
21. digitalWrite(ledPin, HIGH);
22. Serial.println("LED: ON");;
23. state = 0;
24. }
25. }

2. Lab Tasks:
In-Lab Tasks:
 Design a system to control 3 lights (LEDs) from smartphone Bluetooth app and
display analog and digital sensors data on smartphone Bluetooth app
Post-Lab Task:
 Design Bluetooth APP based smart home automation control system that remote
control of lights, display temperature and humidity level of a home
Lab-8: Arduino External Interrupts (An interrupts based
Devices Control)

This lab will be focused on how to use Arduino interrupts. Unlike timer interrupts, external
interrupts are triggered by external events. For example, when a button is pushed or you
receive a pulse from a rotary encoder. However, just like the timer interrupts, you don’t need
to keep polling the GPIO pins for a change.

Lab Objectives
The objectives of this lab is to explore how the interrupts work. First, we will see what are
Arduino interrupts? After that we will see the general concepts of interrupts. We will see how
to use interrupt service routine with Arduino. At the end of lab, we will take two examples to
demonstrate the effect and use of Arduino projects in real world embedded systems projects.
Lab Background and Getting Knowledge of:
1. Basic Understanding of Interrupts. Student will learn the basic of interrupts
working and interrupt service routines.
2. Interfacing of Actuator working with Interrupts. After this lab, Student
should be able to understand how link the interrupt service routine with external
PINs interrupts.
Laboratory Pre-Exercise Tasks Overview:
1.1 What is an Interrupts?
Interrupts are the section of hardware and software on microcontroller which is
capable of monitoring the external event on the input pin when any external event is
monitor then the program is stop execution at this point and jump into their ISR function
which is a interrupt handler then after executing the ISR function go back that point where
the external event is monitor than it complete there execution. Different types of Arduino
board have different numbers of interrupts pins e.g. Arduino UNO have two interrupt
ports and Arduino Mega2560 have six interrupt ports named as INT1,INT0. On the

Figure 1: Arduino Boards and Interrupts


software side create sleep mode for Arduino and use a timer base interrupts which would
internally be essentially triggering awakening function and not relay on any external
hardware.

1.2 How an Interrupt Works?


So interrupts call an external function which is more commonly called an interrupts
service routine or an ISR function. Interrupts service routine do have very specific
constrains and do not behave exactly like some of the other functions that have been
written for the Arduino. Interrupt service routine (ISR) is also called an interrupts handler.
There are many different type of interrupt handler which may handles many different
types of interrupts like same as a simple example the clock in a system have its own
interrupt handler same as the keyboard it also have its own interrupt handler for every
device which is existing have its have its interrupt handler.
Generally ISR will use that something called a volatile variable which can still be used
between other pieces of code also ISR should be short and fast as possible. Interrupts
execute immediately if stop everything than program will currently doing in order to jump
into the interrupts function and execute the code. Furthermore the interrupts will returns
to the same point within the software where had perversely left off.

Figure 2: An interrupt working Example

Above is the example of execution so line by line the code is execute until interrupt is called
on Line3 then the function jumps down to the ISR and started executing the line5 and line
6 than after executing the lines within the ISR it jumps back to line4 and finishing the
execution as routine. If it is in loop than go back to line1.
1.3 How an Interrupt is triggered?
In Arduino interrupts, you can set how the interrupts are been triggered. There
are five types of triggering Arduino interrupts:
 Change: When signal change even if signal rise or signal fall or if the signal is
in low state at 0 or if the signal is in high state trigger 5v.
 Rising: On a rising edge the signal going from low to high means signal
triggering from 0v to 5v.
 Falling: On a falling edge the signal going from high to low means signal is
triggering from 5v to 0v.
 Low: Low is a continuous trigger whenever the signal is low in other words the
signal is on 0v.
 High: High is a continuous trigger whenever the signal is high in other words
the signal is on 5v.
1.4 How to use an Arduino interrupts?
Now lets see how to use Arduino interrupts functions already available in Arduino
IDE to initialize Arduino interrupts and with which pin of Arduino you want to
initialize it. Attach interrupt function is used for this purpose. This function takes
two arguments as a input. one is a pin number to which pin you want to use for
external interrupt triggering. Second argument is function name to which you want
to call upon every interrupt. Last argument is the types of interrupt you are using.
we have explained five types above.
attachInterrupt ( digitalPinToInterrupt ( pin ), ISR, mode ) ;
e.g.
attachInterrupt ( digitalPinToInterrupt ( 2 ), InterruptFunction, Low ) ;
1.5 Schematic and Code for Blinking LED using Interrupts

Figure 2: Schematic for Blinking an LED using Arduino Interrupts


const byte ledPin = 13 ;
const byte interruptPin = 2 ;
volatile byte state = LOW ;
void setup ( ) {
pinMode ( ledPin , OUTPUT ) ;
pinMode ( interruptPin , INPUT_PULLUP) ;
attachInterrupt ( digitalPinToInterrupt ( interruptPin ), glow, CHANGE ) ;
}
void loop ( ) {
digitalWrite ( ledPin, state ) ;.
}
void glow ( )
{
state = !state ;
}

2. Lab Tasks:
In-Lab Tasks:
 Design a system to control smart home light using the PIN change interrupts
Post-Lab Task:
 Design Rest-room exhaust fan and light control 1) using PIR sensors to detect the
entrance, exit and number of persons in the rest-room area 2) If no body in rest-room
area then switch OFF exhaust fan and lights otherwise turn it ON.
Lab-9: Arduino-Controlled Smart Home Internet-of-Things
Platform (Web-Controlled Smart Home Appliances)

This lab will be focused on to build a smart home device which can be used to control the home
appliances via internet. The home automation device that you build can be integrated with
almost all the home appliances and can be used to control them remotely from any part of the
world. To facilitate the wireless connectivity with the system, the Arduino Uno will be
embedded with a WiFi module. This establishes the internet connection to the system and all
the home appliances can in turn be connected and controlled by internet.

Lab Objectives
The objectives of this lab is to explore what is internet-of-things. First, we will see how the
home legacy devices can be connected to the internet to remotely access it. Second, we will see
how the local-IP can be port-forward in order to access the local home appliances that are
internet enabled now.

Lab Background and Getting Knowledge of:


1. Basic Understanding of IoT Platform. Student will learn the basic definitions of
IoT, gateway, and how the legacy devices can be internet enabled.
2. Interfacing of Home Sensors and Actuator. After this lab, Student should be
able to understand how to read the home appliances data, design control for
home appliance, and remote access through web using HTTP and web-server.
3. Port Forwarding and Global IP Addressing: After this lab, student will be
how to configure Port-forwarding to access the local static IP on the internet.
Laboratory Pre-Exercise Tasks Overview:
1.2 What is IoT and Smart Home?
The advancements in Internet and web technologies provide a platform to users to
create and consume information. In last decade, the research has focused on the
connectivity of all physical objects and information environment to the Internet for
enabling a user to access and control things from anywhere and at any time. This revolution
coined the term’s Internet of Things (IoTs) and the Internet of Everything (IoE). IoTs and
IoE make smaller objects or things more intelligent and more connected, to perform
complex tasks. The IoT is rapidly gaining ground in service and application of latest
wireless and wire communications. Also, the IoT is a dynamic and adaptive global
information network of a home or a city composed of Internet‐connected things and
objects, such as sensors, actuators, Auto‐IDs, radiofrequency identifications and physical
objects, as well as other organizations and smart devices that are becoming a vital element
of the Internet.

Figure 1: Overview of the Global IoT Market (https://www.tado.com/en/internet-of-


things)

The technological trends of IoTs and WoTs show that the next‐generation smart home
environment will be ubiquitous, pervasive, and perceptual. The pervasive systems without
user interaction support will not exist, and the system which is difficult to use, obtrusive
and subject to risks, will not be used by users. Smart home embeds computing capabilities,
networking, and telecommunication interfaces in the home appliances in order to facilitate
everyday life. The smart home environment comprises sensors, actuators, interfaces, and
appliances networked together to provide localized and remote control of the environment.
Sensing and monitoring of environment include temperature, humidity, light, and motion.
Environment control such as heater and fan ON/OFF control is provided by the actuator
having dedicated hardware interfaces and computing capabilities.

Figure 2: Overview of the Conceptual Smart Home IoT


1.2 How is Port Forwarding and How it works?
In computer networking, port forwarding or port mapping is an application
of network address translation (NAT) that redirects a communication request from
one address and port number combination to another while the packets are traversing a
network gateway, such as a router or firewall. This technique is most commonly used to
make services on a host residing on a protected or masqueraded (internal) network
available to hosts on the opposite side of the gateway (external network), by remapping
the destination IP address and port number of the communication to an internal host.

Figure 3: Overview of the Port Forwarding at Switch (AP) for Remote Access

1.3 Block Diagram of Smart Home IoT Control

Figure 4: Block Diagram of Smart Home


1.4 Source Code Example for Smart Home IoT appliances Control
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "DHT.h"
#include <Servo.h>
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
// DHT Sensor
uint8_t DHTPin = D8;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

float Temperature;
float Humidity;

/*Put your SSID & Password*/


const char* ssid = "PTCL-BB"; // Enter SSID here
const char* password = "9020ac16"; //Enter Password here

ESP8266WebServer server(8089);

uint8_t LEDpin = D2;


uint8_t FANpin = D3;
uint8_t DOORpin = D4;
Servo myservo;

bool LEDstatus = LOW;


bool FANstatus = LOW;
bool DOORstatus = LOW;

int i = 0;
int j = 0;
int k = 0;

void setup() {
Serial.begin(9600);
delay(100);
dht.begin();
pinMode(FANpin, OUTPUT);
pinMode(LEDpin, OUTPUT);
// pinMode(DOORpin, OUTPUT);
pinMode(DHTPin, INPUT);
myservo.attach(DOORpin);
Serial.println("Connecting to ");
Serial.println(ssid);

//connect to your local wi-fi network


WiFi.begin(ssid, password);

//check wi-fi is connected to wi-fi network


while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected..!");
Serial.print("Got IP: "); Serial.println(WiFi.localIP());

server.on("/", handle_OnConnect);
server.on("/ledon", handle_ledon);
server.on("/ledoff", handle_ledoff);
server.onNotFound(handle_NotFound);

server.on("/fanon", handle_fanon);
server.on("/fanoff", handle_fanoff);

server.on("/dooropen", handle_dooropen);
server.on("/doorclose", handle_doorclose);

server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
if(LEDstatus)
digitalWrite(LEDpin, HIGH);
else
digitalWrite(LEDpin, LOW);
if(FANstatus)
digitalWrite(FANpin, HIGH);
else
digitalWrite(FANpin, LOW);
if(DOORstatus)
myservo.write(90);
//digitalWrite(DOORpin, HIGH);
else
myservo.write( 0 );
//digitalWrite(DOORpin, LOW);
}

void handle_OnConnect() {
LEDstatus = LOW;
FANstatus = LOW;
myservo.write(0);
//DOORstatus = LOW;
i = 0;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
// Temperature = 20.34;
// Humidity = 17.01;
server.send(200, "text/html" ,SendHTML());
}

void handle_ledon() {
LEDstatus = HIGH;
i = 1;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
// Temperature = 20.01;
// Humidity = 16.01;
server.send(200, "text/html",SendHTML());
}

void handle_ledoff() {
LEDstatus = LOW;
i = 0;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
// Temperature = 10.34;
// Humidity = 13.01;
server.send(200, "text/html",SendHTML());
}

void handle_fanon() {
FANstatus = HIGH;
j = 1;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
// Temperature = 22.34;
// Humidity = 13.01;
server.send(200, "text/html",SendHTML());
}

void handle_fanoff() {
FANstatus = LOW;
j = 0;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
// Temperature = 12.34;
// Humidity = 11.01;
server.send(200, "text/html",SendHTML());
}

void handle_dooropen() {
//DOORstatus = HIGH;
myservo.write(90);
k = 1;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
// Temperature = 18.34;
// Humidity = 7.01;
server.send(200, "text/html",SendHTML());
}

void handle_doorclose() {
//DOORstatus = LOW;
myservo.write(0);
k = 0;
Temperature = dht.readTemperature(); // Gets the values of the temperature
Humidity = dht.readHumidity(); // Gets the values of the humidity
//Temperature = 2.34;
//Humidity = 1.01;
server.send(200, "text/html",SendHTML());
}

void handle_NotFound(){
server.send(404, "text/plain", "Not found");
}
String SendHTML(){
String ptr = "<!DOCTYPE html>";
ptr += "<html>";
ptr += "<head>";
ptr += "<title>Home_Automation_NodeMCU</title>";
ptr += "</head>";
ptr += "<body>";
ptr += "<h1 style='vertical-align: text-top;color:black;line-height:40px;font-
size:48px;font:EraslightITC;text-align:center;background-color:cyan'><img src='home.png'
alt='Home_Logo'> Home Automation</h2>";

ptr +="<h2 style='text-align:center;'><rec style='font-size:25px;font:EraslightITC;background-


color:cyan;'>Temp & Humidity ";
ptr +=Temperature;
ptr +="C ";
ptr +=Humidity;
ptr +="%</rec></h2>";

if(i == 0)
ptr += "<h2 style='text-align:center;'><input type=\"button\" style='background-color:white;font-
size:37px;font:EraslightITC;'value=\"Bed Room Light OFF\" id=\"light\"></input></h2>";
else
ptr += "<h2 style='text-align:center;'><input type=\"button\" style='background-color:white;font-
size:37px;font:EraslightITC;'value=\"Bed Room Light ON\" id=\"light\"></input></h2>";
ptr += "<h2 style='text-align:center'>";
ptr += "<button onclick=\"window.location.href='/ledon'; light_on();\" style='color:black;line-
height:42px;font-size:39px;font:EraslightITC;button-align:center;background-color:cyan' > Light ON
</button>";
ptr += "<button onclick=\"window.location.href='/ledoff'; light_off();\" style='color:black;line-
height:42px;font-size:39px;font:EraslightITC;button-align:center;background-color:cyan' > Light OFF
</button>";

if(j == 0)
ptr += "<h2 style='text-align:center;'><input type=\"button\" style='background-color:white;font-
size:38px;font:EraslightITC;'value=\"Bed Room Fan OFF\" id=\"fan\"></input></h2>";
else
ptr += "<h2 style='text-align:center;'><input type=\"button\" style='background-color:white;font-
size:38px;font:EraslightITC;'value=\"Bed Room Fan ON\" id=\"fan\"></input></h2>";

ptr += "<h2 style='text-align:center'>";


ptr += "<button onclick=\"window.location.href='/fanon'; fan_on();\" style='color:black;line-
height:43px;font-size:43px;font:EraslightITC;button-align:center;background-color:cyan' > Fan ON
</button>";
ptr += "<button onclick=\"window.location.href='/fanoff'; fan_off();\" style='color:black;line-
height:43px;font-size:43px;font:EraslightITC;button-align:center;background-color:cyan' > Fan OFF
</button>";

if(k == 0)
ptr += "<h2 style='text-align:center;'><input type=\"button\" style='background-color:white;font-
size:68px;font:EraslightITC' value=\"Door Close\" id=\"door\"></input></h2>";
else
ptr += "<h2 style='text-align:center;'><input type=\"button\" style='background-color:white;font-
size:68px;font:EraslightITC' value=\"Door Open\" id=\"door\"></input></h2>";
ptr += "<h2 style='text-align:center'>";
ptr += "<button onclick=\"window.location.href='/dooropen'; door_open();\" style='color:black;line-
height:34px;font-size:33px;font:EraslightITC;button-align:center;background-color:cyan'> Door Open
</button>";
ptr += "<button onclick=\"window.location.href='/doorclose'; door_close();\" style='color:black;line-
height:34px;font-size:33px;font:EraslightITC;text-align:center;background-color:cyan'> Door Close
</button></h2>";
ptr += "<script>";
ptr += "function fan_off() {document.getElementById(\"fan\").value = \"Bed Room Fan OFF\"; }";
ptr += "</script>";
ptr += "<script>";
ptr += "function fan_on() {document.getElementById(\"fan\").value = \"Bed Room Fan ON\";}";
ptr += "</script>";
ptr += "<script>";
ptr += "function light_off() {document.getElementById(\"light\").value = \"Bed Room Light OFF\";}";
ptr += "</script>";
ptr += "<script>";
ptr += "function light_on() {document.getElementById(\"light\").value = \"Bed Room Light ON\";}";
ptr += "</script>";
ptr += "<script>";
ptr += "function door_open() {document.getElementById(\"door\").value = \"Door Open\";}";
ptr += "</script>";
ptr += "<script>";
ptr += "function door_close() {document.getElementById(\"door\").value = \"Door Close\";}";
ptr += "</script>";
ptr += "</body>";
ptr += "</html>";

return ptr;
}
2. Lab Tasks:
In-Lab Tasks:
 Configure the NodeMCU (WiFi) and control 3-LEDs to turn them ON/OFF from
internet
Post-Lab Task:
 Design Web-enabled Smart Home System to control remotely home lighting
system, FAN, Door, and show the temperature and humidity on webpage
Lab-10: Data Transfer of Arduino-Controlled Smart Home to
Thingspeak Cloud
This lab will be focused on cloud data storage and visualization. Thingspeak is an IoT analytics
cloud platform service that allows you to aggregate, visualize, and analyze live data streams
in the cloud. You can send data to Thingspeak from your devices, create instant visualizations
of live data, and send alerts using web services. Thingspeak enables engineers and scientists
to prototype and build IoT systems without setting up servers or developing web software.
Lab Objectives
The objectives of this lab is to explore Configure devices to send data to Thingspeak using a
REST API or MQTT. Aggregate data on-demand from devices and third-party sources. Get
instant visualizations of live or historical sensor data. Run your IoT analytics automatically
based on schedules or events. Act on your data and communicate using third-party services
like Twitter.

Lab Background and Getting Knowledge of:


1. Basic Understanding of IoT Cloud Platform. Student will learn the basic
definitions of cloud, cloud data storage, and how the data is transferred to a cloud.
2. Interfacing of Home Sensors and Actuator and Store data on Cloud.
Implement a low cost, reliable and scalable measuring temperature and
humidity cloud system
3. Connecting Legacy Device to Internet: After this lab, student will be how to
access legacy devices on cloud.
Laboratory Pre-Exercise Tasks Overview:
1.3 Implementation and Working Strategy
Make all the connections as per the circuit diagram. Here, we’ll be uploading the code
directly to the ESP8266 Module. This means that the existing code or firmware will be erased.
Before uploading the code, connect the GPIO0 to GND and RESET the ESP Module to enable
Programming Mode. Also, select “Generic ESP8266 Module” in the Boards section of the
Arduino IDE. Make sure that you have selected the correct COM PORT. After uploading the
code, first, disconnect the GPIO0 from GND (you can let is float) and RESET the ESP Module.
Now, if you open the Serial Monitor and set the baud rate to 115200 and also select “Both NL
& CR” option, you can see the progress of the ESP8266 Module.

First, it will get connected to the WiFi Network. Then, immediately, it will try to read the data
from the DHT11 Humidity sensor and calculate the Temperature and Humidity values based
on that data. After this, the values of temperature and humidity will be uploaded to the
Thingspeak API. If you open your channel in the Thingspeak, you can see the chart associated
with the values from the DHT11 Sensor.

Figure 1: Connecting devices to the Cloud using NodeMCU

1.4 Flow Chart and Source for Smart Home Data to Cloud

Figure 2: Flow chart for connecting devices to the Cloud using NodeMCU
2. Lab Tasks:
In-Lab Tasks:
 Configure the Thingspeak cloud and Design NodeMCU based to acquire the humidity
and temperature data and display on cloud
Post-Lab Task:
 Design cloud-based Smart Home System to store and visualize home lighting
system, FAN, Door, temperature and humidity
Lab-11: Introduction of Raspberry PI, Installation of
RTOS/Raspbian Operating System, Database on System-on-
Chip (Raspberry Pi) MYSQL
These labs will be focused on concepts of System-on-Chip designing and specifically on
Raspberry-PI board. 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.
Lab Objectives
The objectives of these lab is to explore system-on-chip, Real Time operating, and databases
to store the embedded system.

Lab Background and Getting Knowledge of:


1. Basic Understanding of System-on-Chip. Student will learn the basic concepts
of system-on-chip, realtime operating system, and different types of databases.
2. Installation of RTOS and Databases on Raspberry-PI (SoC). Installation
of RTOS and Databases on Raspberry-PI using Linux form of commands.
3. Design and Implementation using SoC: After this lab, student will be able
to differentiate between controller and SoC. They will be able to implement and
design using SoC platform.

Laboratory Pre-Exercise Tasks Overview:


1.1 Installation of Operating System and Database on Raspberry-PI
See notes as provided with Lab.
2. Lab Tasks:
In-Lab Tasks:
 Installation and Configuration of Raspberry-PI board (Operating system, and
database)
Post-Lab Task:
 Database schema of smart home system
 Implementation of smart home database on Raspberry-PI
 Storing smart home data to the database.
Lab-11: Introduction of Raspberry PI, Installation of
RTOS/Raspbian Operating System
These labs will be focused on concepts of System-on-Chip designing and specifically on
Raspberry-PI board. 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.

Lab Objectives
The objectives of this lab are to explore system-on-chip, Real Time operating system and
basics of Python IDE.

Lab Background and Getting Knowledge of:


1. Basic Understanding of System-on-Chip: Student will learn the basic concepts of
system-on-chip, real-time operating system, and coding in python IDE.
2. Installation of RTOS and Databases on Raspberry-PI (SoC): Installation of RTOS
on Raspberry-PI using Linux form of commands.
3. Design and Implementation using SoC: After this lab, student will be able to
differentiate between controller and SoC. They will be able to implement and
design using SoC platform.

Laboratory Pre-Exercise Tasks Overview:

Introduction of Raspberry PI:


Raspberry Pi is a small single board computer. By connecting peripherals like Keyboard,
mouse, display to the Raspberry Pi, it will act as a mini personal computer. Raspberry Pi
is popularly used for real time Image/Video Processing, IoT based applications and
Robotics applications. Raspberry Pi is slower than laptop or desktop but is still a
computer which can provide all the expected features or abilities, at a low power
consumption. Raspberry Pi Foundation officially provides Debian based Raspbian OS.
Also, they provide NOOBS OS for Raspberry Pi. We can install several Third-Party
versions of OS like Ubuntu, Archlinux, RISC OS, Windows 10 IOT Core, etc.

Raspbian OS is official Operating System available for free to use. This OS is efficiently
optimized to use with Raspberry Pi. Raspbian have GUI which includes tools for
Browsing, Python programming, office, games, etc. We should use SD card (minimum 8
GB recommended) to store the OS (operating System).

Raspberry Pi is more than computer as it provides access to the on-chip hardware i.e.
GPIOs for developing an application. By accessing GPIO, we can connect devices like
LED, motors, sensors, etc and can control them too.

It has ARM based Broadcom Processor SoC along with on-chip GPU (Graphics
Processing Unit). The CPU speed of Raspberry Pi varies from 700 MHz to 1.2 GHz. Also,
it has on-board SDRAM that ranges from 256 MB to 1 GB. Raspberry Pi also provides on-
chip SPI, I2C, I2S and UART modules.

Hardware specifications table:


Serial# Name Description
1 The processor This chip is a 32 bit,700MHz System on chip
2 The secure SD/MMC/SDIO card slot (3.3 card power support only)
digital card slot
3 The USB port Model B has 2 USB 2.0 ports.
4 Ethernet port Model B has standard RJ45 connector and Model A does
not
5 HDMI connector The HDMI port provides digital video and audio output
hence TV can be connected 14 different video
resolutions are supported.
6 STATUS LEDs ACT Green Light when the SD card is accessed.
PWR Red Hooked upto 3.3 power.
FDX Green ON if network adapter is full duplex.
LNX Green Network activity light.
100 Yellow On if the network connection is
100Mbps.
7 Analog Audio This is a standard 3.5mm mini analog audio jack
out intended to drive high impedance load (like amplified
speakers)
8 Composite This is a standard RCA-type jack that provides NTSC or
Video out PAL video signals.
9 Memory 512 MB in Model B and 256 MB in Model A.
(SDRAM)
10 Supporting Arch Linux ARM, Debian GNU/Linux, Gentoo, Fedora,
operating FreeBSD, NetBSD, Plan 9, Raspbian OS, RISC OS,
systems Slackware Linux

Installation of RTOS on Raspberry-PI (SoC):


For installing Operating System in RPi:

Software requirements: Debian/Linux image file. Win32 Disk imager. Download


NOOBs setup (offline and network install recommended).

Hardware requirements:

 Raspberry Pi board (Broadcom BCM 2835) Model B.


 SD card at least 8GB,
 Monitor,
 USB Keyboard
 and USB mouse.
Installation steps:

Operating Systems:

Raspbian (Optimized for RP)

How to install Raspbian

 Use NOOBS
 Use NOOBS Lite
 Download only Raspbian image file

NOOBS

It is an easy operating system installer which contains Raspbian.

OS & NOOBS download site

http://www.raspberrypi.org/downloads/

Preparing an RPi OS in a SD card:

Procedure:

An SD card is needed to store Raspbian. For this purpose connect micro SD card to SD
card reader.
Difference between using NOOBS and Downloading Raspbian Image.

Download the NOOBS or the Raspbian image file from the following links

http://www.raspberrypi.org/downloads/downloads/noobs/

http://www.raspberrypi.org/downloads/downloads/raspbian/
Writing image to Micro SD card

A specific software is required to write the Raspbian image on to the MicroSD card.
Win32 Disk Imager is the software that can be used for this purpose. It can be
downloaded from the following link

http://sourceforge.net/projects/win32diskimager/
Setup Win32 Disk Imager

Now this image can be written to Micro USB.


Python IDE:
Python is a multipurpose programming language, and it has applicability pretty much
anywhere that uses data, mathematical computation, or lines of code. That means unlike
Java, for instance, Python isn't confined to being used for web development.

Like most programming languages, Python works in tandem with an interpreter that
executes the finalized lines of codes. There are lots of free resources to learn the Python
coding language, which, with its basis in English syntax, is considered one of the least
fussy and most straightforward coding languages to learn and read.

Raspberry Pi OS and other Linux (Debian-based) distributions

Most distributions of Linux come with Python 3 already installed, but they might not
have IDLE, the default IDE (interactive development environment), installed.

Use apt to check whether they are installed and install them if they aren’t.

Open a terminal window and type:

o sudo apt update


o sudo apt install python3 idle3

This will install Python 3 (and IDLE), and you should then be able to find it in your
Application menu.
1. Lab Tasks:
In-Lab Tasks:

 Installation and Configuration of Raspberry-PI board (Operating system, and


database)
 Installation of Python IDE on Raspberry Pi board
Lab-12: Basic Interfacing (LDR, Proximity Sensors, Camera) with
Raspberry Pi using Python
These labs will be focused on concepts of System-on-Chip designing and specifically on
Raspberry-PI board. 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.

Lab Objectives
The objectives of this lab is to implement the lab already performed on Arudino on
Raspberry-PI now. The student will be able to convert the Arudino C based programming
into Python.

Lab Background and Getting Knowledge of:


1. Basic Understanding of Raspberry-PI Pins Configuration: Student will learn the
basic concepts of interfacing the hardware with the Raspberry-PI.
2. Conversion of Arduino C code to Python: Using previous labs concepts convert
it into Python.
3. Design and Implementation using SoC: After this lab, student will be able to
design and interface different embedded components such as LDR, Ultrasonic
range finder, and camera interfacing.

Laboratory Pre-Exercise Tasks Overview:

Interfacing LDR:
LDR “light-dependent resistor to control an LED” light-emitting diode” can be interfaced with
Raspberry PI to measure intensity of light. The LED will be turned on and turned off depending
on the light intensity in the room. This project can also be used for day and night detection.

Light Dependent Resistor LDR:


A photoresistor or light dependent resistor is an electronic component that is sensitive to
light. When light falls upon it, then the resistance changes. Values of the resistance of the
LDR may change over many orders of magnitude the value of the resistance falling as the
level of light increases.

Components required:

 Raspberry PI
 Breadboard
 LED
 Resistor
 Photoresistor 3 pin
 Jumper cables
Schematic Diagram of connecting LDR with Raspberry Pi:
Interfacing Proximity Sensor with Raspberry Pi to measure distance:

Ultrasonic Sensors, particularly HC-SR04 Ultrasonic Sensor, are very popular among
electronic hobbyists and are frequently used in a variety of projects like Obstacle
Avoiding Robot, Distance Measurement, Proximity Detection and so forth. In this project,
we will learn about HC-SR04 Ultrasonic and see how to interface one with Raspberry Pi.

Ultrasonic Sensor:
An ultrasonic sensor is an electronic device that measures the distance of a target object
by emitting ultrasonic sound waves, and converts the reflected sound into an electrical
signal. Ultrasonic waves travel faster than the speed of audible sound (i.e., the sound that
humans can hear).

Components required:

 Raspberry PI
 Breadboard
 LED
 Resistor
 Photoresistor 3 pin
 Jumper cables
Schematic Diagram of connecting Ultrasonic sensor with Raspberry Pi:
Pi Camera Module Interface with Raspberry Pi using Python
Pi Camera module is a camera which can be used to take pictures and high-definition
video. Raspberry Pi Board has CSI (Camera Serial Interface) interface to which we can
attach PiCamera module directly.

This Pi Camera module can attach to the Raspberry Pi’s CSI port using 15-pin ribbon
cable.

Features of Pi Camera

Its features are listed below,

 Resolution – 5 MP

 HD Video recording – 1080p @30fps, 720p @60fps, 960p @45fps and so on.

 It Can capture wide, still (motionless) images of resolution 2592x1944 pixels

 CSI Interface enabled.

Before using Pi Camera, we need to enable camera for its working.

How to Enable Camera functionality on Raspberry Pi

For enabling camera in Raspberry Pi, open raspberry pi configuration using following
command,
sudo raspi-config

then select Interfacing options in which select camera option to enable its functionality.

reboot Raspberry Pi.

Now we can access camera on Raspberry Pi and can capture images and videos using Pi
Camera on Raspberry Pi.

1. Lab Tasks:
In-Lab Tasks:

 Interfacing of LDR and Ultrasonic sensors following the lab instruction

Post-Lab Task:

 Interfacing PI-camera with Raspberry PI, capturing images, and store it to a drive
 Interface ultrasonic sensor with Raspberry Pi using Python coding (Complete the
Following Table)

S.No Time (Microseconds) Actual Distance Measured Error in


(inches/cm) Distance distance
(inches/cm)

You might also like