0% found this document useful (0 votes)
13 views

2024-25 IoT Master Manual Copy

The document is an IoT lab manual for electronics and communications engineering students, detailing experiments involving Arduino boards and NODE MCU. It includes prerequisites, a list of experiments, and programming examples for controlling LEDs and sensors using Arduino. Additionally, it provides insights into the features and functionalities of the Arduino UNO, Arduino Mega 2560, and ESP8266 Node MCU, along with practical applications and circuit diagrams.

Uploaded by

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

2024-25 IoT Master Manual Copy

The document is an IoT lab manual for electronics and communications engineering students, detailing experiments involving Arduino boards and NODE MCU. It includes prerequisites, a list of experiments, and programming examples for controlling LEDs and sensors using Arduino. Additionally, it provides insights into the features and functionalities of the Arduino UNO, Arduino Mega 2560, and ESP8266 Node MCU, along with practical applications and circuit diagrams.

Uploaded by

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

Internet of Things

IoT- Lab Manual

R22- Regulation

Department of Electronics and Communications


Engineering

Vadlamudi, Guntur-522213

VFSTR (Deemed to be University) 1


Prerequisite knowledge: Basic knowledge of Computer hardware, Computer Programming
and Computer Networks

List of Experiments:
1. Familiarization of Arduino Boards and NODE MCU.
2. Blinking Two LEDs Using Arduino Mega 2560 with Delays
3. Interfacing of LED, Switch Using Development Boards
4. 2-Way Traffic Lights
5. Interfacing of Ultrasonic Sensor Using Exemplary Devices.
6. Interfacing of LDR Using Exemplary Devices.
7. Interfacing of IR/PIR Sensor Using Exemplary Devices.
8. Interfacing of Servo/DC motor Using Exemplary Devices.

Familiarization of Arduino UNO

The Arduino UNO is a popular microcontroller board used for building digital
devices and interactive objects that can sense and control the physical world.

Key Features of Arduino UNO


• Microcontroller: ATmega328P
• Overall Pins: 32 Pins Available
• Operating Voltage: 5V
• Input Voltage: 7-12V
• Digital I/O Pins: 14 (6 of which can be used as PWM outputs)
• Analog Input Pins: 6(A0-A5)
• Clock Speed: 16 MHz
• Memory: 32 KB flash memory, 2 KB SRAM, 1 KB EEPROM
• Communication Protocols: UART, SPI, I2C
Anatomy of the Board: The Arduino UNO has a USB connection, a power jack, an
ICSP header, and a reset button. It also includes a 16 MHz ceramic resonator and a
USB-to-serial converter1.

VFSTR (Deemed to be University) 2


Arduino IDE: The Integrated Development Environment (IDE) is used to write,
compile, and upload code to the board. It supports C/C++ programming languages.

LED Blinking Using Arduino


Aim: To control the built-in LED1 and LED2 using the Arduino Uno board on Pin 13
Required Components:
• Arduino Uno Board
• Bread Board
• LEDs
• Arduino IDE Software
• Connecting Wires
Block Diagram

Program:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
// turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW);
VFSTR (Deemed to be University) 3
// turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}

void setup() {
// Set Pin 13 as an output
pinMode(13, OUTPUT);
}
Program-2:
void loop() {
// Turn the LED on
digitalWrite(13, HIGH);
delay(1000); // Wait for 1 second
// Turn the LED off
digitalWrite(13, LOW);
delay(1000); // Wait for 1 second
}

Observations: The LED connected to Pin 13 will blink on and off every 1000 milli seconds.

Familiarization with Arduino Mega 2560


The Arduino Mega 2560 is a microcontroller board based on the ATmega2560. It offers more
I/O pins and memory compared to the Arduino Uno, making it suitable for more complex projects.
The core of the board is the ATmega2560 microcontroller, which handles the processing and control
tasks. A total of 54 Digital I/O Pins are available. It Can be configured as either input or output.

VFSTR (Deemed to be University) 4


1.16 Analog Pins (A0-A15): Used for reading analog signals (0-5V) and converting them into
digital values.
2. 15 PWM Output Pins Pins (3, 5, 6, 9, 10, 11, 12, 13, 44, 45, 46): Support PWM for simulating
analog output.
3. Serial Communication - 4 Hardware Serial Ports**: Serial0 (USB), Serial1, Serial2, Serial3 for
different serial communication needs. - **Pin 0 (RX) and Pin 1 (TX)**: Default Serial
Communication (USB to PC).
4. SPI Communication - Pins 50 (MISO), 51 (MOSI), 52 (SCK), 53 (SS): Used for SPI (Serial
Peripheral Interface) communication with peripherals.
5. I2C Communication- Pins 20 (SDA) and 21 (SCL): Used for I2C (Inter-Integrated Circuit)
communication.
6. Power Supply - 5V and 3.3V Pins: Provide regulated power to external components. - Vin Pin:
Allows powering the board with an external voltage source (7-12V recommended) - GND Pins:
Ground connections for circuits and components.
7. Reset Button - Resets the microcontroller**: Used to restart the program running on the Arduino.
8. LED Indicators- Built-in LEDs: Includes a power LED and an onboard LED connected to Pin 13
for basic testing and debugging.
9. USB-B Port: Used for programming the board and serial communication with the computer.
10. External Interrupts - Pins 2 and 3: Can be used for external interrupts to respond to specific
events or signals.
11. ICSP Header- 6-Pin Header: For in-circuit serial programming of the ATmega2560 chip.

Blinking Two LEDs Using Arduino Mega 2560 with Delays

Aim: To control the built-in LED1 and LED2 using the Arduino Uno board on Pin 13
Required Components:
• Arduino Mega2560
• Bread Board
• 2- LEDs
• Arduino IDE Software
• Connecting Wires (Male-Male Jumper Wires)
Circuit Diagram:

VFSTR (Deemed to be University) 5


Description:
LED Connections:
• Connect the anode (longer leg) of LED1 to Pin 8 on the Arduino Mega 2560.
• Connect the cathode (shorter leg) of LED1 to one end of a current-limiting resistor (220Ω to
1kΩ).
• Connect the other end of the resistor to the ground (GND) on the Arduino Mega 2560.
• Repeat the same for LED2, connecting it to Pin 9 and using a separate resistor.

