0% found this document useful (0 votes)
29 views88 pages

Iot Lab Manual For Print

The document is a lab manual for a B.Tech first-year course on the Internet of Things (IoT) at CMR College of Engineering & Technology. It outlines the objectives, outcomes, and a list of experiments designed to teach students about IoT concepts, Python programming, and Raspberry Pi applications. Additionally, it covers the definition, history, architecture, enabling technologies, and fundamental characteristics of IoT.

Uploaded by

nishmabhaskarani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views88 pages

Iot Lab Manual For Print

The document is a lab manual for a B.Tech first-year course on the Internet of Things (IoT) at CMR College of Engineering & Technology. It outlines the objectives, outcomes, and a list of experiments designed to teach students about IoT concepts, Python programming, and Raspberry Pi applications. Additionally, it covers the definition, history, architecture, enabling technologies, and fundamental characteristics of IoT.

Uploaded by

nishmabhaskarani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 88

Lab Manual

INTERNET OF THINGS

B.Tech- I Year
CMR COLLEGE OF ENGINEERING & TECHNOLOGY
(UGC AUTONOMOUS COLLEGE, ACCREDITED BY NAAC WITH “A” GRADE)

KANDLAKOYA, MEDCHAL ROAD, HYDERABAD

Lab Manual

INTERNET OF THINGS

B.Tech- I Year

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CMR COLLEGE OF ENGINEERING & TECHNOLOGY

KANDLAKOYA, MEDCHAL ROAD, HYDERABAD


OBJECTIVES:
1.To assess the vision and introduction of IoT.

2. To Understand IoT Market perspective.

3. To Implement Data and Knowledge Management and use of Devices in IoT Technology.

4. To Understand State of the Art - IoT Architecture.

5. To classify Real World IoT Design Constraints, Industrial Automation in IoT.


OUTCOMES:
At the end of the course the student will be able to

1. Identify and differentiate various components used in IoT Architecture.

2. Write & execute programs in python programming language.

3. Use python programming language to interface with raspberry.

4. Demonstrate the various real time applications using Raspberry Pi.

5. Create and deploy mobile applications using android.


LIST OF EXPERIMENTS
S.NO NAME OF THE EXPERIMENT
1 Introduction to IoT
Definition of IoT
 History of IoT
 IoT Architecture
 Enabling Technologies for IoT
 Fundamental characteristics of IoT
 Benefits and Applications of IoT
 Introduction to Basic Components
2 Programming in python
Introduction to Python
 Python Installation
 Understanding Python Basics
 Using Arithmetic in your programs
 Learning about Loops
3 Platform Based Development – Raspberry Pi
Introduction to Raspberry Pi
Why Raspberry Pi?
 Setting up the Raspberry Pi
 Python on Raspberry Pi