Program:
// Define LED pins
const int ledPin1 = 8;
const int ledPin2 = 9;

void setup() {
// Initialize LED pins as outputs
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
}

void loop() {
// Turn LED1 on and LED2 off
digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, LOW);
delay(1000); // Wait for 1 second

// Turn LED1 off and LED2 on


digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, HIGH);

VFSTR (Deemed to be University) 6


delay(1000); // Wait for 1 second

// Turn both LEDs off


digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
delay(500); // Wait for 0.5 seconds

// Turn both LEDs on


digitalWrite(ledPin1, HIGH);
digitalWrite(ledPin2, HIGH);
delay(500); // Wait for 0.5 seconds
}

Observations:
• First, LED1 is turned on while LED2 is off. Both LEDs are controlled by setting the
respective pins HIGH or LOW.
• After a 1-second delay, LED1 is turned off and LED2 is turned on.
• Both LEDs are then turned off for 0.5 seconds, followed by turning both LEDs on for
another 0.5 seconds.

Familiarization of NODE MCU


Installing Arduino and downloading the ESP8266 Node MCU supported packages.
Familiarization of Arduino Programming.

To program the ESP8266, you'll need a plugin for the Arduino IDE, but it is easier to just add the
URL in the Arduino IDE:
1. Open the Arduino IDE.
2. Go to File > Preferences.
3. Paste the URL http://arduino.esp8266.com/stable/package_esp8266com_index.json into
the Additional Board Manager URLs field. (You can add multiple URLs, separating them with
commas.)
4. Go to Tools > Board > Board Manager and search for 'esp8266'.
5. Select the newest version and click install/ Update

Digital I/O

Just like with a regular Arduino, you can set the function of a pin using pinMode(pin,
Mode); where pin is the GPIO number*, and mode can be either INPUT, which is the default,
OUTPUT, or INPUT_PULLUP to enable the built-in pull-up resistors for GPIO 0-15. To enable the
pull-down resistor for GPIO16, you have to use INPUT_PULLDOWN_16.To address a NodeMCU
pin, e.g. pin 5, use D5: for instance: pinMode(D5, OUTPUT). To set an output pin high (3.3V) or low
(0V), use digitalWrite(pin, value); where pin is the digital pin, and value either 1 or 0 (or HIGH and
LOW).
To read an input, use digitalRead(pin). To enable PWM on a certain pin, use analogWrite(pin,
value); where pin is the digital pin, and value a number between 0 and 1023. You can change the
range (bit depth) of the PWM output by using analogWriteRange(new_range). The frequency can be
changed by using analogWriteFreq(new_frequency);. new_frequency should be between 100 and
1000Hz.

Analog input

VFSTR (Deemed to be University) 7


Just like on an Arduino, you can use analogRead(A0) to get the analog voltage on the analog
input. (0 = 0V, 1023 = 1.0V). The ESP can also use the ADC to measure the supply voltage (VCC).
To do this, include ADC_MODE(ADC_VCC); at the top of your sketch, and use ESP.getVcc(); to
actually get the voltage. If you use it to read the supply voltage, you can’t connect anything else to
the analog pin. Communication

Serial communication

To use UART0 (TX = GPIO1, RX = GPIO3), you can use the Serial object, just like on an Arduino:

Serial.begin(baud). To use the alternative pins (TX = GPIO15, RX = GPIO13), use Serial.swap() after
Serial.begin. To use UART1 (TX = GPIO2), use the Serial1 object. All Arduino Stream functions,
like read, write, print, println,... are supported as well.

I²C and SPI

You can just use the default Arduino library syntax, like you normally would.

Familiarization of ESP8266 Node MCU.

The ESP8266 is a System on a Chip (SoC), manufactured by the Chinese company


Espressif. It consists of a Tensilica L106 32-bit micro controller unit (MCU) and a Wi-Fi transceiver.
It has 11 GPIO pins* (General Purpose Input/Output pins), and an analog input as well. This means
that you can program it like any normal Arduino or other microcontroller. And on top of that, you get
Wi-Fi communication, so you can use it to connect to your Wi-Fi network, connect to the Internet,
host a web server with real web pages, let your smartphone connect to it, etc ... The possibilities are
endless! It's no wonder that this chip has become the most popular IOT device available.

There are many different modules available, standalone modules like the ESP-## series
by AI Thinker, or complete development boards like the NodeMCU DevKit or the WeMos D1.
VFSTR (Deemed to be University) 8
Different boards may have different pins broken out, have different Wi-Fi antennas, or a different
amount of flash memory on board.

Digital I/O

Just like a normal Arduino, the ESP8266 has digital input/output pins (I/O or GPIO,
General Purpose Input/Output pins). As the name implies, they can be used as digital inputs to read a
digital voltage, or as digital outputs to output either 0V (sink current) or 3.3V (source current).

Voltage and current restrictions

The ESP8266 is a 3.3V microcontroller, so its I/O operates at 3.3V as well. The pins are not 5V
tolerant, applying more than 3.6V on any pin will kill the chip.
The maximum current that can be drawn from a single GPIO pin is 12mA.

Usable pins

The ESP8266 has 17 GPIO pins (0-16), however, you can only use 11 of them, because 6 pins (GPIO
6 - 11) are used to connect the flash memory chip. This is the small 8-legged chip right next to the
ESP8266. If you try to use one of these pins, you might crash your program. GPIO 1 and 3 are used
as TX and RX of the hardware Serial port (UART), so in most cases, you can’t use them as normal
I/O while sending/receiving serial data. Internal pull-up/-down resistors
GPIO 0-15 all have a built-in pull-up resistor, just like in an Arduino. GPIO16 has a built-in pull-
down resistor.

PWM

Unlike most Atmel chips (Arduino), the ESP8266 doesn’t support hardware PWM, however, software
PWM is supported on all digital pins. The default PWM range is 10-bits @ 1kHz, but this can be
changed (up to >14-bit@1kHz).

Analog input

The ESP8266 has a single analog input, with an input range of 0 - 1.0V. If you supply 3.3V, for
example, you will damage the chip. Some boards like the NodeMCU have an on-board resistive
voltage divider, to get an easier 0 - 3.3V range. You could also just use a trimpot as a voltage
divider.The ADC (analog to digital converter) has a resolution of 10 bits.

Communication

Serial

The ESP8266 has two hardware UARTS (Serial ports):


UART0 on pins 1 and 3 (TX0 and RX0 resp.), and UART1 on pins 2 and 8 (TX1 and RX1
resp.), however, GPIO8 is used to connect the flash chip. This means that UART1 can only transmit
data.
UART0 also has hardware flow control on pins 15 and 13 (RTS0 and CTS0 resp.). These two
pins can also be used as alternative TX0 and RX0 pins.

I²C

The ESP doesn’t have a hardware TWI (Two Wire Interface), but it is implemented in software. This
means that you can use pretty much any two digital pins. By default, the I²C library uses pin 4 as SDA
VFSTR (Deemed to be University) 9
and pin 5 as SCL. (The data sheet specifies GPIO2 as SDA and GPIO14 as SCL.) The maximum
speed is approximately 450kHz.

SPI

The ESP8266 has one SPI connection available to the user, referred to as HSPI. It uses GPIO14 as
CLK, 12 as MISO, 13 as MOSI and 15 as Slave Select (SS). It can be used in both Slave and Master
mode (in software).

VFSTR (Deemed to be University) 10


1.Interfacing of LED and SWITCH

AIM: To Blink an LED when switch is pressed using ESP8266 Node MCU.
APPARATUS REQUIRED:
• PC with Arduino IDE
• ESP8266 Node MCU/
• LED
• Switch
• Bread board
• Resistor – 1KΩ
THEORY:
Floating state (Neither connected to 5V nor connected to 0V) is not a good state and is a confused
state. To avoid such there is a mechanism in arduino called pullup or pulldown. There is an inbuilt
resistance which is connected to +5V if there any ambiguious situation then that pin is considered as
high if Pullup resistor is connected. Similarly, Pull down forces to Gnd when there any ambiguous
situation. Arduino have inbuilt pullup resistance but not pull down resistance. One can make pull up
and pull-down resistances by connecting to VCC through 10KΩ resistor. In Arduino, pinMode
(BUTTON, INPUT_PULLUP) will make the pin connected to pull resistor.

PROCEDURE:
1. Connect the Node MCU to the PC using USB cable.

2. Open Arduino IDE, select com port at Tools → port. If the com port is not visible under ports

section. Check the USB connection. If it is proper then go to device manager and select the port.

3. Select the Board NodeMCU 1.0 at Tools → board and Enter the Program.

4. Save it with an appropriate name. Verify/compile to check errors.

5. After ensuring the code is error free. Upload it and observe the output.

OUTPUT:
S.No SWITCH LED
1

VFSTR (Deemed to be University) 11


2

Circuit Diagram:

VFSTR (Deemed to be University) 12


Program:
const int led=D1;
const int sw=D2;
void setup() {
pinMode(led,OUTPUT);
pinMode(sw,INPUT_PULLUP);
}
void loop() {
int v = digitalRead(sw);
if(v==HIGH)
{
digitalWrite(led,LOW);
}
else
{
digitalWrite(led,HIGH);
}}
RESULT:

MODEL VIVA QUESTIONS:

VFSTR (Deemed to be University) 13


1. What is mean by a library in Arduino?
2. Meaning of Sketch in Arduino?
3. What is the GPIO?
4. What is a “Thing” in the context of the Internet of Things (IoT)?

2. Traffic Light
AIM :
To design a traffic light system with red, yellow and green LEDs using nodeMCU

APPARATUS:
S.No. Name of the component Quantity
1 Node MCU 1
2 Red LED 1
3 Green LED 1
4 Yellow LED 1
5 Data cable 1
6 Male – Female wires As per required
7 Personal computer 1
8 Mini Bread Board 1

THEORY:
Traffic lights, also known as traffic signals, traffic lamps, traffic semaphore, signal lights, stop
lights, red lights and traffic control signals in technical parlance, are signaling devices positioned
at road intersections, pedestrian crossings, and other locations to control flows of traffic.
Traffic lights alternate the right of way accorded to users by illuminating lamps or LEDs of
standard colours (red, yellow, and green) following a universal colour code. In the typical sequence
of colour phases:

• The green light allows traffic to proceed in the direction denoted, if it is safe to do so and there is
room on the other side of the intersection.
• The yellow light warns that the signal is about to change to red. Actions required by drivers on a
yellow light vary, with some jurisdictions requiring drivers to stop if it is safe to do so, and others
allowing drivers to go through the intersection if safe to do so.
• A flashing yellow indication is a warning signal. In the United Kingdom, a flashing yellow light
is used only at pelican crossings, in place of the combined red–yellow signal, and indicates that
drivers may pass if no pedestrians are on the crossing.
• The red signal prohibits any traffic from proceeding.
• A flashing red indication requires traffic to stop and then proceed when safe (equivalent to a stop
sign).
In some countries traffic signals will go into a flashing mode if the conflict monitor detects a
problem, such as a fault that tries to display green lights to conflicting traffic. The signal may display
flashing yellow to the main road and flashing red to the side road, or flashing red in all directions.
Flashing operation can also be used during times of day when traffic is light, such as late at night.

Interfacing Diagram:

VFSTR (Deemed to be University) 14


OUTPUT:

Time (nsec) Red LED Yellow LED Green LED


0 ON OFF OFF
5000 OFF ON OFF
10000 OFF OFF ON
15000 ON OFF OFF
20000 OFF ON OFF
25000 OFF OFF ON

VFSTR (Deemed to be University) 15


The purpose of traffic light is simply to facilitate the safe movement of cars, avoiding collisions. In
some cases, however, it seems the purpose is to "catch" some not cautious motorists and sock them
with traffic tickets and fines to raise money for government.

PROCEDURE:
1. Connect the Node MCU to the PC using USB cable.
2. Open Arduino IDE, select com port at Tools → port. If the com port is not visible under ports
section. Check the USB connection. If it is proper then go to device manager and select the port.
3. Select the Board NodeMCU 1.0 at Tools → board and Enter the Program.
4. Save it with an appropriate name. Verify/compile to check errors.
5. After ensuring the code is error free. Upload it and observe the output.