4
Experiment 1: Your First Circuit – To Blink an LED (Light Emitting Diode)
Experiment 2: To Blink an RGB LED
Experiment 3: To read the temperature and display the same in serial monitor. (use
LM35 Temperature sensor)
Experiment 4: To make an LED glow when controller detects a button pressed.
5 Experiment 5: To control an LED according to the range of analog input sensed using
photo resistor. (use Light Dependent Resistor(LDR)
Experiment 6: To interface the Liquid Crystal Display (LCD) with the Raspberry Pi to
display the characters on the LCD.
6 Experiment7: To interface the Ultrasonic Sensor with the Raspberry Pi to determine
the distance of an object from the sensor.
Experiment8: To interface the Infrared sensor with the Raspberry Pi to sense the path
is clear/indicate the presence of any obstacles
7 Introduction to Android
Explain the structure of Android App
. Create Hello World application with Android.
 Create Application to change the Background Color and Background Image
 Explain simple User interface components in Android and
 create simple Application
9 Create an application that display color or image as background when selected the
radio buttons or checkboxes.
 Create an Application to perform addition, Subtraction, multiplication, division.
10 Explain what activity, intent and its functions is.
 Create an application with Android intent.
11 Create a simple android application with the following event handlers.
On Click
 On Key Down
 On Focus changed
12 Explain about Toast, Create Application with User defined
 Toast Notifications
 Create login page by using login activity
WEEK 1

DEFINITION OF IOT:
The Internet of Things (IoT) is a network comprised of physical objects capable of gathering and
sharing electronic information

(OR)

The internet of things (IoT) is a computing concept that describes the idea of everyday physical
objects being connected to the internet and being able to identify themselves to other devices

HISTORY OF IOT:

The term Internet of Things is 16 years old. But the actual idea of connected devices had been
around longer, at least since the 70s. Back then, the idea was often called “embedded internet” or
“pervasive computing”.
Figure1. Internet of things

Figure2. Kevin Ashton, Inventor of the Internet of Things

The term “Internet of Things” was coined by Kevin Ashton in 1999 during his work at Procter &
Gamble. Ashton who was working in supply chain optimization, wanted to attract senior
management’s attention to a new exciting technology called RFID. Because the internet was the
hottest new trend in 1999 and because it somehow made sense, he called his presentation “Internet
of Things”. Even though Kevin grabbed the interest of some P&G executives, the term Internet of
Things did not get widespread attention for the next 10 years.

IOT ARCHITECTURE:
IOT architecture consists of different layers of technologies supporting IOT. It serves to illustrate
how various technologies relate to each other and to communicate the scalability, modularity and
configuration of IOT deployments in different scenarios
Figure3.IoTArchitecture

ENABLING TECHNOLOGIES FOR IOT:

Enabling technologies for the Internet of Things are considered in and can be grouped into
three categories:
1. Technologies that enable “things” to acquire contextual information,
2. Technologies that enable “things” to process contextual information, and
3. Technologies to improve security and privacy.

FUNDAMENTAL CHARACTERISTICS OF IOT:


There are 7 crucial Internet of Things characteristics:
Intelligence

Connectivity

Dynamic Nature

Enormous scale

Sensing

Heterogeneity

Security

BENEFITS OF IOT:

1. Data Management: Using devices we collect lots of raw data. These data are filtered
and managed by the IOT systems to produce an informative data. IOT reduces the
overall complexity of data management.

2. Good Decision Making: More informative data will help you to take right decision.
Calculated charts and reports generated by the IOT systems will help you to take good
decisions for your businesses.

3. Tracking and Safety: Using IOT system we can track and monitor all the objects
functionalities and their outputs. For safety of life we can track the quality and
expiration date of the products before its consumption.
4. Save Time & Money: IOT system perform task rapidly and doesn't requires human
which makes these devices more cost effective and fast

INTRODUCTION TO BASIC COMPONENTS:

1. Jumper wires – Jumper wires/cables or simply jumpers are available in various colours with
male-male, female-female or male-female connectors at the two ends, and are used for
interconnecting components on the breadboard or Arduino board.

Figure 4. Types of jumper wires


2. LEDs (Light Emitting Diodes),

LEDs consume very low power and so are long-lasting, with little energy wasted in heat. They
are used in flashlights, on front of appliances like TV (to indicate condition, like green for on,
red for standby, etc.).

Figure.5 Types of LEDs

3. Resistors: These are color-coded (with bands or stripes), and used to control the voltages
and currents in the circuit, e.g., to limit current in LEDs to set light intensity and avoid
damaging the LEDs. Note that unlike an LED, a resistor is reverse (i.e., polarity does not
matter).

Figure 6 Color Coding


4. Potentiometer: A potentiometer – also called a pot – is a variable resistor whose value can
be varied from zero to a fixed (final) value. By varying the resistor, we can vary audio
volume (in radio), speed (in fan regulator), light (in dimmer switch), etc.

Figure7. Potentiometer

5. Diode: A diode is an electronic device with two terminals (wires). It lets current flow in one
direction only (from positive or anode to negative or cathode), and acts like a gate or switch. An
LED is a special type of diode, where reversing the connection will damage the device. Signal
diode handles low currents, whereas power diodes are used with large currents/voltages.

Figure8. Diode

6. Photoresistor: Also called light-dependent resistor (LDR) or photocell, it is a light-controlled


variable resistor, i.e., its resistance changes with the intensity of light to which it is exposed.
Figure9 Photoresistor (LDR)

7. Buzzer: It is a piezo element, and produces a sound of a specified tone or frequency. It can also
be used to sense or detect vibrations (e.g., knock or tap).

Figure10 Buzzer

8. Temperature Sensor: When the temperature sensor is connected to a power supply, it produces
a voltage corresponding to the ambient temperature. By reading this voltage with an Arduino, we
can determine the temperature and record it in the computer, etc.

Figure11. LM35
9. DC Motor: DC motors are used in toys, RC cars, robots, and many other situations. By
controlling the voltage given to a motor using the Arduino, we can control the motion (angle
or speed) of the platform (e.g., robot manipulator or mobile robot) to which the motor is
attached.

Figure12. DC Motor

10. Push Button: Push buttons are switches which are used to turn on and off devices like motors,
LEDs, and so on.

Figure13. Push Button

11. RC Servo: RC (for radio control) servos are motors used in toy cars, RC planes and boats (to
control fins), etc, generally with less than one full rotation (whereas DC motors rotate
continuously).
Figure14. RC Servo

12. Relays: A relay is a switch that is turned ON and OFF by an electrical signal (e.g., sent
from Arduino). Typically, it used to turn on or off large-current devices (e.g., motors).

Figure15. Relay

13. Breadboard: A breadboard is used to build and test electronic circuits. No soldering is required
so we can change connections and replace components easily. Parts will be available for re-
use afterwards aft er successful testing.
Week 2
2.1. INTRODUCTION TO PYTHON:

2.1.1. What is Python?

 Python is an interpreted, interactive, object-oriented programming language.

 Python is a high-level general-purpose programming language

 Python is an easy to learn, powerful programming language.

 It incorporates modules, exceptions, dynamic typing, very high level dynamic data types,
and classes.

 Python combines remarkable power with very clear syntax.

 It has interfaces to many system calls and libraries, as well as to various window systems,
and is extensible in C or C++.

 It is also usable as an extension language for applications that need a programmable


interface.

 Finally, Python is portable: it runs on many Unix variants, on the Mac, and on Windows
2000 and later.

 Python is ideal language for scripting and rapid application development in many areas on
most platforms.

The Python Software Foundation is an independent non-profit organization that holds the copyright
on Python versions 2.1 and newer. The PSF’s mission is to advance open source technology related
to the Python programming language and to publicize the use of Python. The PSF’s home page is
athttps://www.python.org/psf/. You can do anything you want with the source.

The name "Python" was adopted from the same series "Monty Python's Flying Circus".
2.2. PYTHON INSTALLATION:

Downloading steps:

1. Go to: https://www.python.org/downloads/

The following page will appear in your browser.

2. Click the Download Python 3.6.2 button.

The file named python-3.6.2.exe should start downloading into your standard download
folder. This file is about 30 Mb so it might take a while to download fully if you are on a
slow internet connection (it took me about 10 seconds over a cable modem). The file
appears as an exe file.

3. Move this file to a more permanent location, so that you can install Python (and reinstall it
easily later, if necessary).

4 Double-click the icon labeling the file python-3.6.2.exe

5 An Open File - Security Warning pop-up window will appear.


4. Click Run.

A Python 3.6.2 (32-bit) Setup pop-up window will appear.

Ensure that the Install launcher for all users (recommended) and the Add Python 3.6 to
PATH checkboxes at the bottom are checked.

If the Python Installer finds an earlier version of Python installed on your computer, the Install
Now message will instead appear as Upgrade Now (and the checkboxes will not appear).

5. Highlight the Install Now (or Upgrade Now) message, and then click it.

A User Account Conrol pop-up window will appear, posing the question

Do you want to allow the following program to make changes to this computer?
6. Click the Yes button.

A new Python 3.6.2 (32-bit) Setup pop-up window will appear with a Setup Progress message
and a progress bar.

During installation, it will show the various components it is installing and move the progress bar
towards completion. Soon, a new Python 3.6.2 (32-bit) Setup pop-up window will appear with
a Setup was successfuly message.
7. Click the Close button.

Python should now be installed.

2.2. Understanding Python Basics:

Let's write our first Python program, "Hello, World!". It's a simple program that prints Hello
World!

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
l)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World");
Hello, World
>>>
Example programs:
1. Program to Add Two Numbers
Line1: # Add two numbers