Block Diagram/ Connection Diagram:

PROGRAM :

const int rled=d1;


const int yled=d2;
const int gled=d3;
void setup() {
pinMode(rled,OUTPUT);
pinMode(yled,OUTPUT);
pinMode(gled,OUTPUT);
}

VFSTR (Deemed to be University) 16


void loop()
{
digitalWrite(yled,LOW);
digitalWrite(gled,LOW);
digitalWrite(rled,HIGH);
delay(5000);
digitalWrite(rled,LOW);
digitalWrite(yled,HIGH);
digitalWrite(gled,LOW);
delay(2000);
digitalWrite(yled,LOW);
digitalWrite(gled,HIGH);
digitalWrite(rled,LOW);
delay(5000);
}

RESULT:
Successfully designed a traffic light system with red, yellow and green leds using nodeMCU

MODEL VIVA QUESTIONS:


• what is the operating voltage of ESP8266
• What is the A0 voltage range?
• What is the current flow through a typical LED?
• What is a light emitting diode made of?
• What is the basic principle of LED?

Block Diagram

VFSTR (Deemed to be University) 17


3 INTERFACING DHT SENSOR TO NodeMCU

AIM: To Interface DHT sensor with NodeMCU to display temperature and humidity.

APPARATUS: NodeMCU board, DHT Sensor, bread board.


Arduino IDE software.

THEORY:
The DHT11 is a basic, ultra low-cost digital temperature and humidity sensor. It uses a
capacitive humidity sensor and a thermistor to measure the surrounding air, and spits out a digital
signal on the data pin (no analog input pins needed). Its fairly simple to use, but requires careful timing
to grab data. The DHT11 calculates relative humidity by measuring the electrical resistance between
two electrodes. The humidity sensing component of the DHT11 is a moisture holding substrate with
the electrodes applied to the surface.The change in resistance between the two
electrodes is proportional to the relative humidity.

DHT11 Specifications:
VFSTR (Deemed to be University) 18
• Operating Voltage: 3.5V to 5.5V
• Operating current: 0.3mA (measuring) 60uA (standby)
• Output: Serial data
• Temperature Range: 0°C to 50°C
• Humidity Range: 20% to 90%
• Resolution: Temperature and Humidity both are 16-bit
• Accuracy: ±1°C and ±1%

Circuit Diagram:

Program:

#include<dht.h>;
dht DHT;
#define DHT11_PIN D2
void setup()
{
Serial.begin(9600);
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
Serial.print(“Temperature=”);
Serial.println(DHT.temperature);
Serial.print(“Humidity=”);
Serial.println(DHT.humidity);
delay(1000);
}

OUTPUT:

Temperature: 30.00
Humidity: 74.00
Temperature: 31.00
Humidity: 73.00
VFSTR (Deemed to be University) 19
Temperature: 32.00
Humidity: 70.00

RESULT:

4. INTERFACING DC MOTOR TO NodeMCU


AIM: To interface and control the DC motor with NodeMCU.

VFSTR (Deemed to be University) 20


APPARATUS: NodeMCU board, DC Motor, bread board, RPS, L293D.
Arduino IDE software.
THEORY:
DC motors are simple two-lead, electrically controlled devices that convert electrical
power into mechanical power through the interaction of two magnetic fields. One field is usually
produced by a stationary permanent magnet (on the stator), and the other field is produced by an
electric current flowing in the motor coil (on the rotor). The interaction of the two fields results in a
torque that tends to rotate the rotor.
DC motors are usually classified on the basis of their excitation configuration, as follows
1. Separately excited (field winding is fed by external source)
2. Self-excited –
a. Series wound
b. Shunt wound
3. Compound wound –
a. Long shunt
b. Short shunt
L293D IC is a typical Motor Driver IC which allows the DC motor to drive on any direction. This IC
consists of 16-pins which are used to control a set of two DC motors instantaneously in any direction.
It means, by using a L293D IC we can control two DC motors. As well, this IC can drive small and
quiet big motors.

PIN DIAGRAM OF L293D MOTOR DRIVER

VFSTR (Deemed to be University) 21


CIRCUIT DIAGRAM OF DC MOTOR

OUTPUT:

D1 D2 DIRECTION
HIGH LOW CLOCK WISE
LOW HIGH ANTI CLOCK WISE

VFSTR (Deemed to be University) 22


PROGRAM:
//Motor A
const int inputPin1 = D1; // Pin 15 of L293D IC
const int inputPin2 = D2; // Pin 10 of L293D IC
void setup()
{
pinMode(inputPin1, OUTPUT);
pinMode(inputPin2, OUTPUT);
}
void loop()
{
digitalWrite(inputPin1, HIGH);
digitalWrite(inputPin2, LOW);
delay(1000)
digitalWrite(inputPin1, LOW);
digitalWrite(inputPin2, HIGH);
delay(1000)
}

RESULT:

MODEL VIVA QUESTIONS:


5. What is the principle operation of DC Motors?
6. What is back e.m.f in a DC motor?
7. Why is shaft torque less than armature torque in a DC motor?
8. Why series motor cannot be started on no-load?
9. Why motordriver IC is used?
10. What is the use of l293d motor driver?

VFSTR (Deemed to be University) 23


5. Python Overview, Exercises using python and File operations
Aim :
To understand the concepts of python language and perform an experiment on files.

Apparatus :

Raspberry pi with python

Theory :

Python :

Python is an object-oriented programming language created by Guido Rossum in 1989. It is


ideally designed for rapid prototyping of complex applications. It has interfaces to many OS system
calls and libraries and is extensible to C or C++. Many large companies use the Python programming
language include NASA, Google, YouTube, BitTorrent, etc.

Python is widely used in Artificial Intelligence, Natural Language Generation, Neural


Networks and other advanced fields of Computer Science.

Characteristics of Python :