Line2: num1 = 10

Line3: num2 = 20

Line4: sum = num1+num2

Line5: print(sum)
The above program works like this:

Line 1: # Add two numbers

Any line starting with # in Python programming is a comment.

Comments are used in programming to describe the purpose of the code. This helps you as well as
other programmers to understand the intent of the code. Comments are completely ignored by
compilers and interpreters.

Line 2: num1 = 10

Here, num1 is a variable. You can store a value in a variable. Here, 10 is stored in this variable.

Line 3: num2 = 20

Similarly, 20 is stored in num2 variable.

Line 4: sum = num1+num2

The variables num1 and num2 are added using + operator. The result of addition is then stored in
another variable sum.

Line 5: print(sum)

The print() function prints the output to the screen. In our case, it prints 30 on the screen.

Python Keywords:

Keywords are the reserved words in Python.

In Python, keywords are case sensitive.

There are 33 keywords in Python 3.3. All the keywords except True, False and None are in
lowercase and they must be written as it is.
False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

Types of Operator :
Python language supports the following types of operators.

 Arithmetic Operators

 Comparison (Relational) Operators

 Assignment Operators

 Logical Operators

 Bitwise Operators

 Membership Operators

 Identity Operators

Python - Decision Making :


Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is TRUE
or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages −

Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.

Python programming language provides following types of decision making statements. Click the
following links to check their detail.

S.No. Statement & Description

1 if statements: An if statement consists of a boolean expression followed by one or more


statements.

2 if...else statement: An if statement can be followed by an optional else statement, which


executes when the boolean expression is FALSE.

3 nested if statements

You can use one if or else if statement inside another if or else if statement(s).

If the suite of an if clause consists only of a single line, it may go on the same line as the header
statement.
Here is an example of a one-line if clause.

var = 100

if ( var == 100 ) : print "Value of expression is 100"

print "Good bye!"

When the above code is executed, it produces the following result −

Value of expression is 100


Good bye!

2.4. Learning about Loops :

Loop: A loop statement allows us to execute a statement or group of statements multiple times.
The following diagram illustrates a loop statement:

Python programming language provides following types of loops to handle looping requirements.

Sr.No Loop Type & Description


.

1 while loop

Repeats a statement or group of statements while a given condition is TRUE. It tests the
condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
3 nested loops

You can use one or more loop inside any another while, for or do..while loop.

1. Python while Loop Statements:


A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is −

while expression:
statement(s)

Flow Diagram

Loop Control Statements:


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements. Click the following links to check their detail.