It provides rich data types and easier to read syntax than any other programming languages
It is a platform independent scripted language with full access to operating system API's
Compared to other programming languages, it allows more run-time flexibility
It includes the basic text manipulation facilities of Perl and Awk
A module in Python may have one or more classes and free functions
Libraries in Pythons are cross-platform compatible with Linux, MacIntosh, and Windows
For building large applications, Python can be compiled to byte-code
Python supports functional and structured programming as well as OOP
It supports interactive mode that allows interacting Testing and debugging of snippets of code
In Python, since there is no compilation step, editing, debugging and testing is fast.

VFSTR (Deemed to be University) 24


Output :

input.txt :

- 123456 ps
0 S ck 1
0 S ck_c 0
0 E rdqs 00
0 E rdqs_c 11
0 E edc 11

- 2345167 ps
0 S ck 0
0 S ck_c 1
0 E rdqs 11
0 E rdqs_c 00
0 E edc 10
-342567 ps

0 S ck 1
0 S ck_c 0
0 E rdqs 00
0 E rdqs_c 11
0 E edc 11

output.txt :

- 123456 ps
0 E edc 11
0 E rdqs 00
0 E rdqs_c 11
0 S ck 1
0 S ck_c 0

- 2345167 ps
0 E edc 10
0 E rdqs 11
0 E rdqs_c 00
0 S ck 0
0 S ck_c 1

-342567 ps
0 E edc 11
0 E rdqs 00
0 E rdqs_c 11
0 S ck 1
0 S ck_c 0

VFSTR (Deemed to be University) 25


Procedure :

1. Enter the python code in python ide.


2. Make sure the python code, input.txt and output.txt files are in the same folder.
3. Check the errors and execute.

Code :

with open("input.txt","r") as f3:


with open("input1.txt", "w") as f2:
for line in f3:
f2.write(line)
f2.write("\n")
f2.write("-")
with open("input1.txt", "r") as file:
data = file.readlines() #
#print(data)
with open("output.txt", "w") as f:
f.write("")
l1=[]
edc=ck=ck_c=rdqs=rdqs_c=st=s=''
for line in data :
for i in line :
if(i=='-'):
s=line
for j in l1:
#print(type(j))
d = j.split()
#print(data)
# Checking if edc,ck etc.,. exists in list
for k in d:
if(k == 'edc') :
edc = j
if(k=='ck'):
ck=j
if(k=='ck_c'):
ck_c=j
if(k=='rdqs'):
rdqs=j
if(k=='rdqs_c'):
rdqs_c=j
#break
with open("output.txt", "a") as f:
f.write(st)
# f.write("\n")
f.write(edc)
# f.write("\n")
f.write(rdqs)
# f.write("\n")
f.write(rdqs_c)

VFSTR (Deemed to be University) 26


# f.write("\n")
f.write(ck)
#f.write("\n")
f.write(ck_c)
f.write("\n")
print(st,edc,rdqs,rdqs_c,ck,ck_c)

st=s
l1=[]
l1.append(line)

Result :

MODEL VIVA QUESTIONS:

1. How to run a file in python?


2. Write file modes in python?
3. Explain read operation.
4. Explain write operation.
5. Explain append operation.
6. Explain print operation.
7. Write open command
8. Explain Loops

VFSTR (Deemed to be University) 27


Familiarization of Raspberry pi board
a. Downloading and installing Raspbian:

1.Open the site https://www.raspberrypi.org/downloads/raspbian/ and download Raspbian stretch


with desktop. Raspbian stretch lite is the os for low memory devices.
2. Download etcher. Unzip Raspbian and burn it into a memory card using etcher.
3. Now remove the memory card from PC and place it in Raspberry pi.
4. When the first time, the raspberry pi gets switched on, the Raspbian automatically installs.

Specifications :

SoC – Broadcom BCM2837 64bit ARMv8 quad core Cortex A53 processor @ 1.2GHz with dual core
VideoCore IV GPU @ 400 MHz supporting OpenGL ES 2.0, hardware-accelerated OpenVG, and
1080p30 H.264 high-profile decode. Capable of 1Gpixel/s, 1.5Gtexel/s or 24GFLOPs with texture
filtering and DMA infrastructure
System Memory – 1GB LPDDR2
Storage – micro SD slot
Video & Audio Output – HDMI 1.4 and 4-pole stereo audio and composite video port
Connectivity – 10/100M Ethernet, WiFi 802.11 b/g/n up to 150Mbps and Bluetooth 4.1 LE
(BCM43438 module)

VFSTR (Deemed to be University) 28


USB – 4x USB 2.0 host ports (with better power management, allowing higher power peripherals),
1x micro USB port for power Expansion
40-pin GPIO header
MIPI DSI for Raspberry Pi touch screen display
MIPI CSI for Raspberry Pi camera
Power Supply – 5V up to 2.4A via micro USB port
Dimensions – 85 x 56 x 17 mm
So the specifications were more or less as expected from the leaked information we’ve received before
the official release, and people hoping for 4K or H.265 video decoding will be disappointed. The new
processor is said to be 10 times faster than BCM2835 processor found in the first Raspberry Pi Model
B board, and it’s likely it can handle 1080p H.264 @ 60 fps using software decoding. The VideoCore
IV GPU’s subsystem is now clocked at 400MHz and the 3D core at 300MHz against 250MHz for
previous “Raspberry Pi processors”.
Since they’ve basically kept the same features as Raspberry Pi 2, beside changing the Cortex
A7 cores to 64-bit Cortex A53 ones, and adding built-in WiFi and Bluetooth via a BCM43438 module,
firmware support is basically the same with various Linux distributions – Raspbian being the
recommended distro – and Windows 10 IoT.

Fig. Rapberry pi board numbering.

VFSTR (Deemed to be University) 29


Block Diagram

Output:

LED is Blinking Continuously

VFSTR (Deemed to be University) 30


6.a. Switching ON and OFF LED
Aim : To switch ON and OFF LED using Raspberry pi.

Apparatus :

Raspberry pi with python.


LED

Procedure :

1. Open the python editor, enter the code.


2. Save it with an extension .py.
3. Made the hardware connections.
4. Execute the code by clicking on Run.

Program :

import RPi.GPIO as GPIO


import time
pin=18
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.HIGH)
time.sleep(1)
GPIO.output(pin, GPIO.LOW)
time.sleep(1)
GPIO.cleanup()

Result :

VFSTR (Deemed to be University) 31


Block Diagram

OUTPUT:

VFSTR (Deemed to be University) 32


6.b. Capturing and Storing image
Aim :
To capture and store an image using Raspberry pi.

Apparatus :
pi camera
Raspberry pi

Procedure :

1. To capture an image with name image.jpg from console the command is raspistill -o image.jpg.
2. Using module python-picamera, the images can be captured in python code. Hence before using it,
one needs to install that as sudo apt-get install python-picamera.

Python code :

import picamera
camera = picamera.PiCamera()
camera.capture(‘image.jpg’)

Result :

Model Viva Questions:


1. What is raspberry Pi
2. What is type of camera used
3. How to capture an image
4. How to keep camera in active state
5. What are libraries to be installed for camera
6. Explain GPIO Command
7. Explain Output command
8. Explain Setup command
9. What is Rpi
10. Explain Setmode Command

VFSTR (Deemed to be University) 33


Circuit Diagram and Wiring Connections:

a) Circuit Diagram

b) Wiring connection between Sensor and Raspberry pi 3

VFSTR (Deemed to be University) 34


1. Interfacing sensors to Raspberry pi
Aim: PIR Sensor interfacing with Raspberry pi for Intruder detection.

Apparatus Required:
• Raspberry Pi 3 Model B

• PIR Sensor
• 5V Buzzer
• Connecting Wires
• Mini Breadboard
• Power Supply
• Computer
Theory:

PIR Sensor:
PIR Sensor has three pins namely VCC, DATA and GND. Also, the PIR Sensor has two
potentiometers: one for adjusting the sensitivity of the sensor (or rather the sensing distance of the
sensor) and the other for adjusting the time for which the Output stays high upon detecting any human
movement.

Working:
The working of the PIR Motion Sensor using Raspberry Pi is very simple. If the PIR Sensor detects
any human movement, it raises its Data Pin to HIGH. Raspberry Pi upon detecting a HIGH on the
corresponding input pin will activate the Buzzer.

Applications:

The applications of the PIR Sensor using Raspberry Pi have been mentioned below. Some of them
are Automatic Room Light, Motion Detection Intruder, Alert Automatic Door Opening and Home
Security System.

Procedure:

1. Open the python editor, enter the code.


2. Save it with an extension .py.
3. Made the hardware connections.
4. Execute the code by clicking on Run.

VFSTR (Deemed to be University) 35


OUTPUT:

Motion Detected….
Motion Detected….
Motion Detected….
Program:
import RPi.GPIO as GPIO
import time

sensor = 16
buzzer = 18

GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor,GPIO.IN)
GPIO.setup(buzzer,GPIO.OUT)

GPIO.output(buzzer,False)
print "Initialzing PIR Sensor......"
time.sleep(12)
print "PIR Ready..."
print " "

try:
while True:
if GPIO.input(sensor):
GPIO.output(buzzer,True)
print "Motion Detected"
while GPIO.input(sensor):
time.sleep(0.2)
else:
GPIO.output(buzzer,False)

except KeyboardInterrupt:
GPIO.cleanup()

Result:

Model Viva Questions:


1. Define PIR Sensor
2. What is the working principle of PIR Sensor
3. What is the Intruder Detection
4. How many pins of PIR Sensor
5. What are the components to build a Intruder Detection Application
6. What are the drawbacks of PIR Sensor
7. What are the advantages of PIR Sensor
8. Mention the applications of PIR Senso
9. What is Buzzer
10. Explain the wiring connection between the PIR Sensor and Raspberry pi

VFSTR (Deemed to be University) 36


Sourece Links:

1. https://www.electronicshub.org/pir-motion-sensor-using-raspberry-pi/
2. https://www.youtube.com/watch?v=_ACe6z-Hp2E
2. Data logging

Aim :
To send data from client to server remotely and store in the database.

Apparatus:

Sl.No Name of the component Quantity


1 Raspberry pi with python and Django 1
2 Node MCU 1

Theory :

Django is a high-level Python Web framework that encourages rapid development and clean,
pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web
development, so you can focus on writing your app without needing to reinvent the wheel. It’s free
and open source.

Django installation on Raspberry pi :

1. Setup Project Files Raspberry Pi Django Web App

mkdir -p ~/djangoproject
cd ~/djangoproject

2. Install Virtual Environment for Django Web App

pip3 install virtualenv


or
sudo pip3 install virtualenv

3. Create Virtual Environment and Activate

virtualenv venv && source venv/bin/activate

4. Install Django on your Raspberry Pi, and Create the Project Files

pip3 install django


django-admin startproject raspberrypiapp
cd raspberrypiapp

5. Migrate Changes and Start the Server!

python3 manage.py migrate

VFSTR (Deemed to be University) 37


python3 manage.py runserver 127.0.01:8000

OUTPUT :

VFSTR (Deemed to be University) 38


Procedure :

1. Install django on Raspberry pi. Create a django project and create an app inside the project.
2. Run the server.
3. Connect the internet and run the code on Node MCU.
4. Check the database whether the data sending from nodemcu is reached to Raspberry pi and stored
inside the database.

Program :

On Raspberry pi :

models.py :

from django.db import models


class sss(models.Model):
am = models.CharField(max_length=300, blank=True)
bm = models.CharField(max_length=300, blank=True)

views.py :

from django.shortcuts import render


from django.http import HttpResponse
def index(request,a,b):
a1=sss(am=a,bm=b)
a1.save()
title = "The values of a and b as %s and %s are inserted into the database successfully" % (a,
b)
return HttpResponse("<h1>%s</h1>" %title)

app-urls.py :

from django.urls import path


from . import views
urlpatterns = [
path(''<str:a>/<str:b>/, views.index, name='index'),
]

project-urls.py

from django.contrib import admin


from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('events.urls')),
]

VFSTR (Deemed to be University) 39


On NodeMCU :

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";
void setup () {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print("Connecting..");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://jsonplaceholder.typicode.com/10/15"); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString();//Get the request response payload
Serial.println(payload); //Print the response payload
}
http.end(); //Close connection
}
delay(30000); //Send a request every 30 seconds
}

RESULT:

Model Viva questions :