Sr.No. Control Statement & Description


1 break statement

Terminates the loop statement and transfers execution to the statement immediately
following the loop.

2 continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

1.break statement
It terminates the current loop and resumes execution at the next statement, just like the
traditional break statement in C.

Syntax
The syntax for a break statement in Python is as follows −

Break

Flow Diagram
2. continue statement
It returns the control to the beginning of the while loop.. The continue statement rejects all the
remaining statements in the current iteration of the loop and moves the control back to the top of
the loop.

The continue statement can be used in both while and for loops.

Syntax
continue

Flow Diagram
Week 3
Platform Based Development – Raspberry Pi

3.1. Introduction to Raspberry Pi


• The Raspberry Pi is a credit-card sized computer

• Its is a fully featured micro-computer squashed onto a circuit board.


• Measuring approximately9cm x 5.5cm

3.2. Why Raspberry Pi?

The Raspberry Pi is a credit-card-sized computer . It's available anywhere in the world,


and can function as a proper desktop computer or can be used to build smart devices.
• Ultra low-cost (Model A $25, Model B $35)
• Ultra low-power ~1W
• Credit-card sized, fanless, instant start-up
• Complete easy-to-program computer

3.3. Setting up the Raspberry Pi :

Download NOOBS onto the microSD card


1. Download the ZIP file of NOOBS Version 2.4.5. It is a large file and will take a while to
complete.

2. Double-click on the NOOBS file from the Downloads folder in your Dock to open it

3. Select the first file inside the NOOBS folder.


4. Scroll down and Shift + left-click on the last file in the NOOBS folder.
5. Drag and drop all selected NOOBS files into the SD card icon on your desktop. You don't
have to open the SD card drive.

6. Right-click on the SD card icon.


7. Select "Eject [SD Card Name]".

8. Remove the card reader from your computer.


9. Remove the microSD card from the card reader.

Set up your Raspberry Pi :

 Insert the microSD card into the card slot on the underside of the Raspberry Pi.

 Plug the USB keyboard into one of the USB ports.


 Plug the USB mouse into one of the USB ports

 Alternatively, connect the Bluetooth adapter into one of the USB ports.

 Turn on your monitor or TV set and make sure it is set to the proper input (e.g. HDMI 1 or
Component)
 Plug the HDMI or video component cable into the monitor or TV set.
 Connect the other end of the cable into the Raspberry Pi.

 Connect an ethernet cable to your router if you plan to connect to the Internet.
 Connect the other end of the cable to your Raspberry Pi.

 Alternately, connect the Wi-Fi adapter to the Raspberry Pi.

 Connect the power supply to the Raspberry Pi.

 Plug the power supply into the power outlet. This will turn on and boot up Raspberry Pi. A
power indicator light will begin to glow, letting you know that you are connected,
3.4. Platform Based Development-Raspberry Pi
Week 4
Experiment 1

AIM: To Blink an LED (Light Emitting Diode) Using Raspberry pi 3

Components Required:

Connecting pins

1KΩresistor

LED

Bread Board

Circuit Explanation:

As shown in the circuit diagram we are going to connect an LED between PIN8 and PIN39
(GROUND) so to limit the current we are connecting a 1KΩ resistor in series with the LED.
Working Explanation:

Turn ON your PI and go to the desktop.


1. On the desktop, go the Start Menu and choose for the PYTHON 3, as shown in figure below.

2. After that, PYHON will run and you will see a window as shown in below figure.

3. After that, click on New File in File Menu, You will see a new Window open
4. Save this file as blinkpy on the desktop

5. After that write the program for blinkpy as given below and execute the program by clicking on
“RUN” on ‘DEBUG’ option.

If the program has no errors in it, you will see a “>>>”, which means the program is executed
successfully. By this time you should see the LED blinking three times. If there were any errors in
the program, the execution tells to correct it. Once the error is corrected execute the program again.
Code Explanation:

In the Python program, first we have imported two packages RPi.GPIO and Time. The
package RPi.GPIO will help us in controlling the GPIO Pins of the Raspberry Pi.

The first important function of the RPi.GPIO Module is the setmode(). Using GPIO.setmode(), we
can select either GPIO Numbering of the Pins or Physical Numbering. By
using GPIO.setmode(GPIO.BOARD), we are selecting the Physical Numbering Scheme.

NOTE: For GPIO Numbering, you can use GPIO.setmode(GPIO.BCM).

The next function is the setup(pin,mode). This function will allow us to set the pin as either input
(GPIO.IN) or as output (GPIO.OUT). In the program, I have set the ledPin as output by
using GPIO.setup(ledPin, GPIO.OUT).After setting the LED Pin as OUTPUT, now we need to
set the state of this OUTPUT i.e. HIGH (GPIO.HIGH) or LOW (GPIO.LOW). For this, we need to
use the function output(pin, state). So, in our program, we need to use GPIO.output(ledPin,
GPIO.HIGH) for turning ON the LED and GPIO.output(ledPin, GPIO.LOW) for turning it
OFF.