1. Explain Django architecture.


2. What are the files that are created when an app was created in a django project
3. Write the commands for running the server in django.
4. Write about view in django.
5. Write a few lines about django.
6. Write about the django admin site
7. Write the commands for a creating a new project in django.
8. Write about model in django.
9. Write about template in django.

VFSTR (Deemed to be University) 40


Block Diagram:

VFSTR (Deemed to be University) 41


9. Data Processing
AIM : Analyzing Data Streams Using Raspberry Pi and DHT11.

APPARATUS REQUIRED :
• DHT11 - Temperature and Humidity Sensor Module
• Raspberry Pi
• Bread board
• Jumper wires

PROCEDURE:

• Set up the DHT11 humidity sensor on the Raspberry Pi.


• GPIO pin is 27.

Download the Adafruit DHT11 library. In the terminal, type the following command.

Navigate to Adafruit_Python_DHT directory (folder).

Run the following commands in the terminal.

To install the library, in the terminal, type the following.

Navigate to the example folder.

Replace the following demo code.

Run the program.

VFSTR (Deemed to be University) 42


OUTPUT:

VFSTR (Deemed to be University) 43


Program:
import sys
import Adafruit_DHT
import time
import xlwt
from xlwt import Workbook
# Workbook is created
wb = Workbook()
sheet1 = wb.add_sheet('Sheet 1')
i=0
sheet1.write(1, 0, 'temperature')
sheet1.write(2, 0, 'humidity')
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
i=i+1
#humidity = i
#temperature = i+5
print ('Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity))
time.sleep(1)
k=time.asctime(time.localtime(time.time()))
sheet1.write(1, i, temperature)
sheet1.write(2, i, humidity)
sheet1.write(0, i, k)
wb.save('xlwt example.xls')

RESULT:

VFSTR (Deemed to be University) 44


MODEL VIVA QUESTIONS:
a. What is Raspberry Pi ?
b. What is the GPIO ?
c. Due to what components DHT 11 sensor will calculate Temperature & Humidity ?
d. What is a “Thing” in the context of the Internet of Things (IoT) ?

VFSTR (Deemed to be University) 45


10. SENDING EMAIL USING RASPBERRY PI

AIM: To Send Email using Raspberry pi

APPARATUS:
1. Raspberry pi Kit with python3.
2. Internet Provider

THEORY:

One of the application of raspberry-pi is to use SMTP (Simple mail transfer protocol) for
sending and receiving emails.
In this project, we are going to send an email via SMTP server using raspberry pi. SMTP works
by starting a session between the user and server, whereas MTA (Mail Transfer Agent) and MDA
(Mail Delivery Agent) provide domain searching and local delivery services

Simple Mail Transfer Protocol (SMTP)


SMTP is the standard protocol for providing email services on a TCP/IP network. This server
provides the ability to receive and send email messages.
SMTP is an application-layer protocol that provides the delivery and transmission of email over the
Internet. It is maintained by the Internet Engineering Task Force (IETF). SMTP is generally
summed within an email client application and is composed of four key components:

1. Local user or client-end utility known as the mail user agent (MUA)
2. Server known as mail submission agent (MSA)
3. Mail transfer agent (MTA)
4. Mail delivery agent (MDA)

Getting email alerts or set of data using raspberry pi python program is very useful application. All
we need is smtplib library in the python script. There are many version of python but pi is more
compatible with 3.2 and 2.7 version of it.
“Allow less secure apps” setting and “On” it using this link

https://myaccount.google.com/lesssecureapps?pli=1

VFSTR (Deemed to be University) 46


OUTPUT:

VFSTR (Deemed to be University) 47


PROCEDURE:

1. Open the python editor, enter the code.


2. Save it with an extension .py.
3. Made the hardware connections.
4. Execute the code by clicking on Run.

PROGRAM:

import smtplib
import config
# list of email_id to send the mail
li = ["[email protected]", "[email protected]"]
for i in range(len(li)):
try:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()
s.login(config.EMAIL_ADDRESS, config.PASSWORD)
message = "Hello there, how are you today?"
s.sendmail("config.EMAIL_ADDRESS", li[i], message)
s.quit()
except :
print("Email failed to send.")
‘’’message = 'Subject: {}\n\n{}'.format(subject, msg)
subject = "Test subject"
msg = "Hello there, how are you today?" ’’’

config.py :

EMAIL_ADDRESS = “xxxxxxx”
PASSWORD = “Xxxxxx”

RESULT:

VFSTR (Deemed to be University) 48


MODEL VIVA QUESTIONS:
1. What is SMTP?
2. What is MDA?
3. What is MTA?
4. Write login Command
5. Write sendmail command

VFSTR (Deemed to be University) 49


11. Send data to Cloud
AIM :

To write a program to send data to Thingspeak cloud

APPARATUS:

Sl.No Name of the component Quantity


1 PC with arduino IDE 1
2 Node MCU 1
3 LM35 1
4 Bread board 1
5 Jumper wires few

THEORY:

Arduino Uno is a microcontroller board based on 8-bit ATmega328P microcontroller. Along


with ATmega328P, it consists other components such as crystal oscillator, serial communication,
voltage regulator, etc. to support the microcontroller. Arduino Uno has 14 digital input/output
pins (out of which 6 can be used as PWM outputs), 6 analog input pins, a USB connection, A
Power barrel jack, an ICSP header and a reset button.

PROCEDURE :

1. Connect the Node MCU to the PC using USB cable.


2. Open Arduino IDE, select com port at Tools → port. If the com port is not visible under ports
section. Check the USB connection. If it is proper then go to device manager and select the port.
3. Select the Board Node-MCU 1.0 at Tools → board and Enter the Program.
4. Save it with an appropriate name. Verify/compile to check errors.
5. After ensuring the code is error free. Upload it and observe the output.

PROGRAM :

#include <ESP8266WiFi.h>
const char* host = "api.thingspeak.com"; // Your domain
String ApiKey = " **************"; // the API key that has to select is write API
String path = "/update?key=" + ApiKey + "&field1=";
const char* ssid = "SSIDNAME";
const char* pass = "Password";
int sensor = A0;
float tempc;
float svoltage;
void setup(void){
Serial.begin(115200);
Serial.println("");
OUTPUT:

WiFi.begin(ssid, pass);
// Wait for connectionwhile (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
float xval = analogRead(sensor);
svoltage = (xval*3300.0)/1023;
tempc = svoltage/10;
Serial.println(tempc);
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
client.print(String("GET ") + path + String(tempc) + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: keep-alive\r\n\r\n");
delay(16000);
}

RESULT :
MODEL VIVA QUESTIONS:
1. How can write data to thingspeak cloud.
2. How to read data from Thingspeak cloud
3. Explain the differences between HTTP and MQTT
4. Give me some examples of HTTP cloud.
5. Give me some examples of MQTT cloud.
6. Give me some examples of both HTTP and MQTT cloud.
12. Networking in Python
Aim :
Transferring the data between the client and server

Aparatus: Raspberry Pi Board

Theory :

Accessing a local server from the Internet:

In computing, a server is a computer program or a device that provides functionality for other
programs or devices, called "clients". This architecture is called the client-server model, and a single
overall computation is distributed across multiple processes or devices. Servers can provide various
functionalities, often called "services", such as sharing data or resources among multiple clients or
performing computation for a client. A single server can serve multiple clients, and a single client can
use multiple servers. A client process may run on the same device or may connect over a network to
a server on a different device.[1] Typical servers are database servers, file servers, mail servers, print
servers, web servers, game servers, and application servers.[2]

You run a simple socket server on a PC listening on port 2017 that just displays state
messages in a console. Try to set up your router so that the server is visible from anywhere on
the Internet. A client on the Raspberry Pi connects to the server and sen ds sensor information
(here just the state of a button) every second.

In this experiment, we exchange the roles of client and server and run the client on the
Raspberry Pi and the server on a PC connected through a WLAN or Ethernet router located
anywhere on the Internet.

To make your PC server accessible from the Internet, you must set up the router for
"IP forwarding" by specifying a single or a range of IP ports. (The setup is sometimes called
"Virtual Servers".) Any request from outside to the router's IP address with a port in the
specified range is then forwarded to your PC.

The socket is a combination of an IP address and a port number is called a socket.


Output:

Client :

Connection established
Data sent successfully

Server :

starting up on 2017 port 10.14.88.82


Message to the server

There are two problems: Because your PC's IP address is given by your router's DHCP, it
is subject to change. Thus the IP forwarding to the specified IP may fail. To avoid this problem,
you can either set up your PC to use a fixed IP address or bind the IP address to the fixed Mac
address of your PC's WLAN or Ethernet adapter by an "address reservation" (if available on your
router).

The second problem arises because your router's IP address is delivered by your provider
using DHCP, and thus is also subject to change. Therefore your PC server cannot be accessed from
outside with a fixed, well-known IP address. This problem can be solved by using a Dynamic
Update Client (DUC), provided for free from noip.com. The DUC connects every 5 minutes (or
another interval you chose) to the no-IP server and announces your router's IP address. From the
TCP client, the link is established using the IP alias provided by No-IP and the connection request
is then forwarded by the no-IP server to your router that finally forwards it to the PC.

Procedure:
1. Open the python editor, enter the python code in python ide.
2. Make sure the python code, input.txt, and output.txt files are in the same folder.
3. Save it with an extension .py
4. Check the errors and execute
5. Made the hardware connections.
6. Execute the code by clicking on Run.
Source Code:
Client-Side:
Import socket
Import sys

#Create a TCP\IP socket


Client _socket =socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#Connect to Listener socket


Client_socket.connect((“10.14.88.82”,2017))
Print>>sys.stderr,’Connection Established’

#Send command
Client_socket.send(‘Message to the server’)
Print(‘Data sent successfully’)

Server Side:
Import socket
Import sys
#Create a TCP/IP socket
Socket=socket.socket(socket.AF_INET,socket.STOCK_STREAM)

#Bind the socket to the port


Server_address=(’10.14.88.82’,2017)
Print>>sys.stderr,’starting up on %s’ %server_address
Sock.bind(server_address)

#Listen for incoming connections


Sock.listen(1)
Connection,client_address=sock.accept()

#Receive command
Data=connection.recv(1024)
Print(data)
Sock.close()

Result:

MODEL VIVA QUESTIONS:


1. What is a Socket?
2. What are the 7 Layers (OSI Model) of Networking?
3. What is the difference between TCP And UDP?
4. What does a socket consist of?
5. What are some advantages and disadvantages of sockets?
6. What is the encapsulation technique?
7. What is the difference between a NULL pointer and a void pointer?
8. What is the server?
9. What is the client?
10. How does race condition occur?

13. Whatsapp Connectivity


Aim : Sending Whatsapp message using Raspberry pi.

Apparatus :

Raspberry pi with python.

Theory:

Selenium is a great tool for Internet scraping or automated testing for websites.

Installations :

pip install selenium


sudo apt-get install chromium-browser

Procedure :

1. Open the python editor, enter the code.


2. Save it with an extension .py.
3. Made the hardware connections.
4. Execute the code by clicking on Run.

Program :

from selenium import webdriver


from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
# Replace below path with the absolute path
# to chromedriver in your computer
driver = webdriver.Chrome('/home/saket/Downloads/chromedriver')

driver.get("https://web.whatsapp.com/")
wait = WebDriverWait(driver, 600)

# Replace 'Friend's Name' with the name of your friend


# or the name of a group
target = '"Friend's Name"'

# Replace the below string with your own message


string = "Message sent using Python!!!"

x_arg = '//span[contains(@title,' + target + ')]'


group_title = wait.until(EC.presence_of_element_located((
By.XPATH, x_arg)))
group_title.click()
inp_xpath = '//div[@class="input"][@dir="auto"][@data-tab="1"]'

OUTPUT:
input_box = wait.until(EC.presence_of_element_located((
By.XPATH, inp_xpath)))
for i in range(100):
input_box.send_keys(string + Keys.ENTER)
time.sleep(1)

Result :

MODEL VIVA QUESTIONS:


1. What is selenium
2. What is import
3. Write wait command
4. Explain input Command
5. Explain how to send messages using Chrome

You might also like