Code:

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)
while True:
GPIO.output(8,True)
print(" LED IS ON")
time.sleep(3)

GPIO.output(8,False)
print("LED IS OFF")
time.sleep(3)

Output:

LED IS ON

LED IS OFF
Experiment 2

AIM: To Blink an RGB LED Using Raspberry PI 3

Components Required:

1. Raspberry Pi 3
2. Breadboard

3. One RGB Led 4

4. 3 resistors

5. Jumper wires

RGB Led Explanation:

The LED is the abbreviation of light emitting diode. The LED has two electrodes, a positive
electrode and a negative electrode. It lights up only when a forward current passes. The RGB LEDs
consist of three LEDs in different colors:red, green and blue. These three colored LEDs are capable
of producing any color. Tri-color LEDs with red, green, and blue emitters, in general use a four-
wire connection with one common lead (anode or cathode).
The symbol for common anode RGB LED

Circuit Explanation:

The longest pin is the common anode of the three LEDs. The pin is connected to the +3.3V pin of
the Raspberry Pi, and the rest pins are connected to pin 8, pin 10, and pin 12 of Raspberry Pi with a
current limiting resistor between(220Ω). Using these pins, we can control the color of the RGB
LED by 3-channel PWM signal.
Code Explanation:

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
while True:
GPIO.output(8,True)
print("RED ON")
time.sleep(3)

GPIO.output(8,False)
print("RED OFF")
time.sleep(3)

GPIO.output(10,True)
print("GREEN ON")
time.sleep(3)

GPIO.output(10,False)
print("GREEN OFF")
time.sleep(3)

GPIO.output(12,True)
print("BLUE ON")
time.sleep(3)

GPIO.output(12,False)
print("BLUE OFF")
time.sleep(3)

OUTPUT:

RED ON

RED OFF

GREEN ON

GREEN OFF

BLUE ON
BLUE OFF

Week5

Experiment-3

AIM: IR sensor Using Raspberry pi 3

Components Required:

1. Raspberry Pi 3 (any model)


2. IR sensor Module
3. Green and Red LED lights
4. Breadboard
5. Connecting wires

IR Sensor Module:

IR sensors (Infrared sensor) are modules which detect the presence of objects before them. If the
object is present it give 3.3V as output and if it is not present it gives 0 volt. This is made possible
by using a pair of IR pair (transmitter and receiver), the transmitter (IR LED) will emit an IR ray
which will get reflected if there is a object present before it. This IR ray will be received back by
the receiver.

Circuit Diagram and Explanation:

The circuit diagram for connecting Raspberry Pi with IR sensor is shown below. As you can see the
circuit diagram is very simple. We have directly powered the IR module from the 5V and Ground
Pin of Raspberry Pi. The output pin of the IR module is connected to the GPIO14. We have also
used two LED (Green and Red) to indicate the status of the object. These two LEDs are connected
to GPIO3 and GPIO2 respectively.
Working:

Once you have created your python code, execute it using the run command. If the program is
executed without any errors you should get the following screen.

Code:

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.IN)
while True:
if(GPIO.input(8)):
print("some one is trying")
time.sleep(2)

Output:

some one is trying…..


Experiment-4

AIM: Counting the number Persons entering the room using IR Sensor

Components Required:

1. Raspberry Pi 3 (any model)


2. IR sensor Module
3. Green and Red LED lights
4. Breadboard
5. Connecting wires

Code:

import RPi.GPIO as GPIO


import time
count=0
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.IN)
while True:
if(GPIO.input(8)):
count=count+1
print(count)
time.sleep(3)

Output:
First person is entered
Second person is entered
.
.
.
Experiment-5

AIM: To make an LED glow when controller detects a button pressed.

Components Required:

Push Button

Bread Board

Led

Raspberry pi model 3

Jumper Wires(M-F)

Resistor

Working Explanation:

A Push Button is a type of switch work on a simple mechanism called “Push-to-make”. Initially,
it remains in off state or normally open state but when it is pressed, it allows the current to pass
through it or we can say it makes the circuit when pressed.
CODE:

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

Led=8

Button=10

GPIO.setup(led,GPIO.OUT)

GPIO.setup(button, GPIO.IN,pull_up_down= GPIO.PUD_UP)

while True:

bs=GPIO.input(button)

print("led off")

while bs==1:

GPIO.output(led, GPIO.LOW)

bs=GPIO.input(button)

print("led on")

while bs==0:

GPIO.output(led, GPIO.HIGH)

bs=GPIO.input(button)

OUTPUT:

LED OFF

LED ON
Week 6

Experiment 6

Aim: To interface the Ultrasonic Sensor with the Raspberry Pi3 to determine the distance of an
object from the sensor

Components Required:

HC-SR04

1kΩ Resistor

2kΩ Resistor

Jumper Wires

Circuit Explanation:

There are four pins on the ultrasound module that are connected to the Raspberry:
 VCC to Pin 2 (VCC)
 GND to Pin 6 (GND)
 TRIG to Pin 8
 ECHO to Pin 10
 An ultrasonic distance sensor sends out pulses of ultrasound which are inaudible to humans,
and detects the echo that is sent back when the sound bounces off a nearby object. It then uses
the speed of sound to calculate the distance from the object.

Code:

#Libraries
import RPi.GPIO as GPIO
import time

#GPIO Mode (BOARD / BCM)


GPIO.setmode(GPIO.BOARD)

#set GPIO Pins


GPIO_TRIGGER=8
GPIO_ECHO=10

#set GPIO direction (IN / OUT)


GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)

def distance():
# set Trigger to HIGH
GPIO.output(GPIO_TRIGGER, True)

# set Trigger after 0.01ms to LOW


time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)

StartTime = time.time()
StopTime = time.time()

# save StartTime
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()

# save time of arrival


while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()

# time difference between start and arrival


TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2

return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
time.sleep(1)

# Reset by pressing CTRL + C


except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()

OUTPUT:
Experiment 7

AIM: To control an LED according to the range of analog input sensed using photo resistor. (use
Light Dependant Resistor(LDR ))

Components Required:

LDR

1kΩ Resistor

Jumper Wires

Working Explanation:

The light dependent resistor or also known as the LDR sensor is the most important piece of
equipment in our circuit (obviously). Without it, we wouldn’t be able to detect whether it is dark or
light.

In the light, this sensor will have a resistance of only a few hundred ohms while in the dark, it can
have a resistance of several megohms.

To get the light sensor circuit built correctly follow the steps below or check out the circuit diagram
right underneath the steps. In the following steps, I am referring to the physical numbers of the pins
(Logical order).
1. First, connect pin #1 (3v3) to the positive rail on the breadboard.

2. Next, connect pin #7 on the breadboard.

3. Now place the LDR sensor onto the board and have a wire go from one end to the positive rail.

4. On the other side of the LDR sensor place a wire leading back to the Raspberry Pi. Hook this to
pin #7.

CODE:

import time
from gpioZero import LightSensor
ldr= LightSensor(4)
while True:
print(ldr.value)
time.sleep(1)

OUTPUT:

9.8372354212

9.7372353471
ANDROID
WEEK 7

Configuring Android Application Development Environment

What is Android SDK ?

 The Android SDK includes a complete set of development tools. It includes a debugger,
libraries, a handset emulator.
 Software written in Java can be compiled to be executed in the Dalvik virtual machine,
which is a specialized VM implementation designed for mobile device use.
Required Software to Install Android ?
1. JDK6 Version
2. Android SDK for Windows (if you have Windows OS)
3. Eclipse IDE

Installing JDK6 (Java Development Kit)


The latest version of jdk is 6, at the time of writing my java tutorial. We can
download thejdk from:
http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Step 1. Once we download the exe file we can now install it. Just follow what
mentioned below: To install the jdk, double click on the downloaded exe file (jdk-6u1-
windows-i586-p.exe) Double Click the icon of downloaded exe from the downloaded
location.

You will see jdk 6 update 1 window as shown below.


Step 2: Now a "License Agreement" window opens. Just read the agreement and
click "Accept" button to accept and go further.

Step 3: Now a "Custom Setup" window opens.

Step 4: Click on "Change" button to choose the installation directory. Here it is

"C:\Program Files\ Java\jdk1.6.0_01". Now click on "OK" button.


Clicking the "OK" button starts the installation. It is shown in the following figure.

Step 5: Next window asks to install Runtime Environment.

Click the "Change" button to choose the installation directory of Runtime Environment. We prefer
not to change it. So click "OK" button.
Step 6: Click "OK" button starts the installation.

Step 7: Now "Complete" window appears indicating that installation of jdk 1.6 has completed
successfully. Click "Finish" button to exit from the installation process.

Step 8: The above installation will create two folders "jdk1.6.0_01" and

"jre1.6.0_01" in "C:\ Program Files\ java" folder.


Installing Android SDK Tools &API ?

Step-1) Download Android SDK from http://developer.android.com/sdk/index.html,


as I shown below.

We will get the downloaded exe file , as


Step-2) Double click on SDK Installer.exe file to install

Click on Next button


Click on Next button

Step-3) Ensure Destination Folder, and click on Next button


Click on Install Button

Click on Next button


Click on Finish button

Step-4)Installing Android SDK tools and Android API Levels.

Ensure the following installed Android SDK location in file system, and click on SDK
manager from the android-sdk directory.

It opens the following window,

Step-5) This step is very important , from the following Window, select tools, API Levels
like API15, API 10, ..etc , and also select Extras-> Google USB Driver package for USB
Connections with real device.
Click on Install XX Packages button.

Be patient Installation will start will take more time…

Installing Eclipse & Configuring Android Plugin for Ec

Configuring Android Tools for Eclipse:

Step-1) Download eclipse software from www.eclipse.org\downloadslocation.


Step-2) Confirm the downloaded .zip file location, and decompress using either winzip
(or) winrar software.

Step-3) Open Eclipse.exe file, from the file system location.

Step-4) Configuring the ADT Plugin :

 Start Eclipse, then select Help>Install New Software.


 Click Add, in the top-right corner.
 In the Add Repository dialog that appears, enter "ADT Plugin" for the
Name and the following URL for the
Location: https://dl-ssl.google.com/android/eclipse/

 Click OK.
If you have trouble for the plugin, try using "http" in the Location URL, instead of "https" (https is
preferred for security reasons).
In the Available Software dialog, select the checkbox next to Developer Tools and click
Next.
In the next window, we'll see a list of the tools to be downloaded. Click Next.

Click on “Next” button

 Read and accept the license agreements, then click Finish.


 If you get a security warning saying that the authenticity or validity of the
software can't be established, click OK.
 When the installation completes, restart Eclip
Configuring the ADT Plugin for Eclipse :

After we've installed ADT and restarted Eclipse, we must specify the location of our
Android SDK directory:

1. Select Window>Preferences... to open the Preferences panel (on Windows OS X,


select Eclipse>Preferences).

2. Select Android from the left panel.


You may see a dialog asking whether you want to send usage statistics to Google. If
so, make your choice and click Proceed.

3. For the SDK Location in the main panel, click Browse... and locate your downloaded
Android SDK directory (such as android-sdk-windows).
4. Click Apply, thenOK.
Note :“With this your Android Installation part is completed, we can configure Android
plugin for other IDE’s like Netbeans, IntelliJ IDE also. “

What is AVD ? How to Configure AVD?

 AVD, stands Android Virtual Device, AVD’s are used to start emulator. When we
launch the emulator, we should specify the AVD configuration that we want to
load..
 Before Configuring AVD, first confirm SDK tools and API levels are installed or not !
 Then select AVD Manager from Window -> AVD Manager.
 Click New... button, name your new AVD, select API target, SD Card size, then click
Create AVD button.

 Click Start... button to start your new AVD. It will takes a few minutes for
creating new AVD.
What is Emulator ? How to Start ?

 The emulator lets you prototype, develop and test Android applications without using a
physical device.

 To use the emulator, first we must create AVD configuration, Remember, If project
is used with Android API15 level , then we should use AVD API level also 15.

Every Emulator needs one AVD support, because the AVD configuration provides both software
and hardware support for Emulator, like it can use the services of the Android platform to invoke
other applications, access the network, play audio and video, store and retrieve data, notify the user,
and render graphical transitions and themes.

 The emulator also includes a variety of debug capabilities.


 The emulator provides dynamic binary translation of device machine code to the
OS and processor architecture of your development machine.
 The Android emulator contains all of the hardware and software features of a real
mobile device, except that it cannot place actual phone calls, can’t carry.
 Emulator provides a screen like as real device to display output of our testing
application, using this we can easily test our applications.
i) Create Hello World application with Android

1. Create Android Project

Select from the menu File --> New --> Other --> Android --> Android Application Project (say
'AndroidHello') and click Nextbutton.

2. Configure Project Settings

Enter Application, Project and Package Name. Select 'Minimum Required SDK' (lowest
version of Android that this app supports), 'Target SDK' (highest version of Android with which
this application has been tested), 'Compile With' (platform version against which this
application will be compiled with) and 'Theme' (Android UI style) from the corresponding
theme. To make it simple you can leave the dropdown value as it is. Click Next button
Click Next button

Choose your App icon and configure as per your requirement.

4. Create Activity

Choose an activity template (say 'Blank Activity') and click Next button.
Enter 'Activity Name' (say 'Hello Activity') and click Finish button.

Finally click Finish button.

5 Overall Project Structure

Android project will be created with some default files as shown below
6. Code

activity_hello.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".HelloActivity" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

</RelativeLayout>
File : HelloActivity.java

package com.srccodes.android;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class HelloActivity extends Activity {


TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
tv=( TextView)findviewbyId(id.textview1);
tv.settext(“HelloWorld”);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_hello, menu);
return true;
}
}

OUTPUT:
Week 8

 Create Application to change the Background Color and Background Image


 Explain simple User interface components in Android and create simple Application

Code

activity_hello.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:Background="#0000FF"

tools:context=".HelloActivity" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

</RelativeLayout>
File : HelloActivity.java

package com.srccodes.android;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class HelloActivity extends Activity {


TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
tv=( TextView)findviewbyId(id.textview1);
tv.settext(“HelloWorld”);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_hello, menu);
return true;
}
}

OUTPUT:
Week 9
 Create an application that display color or image as background when selected the radio
buttons or checkboxes
 Create an Application to perform addition, Subtraction, multiplication, division.

Code
activity_hello.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:id="@+id/txtView1"/>
<RadioButton
android:id="@+id/ RadioButton1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text=" RadioButton "
android:textcolor=”#000000”
android:textsize=”25sp”/>
<CheckBox
android:id="@+id/ CheckBox1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text=" CheckBox "
android:textcolor=”#FF0000”
android:textsize=”25sp”/>

</RelativeLayout>
File : HelloActivity.java

package com.srccodes.android;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class HelloActivity extends Activity {
TextView tv;
RadioButton rb;
CheckBox cb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello);
tv=( TextView)findviewbyId(id.textview1);
tv.settext(“HelloWorld”);
rb=( radiobutton)findviewbyId(id. radiobutton1);
cb=( checkbox)findviewbyId(id. checkbox1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_hello, menu);
return true;
}
}

OUTPUT:
Week 10
i) Create an application with Android intent.

Code
activity_Button.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="@+id/ Button1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text=" click "
android:textsize=”25sp”/>

</RelativeLayout>

File : Button Activity.java

package com.example.intent12;

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class MainActivity extends Activity {

Button bt;

@Override

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

bt=(Button)findViewById(R.id.button1);

bt.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {

// TODO Auto-generated method stub

Intent in= new Intent(MainActivity.this,MainActivity1.class);

startActivity(in);

});

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_main, menu)

return true;

}}

OUTPUT:
Week 11
Create a simple android application with the following event handlers.
 On Click

Code
Hello activity_.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".HelloActivity" >

<TextView

android:id="@+id/ Textview1 "

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

</RelativeLayout>

File :HelloActivity.java
package com.example.onclick12;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


Button bt;
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.button1);
Toast.makeText(getApplicationContext(), "tulsi", 1000).show();
tv=(TextView)findViewById(R.id.textView1);
tv.setText("ur pressed 1");

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

OUTPUT:

ii) On Key Down


File : Edittext Activity.java

package com.example.onkeydown;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {


// TODO Auto-generated method stub
switch (keyCode) {
case KeyEvent.KEYCODE_0:
Toast.makeText(getApplicationContext(), "U Clicked 0",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_1:
Toast.makeText(getApplicationContext(), "U Clicked 1",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_2:
Toast.makeText(getApplicationContext(), "U Clicked 2",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_3:
Toast.makeText(getApplicationContext(), "U Clicked 3",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_4:
Toast.makeText(getApplicationContext(), "U Clicked 4",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_5:
Toast.makeText(getApplicationContext(), "U Clicked 5",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_A:
Toast.makeText(getApplicationContext(), "U Clicked A",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_Y:
Toast.makeText(getApplicationContext(), "U Clicked Y",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_U:
Toast.makeText(getApplicationContext(), "U Clicked U",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_CAPS_LOCK:
Toast.makeText(getApplicationContext(), "U Clicked Caps Lock",
Toast.LENGTH_LONG).show();
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
Toast.makeText(getApplicationContext(), "U Clicked Shift Left",
Toast.LENGTH_LONG).show();
return true;
default:
break;
}
//return super.onKeyDown(keyCode, event);
return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

iii) On Focus changed


Code
activity_Edittext .xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".HelloActivity" >

<Edittext

android:id="@+id/ EditText1 "

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

<Edittext

android:id="@+id/ EditText2 "

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello_world" />

</RelativeLayout>

File : Edittext Activity.java


package com.example.onfocus;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText ed,ed1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed=(EditText)findViewById(R.id.editText1);
ed1=(EditText)findViewById(R.id.editText2);
ed.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if(arg1)
Toast.makeText(getApplicationContext(), "ed has focus",
2000).show();
else
Toast.makeText(getApplicationContext(), "ed1 has not focus",
1000).show();
}
});

//ed1=(EditText)findViewById(R.id.editText2);
ed1.setOnFocusChangeListener(new OnFocusChangeListener() {

@Override
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
if(arg1)
Toast.makeText(getApplicationContext(), "edit text1 has focus", 2000).show();
else
Toast.makeText(getApplicationContext(), "edit text has not focus", 1000).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

OUTPUT:

Week 12

 Explain about Toast, Create Application with User defined Toast Notifications.
 Create login page by using login activity.

Android Toast Example

Andorid Toast can be used to display information for the short period of time. A toast
contains message to be displayed quickly and disappears after sometime.

The android.widget.Toast class is the subclass of java.lang.Object class.

You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.

Toast class

Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.

Methods of Toast class


The widely used methods of Toast class are given below.

Method Description

public static Toast makeText(Context context, makes the toast containing text and
CharSequence text, int duration) duration.

public void show() displays toast.

public void setMargin (float horizontalMargin, float changes the horizontal and vertical
verticalMargin) margin difference.

Code
activity_ Toast .xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".HelloActivity" >

<TextView

android:id="@+id/ Textview1 "

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:text="@string/hello" />

<Button
android:id="@+id/ Button1 "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text=" Toast "
android:textsize=”25sp”/>
</RelativeLayout>

File : Toast Activity.java

package com.example.toast3;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.Toast;

public class MainActivity extends Activity {

Button bt;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

bt=(Button) findViewById(R.id.button1);

bt.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View arg0) {


// TODO Auto-generated method stub

Toast.makeText(getApplicationContext(), "HELLO", 1000).show();

}) ;

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.activity_main, menu);

return true;

OUTPUT:

You might also like