0% found this document useful (0 votes)
62 views74 pages

Wa0002.

Here are the key steps to calculate temperature using an LM35 temperature sensor and Arduino: 1. Connect the LM35 temperature sensor to the Arduino. - Connect the LM35 Vcc pin to the Arduino 5V pin - Connect the LM35 Gnd pin to the Arduino Gnd pin - Connect the LM35 Out pin to an analog input pin on the Arduino (e.g. A0) 2. Write the Arduino code to read the analog value from the temperature sensor pin. The analogRead() function returns a value between 0-1023 that is proportional to the voltage input. 3. Convert the analog reading to voltage. The LM35 outputs 10mV for every

Uploaded by

akvakarthik2005
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)
62 views74 pages

Wa0002.

Here are the key steps to calculate temperature using an LM35 temperature sensor and Arduino: 1. Connect the LM35 temperature sensor to the Arduino. - Connect the LM35 Vcc pin to the Arduino 5V pin - Connect the LM35 Gnd pin to the Arduino Gnd pin - Connect the LM35 Out pin to an analog input pin on the Arduino (e.g. A0) 2. Write the Arduino code to read the analog value from the temperature sensor pin. The analogRead() function returns a value between 0-1023 that is proportional to the voltage input. 3. Convert the analog reading to voltage. The LM35 outputs 10mV for every

Uploaded by

akvakarthik2005
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/ 74

VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE

DEPARTMENT OF INFORMATION TECHNOLOGY

INTERNET OF THINGS (VR23)


LAB MANUAL

Prepared by
D. Chaithanya
Assistant Professor
VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE
DEPARTMENT OF INFORMATION TECHNOLOGY

VISION

To evolve into a center of excellence in Science & Technology through creative


and innovative practices in teaching- learning, promoting academic
achievement & research excellence to produce internationally accepted
competitive and world class professionals who are psychologically strong and
emotionally balanced imbued with social consciousness and ethical values.

MISSION

To provide high quality academic programmes, training activities, research


facilities and opportunities supported by continuous industry – institute
interaction aimed at employability, entrepreneurship, leadership and research
aptitude among students and contribute to the economic and technological
development of the region, state and nation.
INTERNET OF THINGS LAB VR23 BTECH II Year – I Sem
1A) Using Raspberry Pi calculate the distance using distance sensor.
Components Required: Required Hardware

For this tutorial you will need:

• Raspberry Pi (any model and version is suitable)


• HC-SR04 distance detection module
• Breadboard
• 1kΩ Resistor
• 2kΩ Resistor
• Female to male and male to male jumper wires
• microSD card with Raspbian GNU/Linux distribution

Wiring

Connect HC-SR04 distance detection module to your Raspberry Pi as shown on the diagram
below:
Source Code

Open a terminal on your Raspberry Pi or login remotely using SSH. If Python and Git are not
install type the commands below to install it:

sudo apt-get update


sudo apt-get install -y git
sudo apt-get install -y python-dev python-rpi.gpio

Type the following commands to get the source code and execute a Python script that displays
the distance:

git clone https://github.com/leon-anavi/rpi-examples.git


cd rpi-examples/HC-SR04/python/
python distance.py

The Python script will show distance on each second. Move object near the sensor and observe
how to output data changes, for example:

Distance: 5.4 cm
Distance: 8.5 cm
Distance: 265.4 cm
Distance: 264.7 cm
Distance: 386.6 cm
Distance: 232.4 cm
Distance: 231.2 cm
Distance: 230.5 cm
Distance: 215.7 cm
Distance: 136.4 cm
Distance: 9.6 cm
Distance: 145.7 cm
Distance: 131.8 cm
Distance: 129.8 cm
Distance: 219.2 cm
Distance: 5.7 cm
Distance: 7.8 cm
Distance: 15.7 cm
Distance: 2773.4 cm

Press Ctrl + C to terminate the execution of the Python script.


1B) Using Raspberry Pi test the basic LED functionality

Building the Circuit

The circuit consists of a power supply (the Raspberry Pi), an LED that lights
when the power is applied, and a resistor to limit the current that can flow
through the circuit:
• You will be using one of the ‘ground’ (GND) pins to act like the
‘negative’ or 0 volt ends of a battery.
• The ‘positive’ end of the battery will be provided by a GPIO pin. Here
we will be using pin GPIO18 (which is physical pin 12).
• When these pins are ‘taken high’, which means it outputs 3.3 volts, the
LED will light.
Now take a look at the circuit diagram below:

You should turn your Raspberry Pi off for the next bit, just in case you
accidentally short something out.
• Use one of the jumper wires to connect a ground pin to the rail, marked
with blue, on the breadboard. The female end goes on
the Raspberry Pi's pin, and the male end goes into a hole on the
breadboard.
• Then connect the resistor from the same row on the breadboard to a
column on the breadboard, as shown above.
• Next, push the LEDs legs into the breadboard, with the long leg (with
the kink) on the right.
• Lastly, complete the circuit by connecting the right hand leg of the
LED to GPIO18. This is shown here with the blue wire.

The Code

You are now ready to write some code to switch the LED on. Turn on your
Raspberry Pi and open the terminal window.

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

Type or copy over the following code:

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)

Once you have added all the code and checked it, save and exit the text editor
with “Ctrl + x” then “y” then “enter”.

Running the Code

To run this code type:

sudo python LED.py


Copy
You will see the LED turn on for a second and then turn off.

If your code does not run and an error is reported, edit the code again using
nano LED.py.
2A) Using Arduino Calculate the distance using distance sensor

Components Required:

1. Arduino Uno R3 board


2. Ultrasonic sensor (HC-SR04)
3. 16×2 LCD I2C Display
4. Jumper Wires

Circuit Diagram:

Ultrasonic Distance measurement circuit

Setup:

1. Connect the Echo pin of the sensor to the D2 pin of the Arduino.
2. Connect the Trig pin of the sensor to the D3 pin of the Arduino.
3. Navigate to Tools and select board and port.
4. Verify and compile the code, then upload the code to the Arduino Uno R3
board.
5. Monitor the output in the Serial monitor (Set the baud rate as 9600). To
open Serial monitor Tools>Serial Monitor or (Ctrl+Shift+M).

Arduino Code (Output in Serial monitor):

The following code will show the output on the serial monitor of Arduino
software with a baud rate of 9600.

• C++
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04

#define trigPin 3 // attach pin D3 Arduino to pin Trig of HC-SR04

long duration; // Variable to store time taken to the pulse// to reach receiver

int distance; // Variable to store distance calculated using // formula

void setup()

pinMode(trigPin,

OUTPUT); // Sets the trigPin as an OUTPUT

pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT

// Serial Communication is starting with 9600 of

// baudrate speed

Serial.begin(9600);

// The text to be printed in serial monitor

Serial.println(

"Distance measurement using Arduino Uno.");

delay(500);

void loop()

digitalWrite(trigPin, LOW);

delayMicroseconds(2); // wait for 2 ms to avoid collision in serial monitor


digitalWrite(

trigPin,

HIGH); // turn on the Trigger to generate pulse

delayMicroseconds(10); // keep the trigger "ON" for 10 ms to generate pulse


for 10 ms.

digitalWrite(trigPin,

LOW); // Turn off the pulse trigger to stop

// pulse generation

// If pulse reached the receiver echoPin

// become high Then pulseIn() returns the

// time taken by the pulse to reach the

// receiver

duration = pulseIn(echoPin, HIGH);

distance

= duration * 0.0344 / 2; // Expression to calculate

// distance using time

Serial.print("Distance: ");

Serial.print(

distance); // Print the output in serial monitor

Serial.println(" cm");

delay(100);

}
2B) Using Arduino demonstrate the basic LED functionality

LEDs are small, powerful lights that are used in many different applications. To
start, we will work on blinking an LED, the Hello World of microcontrollers. It
is as simple as turning a light on and off. Establishing this important baseline
will give you a solid foundation as we work towards experiments that are more
complex.

Components Required

You will need the following components −

• 1 × Breadboard
• 1 × Arduino Uno R3
• 1 × LED
• 1 × 330Ω Resistor
• 2 × Jumper
Procedure

Follow the circuit diagram and hook up the components on the breadboard as
shown in the image given below.

Note − To find out the polarity of an LED, look at it closely. The shorter of the
two legs, towards the flat edge of the bulb indicates the negative terminal.
Components like resistors need to have their terminals bent into 90° angles in
order to fit the breadboard sockets properly. You can also cut the terminals
shorter.

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino
language will control your circuit. Open the new sketch File by clicking New.
Arduino Code
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/

// the setup function runs once when you press reset or power the board

void setup() { // initialize digital pin 13 as an output.


pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever

void loop() {
digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Code to Note

pinMode(2, OUTPUT) − Before you can use one of Arduino’s pins, you need
to tell Arduino Uno R3 whether it is an INPUT or OUTPUT. We use a built-in
“function” called pinMode() to do this.

digitalWrite(2, HIGH) − When you are using a pin as an OUTPUT, you can
command it to be HIGH (output 5 volts), or LOW (output 0 volts).

Result

You should see your LED turn on and off. If the required output is not seen,
make sure you have assembled the circuit correctly, and verified and uploaded
the code to your board.
2C) Using Arduino Calculate temperature using a temperature sensor

The Temperature Sensor LM35 series are precision integrated-circuit


temperature devices with an output voltage linearly proportional to the
Centigrade temperature.

The LM35 device has an advantage over linear temperature sensors calibrated
in Kelvin, as the user is not required to subtract a large constant voltage from
the output to obtain convenient Centigrade scaling. The LM35 device does not
require any external calibration or trimming to provide typical accuracies of
±¼°C at room temperature and ±¾°C over a full −55°C to 150°C temperature
range.

Technical Specifications
• Calibrated directly in Celsius (Centigrade)
• Linear + 10-mV/°C scale factor
• 0.5°C ensured accuracy (at 25°C)
• Rated for full −55°C to 150°C range
• Suitable for remote applications
Components Required

You will need the following components −

• 1 × Breadboard
• 1 × Arduino Uno R3
• 1 × LM35 sensor
Procedure

Follow the circuit diagram and hook up the components on the breadboard as
shown in the image given below.

Sketch

Open the Arduino IDE software on your computer. Coding in the Arduino
language will control your circuit. Open a new sketch File by clicking New.

Arduino Code
float temp;
int tempPin = 0;

void setup() {
Serial.begin(9600);
}
void loop() {
temp = analogRead(tempPin);
// read analog volt from sensor and save to variable temp
temp = temp * 0.48828125;
// convert the analog volt to its temperature equivalent
Serial.print("TEMPERATURE = ");
Serial.print(temp); // display temperature value
Serial.print("*C");
Serial.println();
delay(1000); // update sensor reading each one second
}
Code to Note

LM35 sensor has three terminals - Vs, Vout and GND. We will connect the
sensor as follows −

• Connect the +Vs to +5v on your Arduino board.


• Connect Vout to Analog0 or A0 on Arduino board.
• Connect GND with GND on Arduino.

The Analog to Digital Converter (ADC) converts analog values into a digital
approximation based on the formula ADC Value = sample * 1024 / reference
voltage (+5v). So with a +5 volt reference, the digital approximation will be
equal to input voltage * 205.

Result

You will see the temperature display on the serial port monitor which is updated
every second.
3A) Using Node MCU Calculate the distance using distance sensor

Components Required

List of components required for the instructable :

Hardware Requirements

• NodeMCU
• HC-SR04 (Ultra-sonic Sensor)
• Bread Board
• Jumper Wires
• Micro USB Cable

Software Requirements

• Arduino IDE

Let's start implementing it.


SPECIFICATION of HC-SR04

1. Power supply : 5v DC
2. Ranging distance : 2cm – 500 cm
3. Ultrasonic Frequency : 40k Hz
Working

HOW IT WORKS?

Hmm, well actually we have to figure out the distance because the sensor itself
simply holds it's "ECHO" pin HIGH for a duration of time corresponding to the
time it took to receive the reflection (echo) from a wave it sent.

1. The module sends out a burst of sound waves, at the same time it applies
voltage to the echo pin.
2. The module receives the reflection back from the sound waves and
removes voltage from the echo pin.

On the base of the distance a pulse is generated in the ultrasonic sensor to send
the data to NodeMCU or any other micro-controller.

The starting pulse is about 10us and the PWM signal will be 150 us-25us on the
base of the distance. If no obstacle is there, then a 38us pulse is generated for
NodeMCU to confirm that there are not objects detected.

Before getting the reading of the HC-SR04 know about the calculation.

FORMULA

D = 1/2 × T × C
where D is the distance, T is the time between the Emission and Reception, and
C is the sonic speed.
(The value is multiplied by 1/2 because T is the time for go-and-return distance.
)
Step 4: Interface HC-SR04

The circuit connections are made as follows:

The HC-SR04 sensor attach to the Breadboard

The sensor Vcc is connected to the NodeMCU +3.3v


The sensor GND is connected to the NodeMCU GND

The sensor Trigger Pin is connected to the NodeMCU Digital I/O D4

The sensor Echo Pin is connected to the NodeMCU Digital I/O D3

Before you get started with coding you need Arduino IDE.

To download Arduino IDE and for NodeMCU setup, you can check my
previous instructacle.

Interfacing Servo Motor With NodeMCU

Code:
// defines pins numbers

const int trigPin = 2; //D4


const int echoPin = 0; //D3

// defines variables
long duration;

int distance;

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

pinMode(echoPin, INPUT); // Sets the echoPin as an Input

Serial.begin(9600); // Starts the serial communication

void loop() {

// Clears the trigPin

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

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


digitalWrite(trigPin, HIGH);

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

// Reads the echoPin, returns the sound wave travel time in microseconds

duration = pulseIn(echoPin, HIGH);

// Calculating the distance

distance= duration*0.034/2;

// Prints the distance on the Serial Monitor

Serial.print("Distance: ");

Serial.println(distance);

delay(2000);

}
3B)Using Node MCU demonstrate basic LED functionality
Hardware Preparation:
NodeMCU x 1
LED x 1
200 ohm resistor x 1
Micro USB cable x 1
PC x 1
Software Arduino IDE(version 1.6.4+)
Step 1: Blink the On-board LED

In this part,we will learn how to use the Arduino IDE to blink the on-board
LED,the blue led in the board was used to signal the execution of a particular
procedure.Because the GPIO16 (DO) limitation to use the analogWrite() and
looking to see my LED doing something else…

First,connect the NodeMCU to the PC,put below code to the Arduino IDE:

#define LED D0 // Led in NodeMCU at pin GPIO16 (D0).


void setup() {

pinMode(LED, OUTPUT); // LED pin as output.

void loop() {

digitalWrite(LED, HIGH);// turn the LED off.(Note that LOW is the voltage lev
el but actually

//the LED is on; this is because it is acive low on the ESP8266.

delay(1000); // wait for 1 second.

digitalWrite(LED, LOW); // turn the LED on.

delay(1000); // wait for 1 second.

Then config the board settings(choose the corresponding board and port for
your NodeMCU) and upload the sketch to the board.

After upload done,you will see the on-board LED blink every second.
Connect one end of the resistor to the digital pin correspondent to the
LED_BUILTIN constant.

Connect the long leg of the LED (the positive leg, called the anode) to the other
end of the resistor.

Connect the short leg of the LED (the negative leg, called the cathode) to the
GND. In the diagram we show a NodeMCU that has D1 as the LED_BUILTIN
value.

The value of the resistor in series with the LED may be of a different value than
200 ohm; the LED will lit up also with values up to 1K ohm.

Upload below code to your NodeMCU:

#define LED D1 // Led in NodeMCU at pin GPIO16 (D0).


void setup() {

pinMode(LED, OUTPUT); // set the digital pin as output.

void loop() {

digitalWrite(LED, HIGH);// turn the LED off.(Note that LOW is the voltage lev
el but actually

//the LED is on; this is because it is acive low on the ESP8266.

delay(1000); // wait for 1 second.

digitalWrite(LED, LOW); // turn the LED on.

delay(1000); // wait for 1 second.

After the upload done,you will see the led blink .


3C) Using Node MCU calculate temperature using Temperature Sensor

Components Needed:

You need following things for this project :


1x ESP 8266 Nodemcu : https://www.utsource.net/itm/p/7929952.html
1x DHT11 : https://www.utsource.net/itm/p/8831706.html

1x breadboard :. : https://www.utsource.net/itm/p/8031572.html

Few jumpers : https://www.utsource.net/itm/p/9221310.html

Step 2: Circuit

The circuit is very easy connect everything According as shown in schmatics


Step 3: Get the Libraries

Open your Arduino IDE and go to Sketch > Include Library > Manage
Libraries. The Library Manager should open.

Search for “DHT” on the Search box and install the DHT library from Adafruit.

After installing the DHT library from Adafruit, type “Adafruit Unified Sensor”
in the search box. Scroll all the way down to find the library and install it.
After installing the libraries, restart your Arduino IDE.

Step 4: Code

After doing above things upload the following code to ESP8266 nodemcu (
please select proper port & board ) & before uploading the code please put ssid
& password of your wifi in the code :

// Including the ESP8266 WiFi library


#include
#include "DHT.h"

// Uncomment one of the lines below for whatever DHT sensor type you're
using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
// Replace with your network details
const char* ssid = "YOUR_NETWORK_NAME";
const char* password = "YOUR_NETWORK_PASSWORD";

// Web Server on port 80


WiFiServer server(80);

// DHT Sensor
const int DHTPin = 5;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

// Temporary variables
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];

// only runs once on boot


void setup() {
// Initializing serial port for debugging purposes
Serial.begin(115200);
delay(10);

dht.begin();

// Connecting to WiFi network


Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");

// Starting the web server


server.begin();
Serial.println("Web server running. Waiting for the ESP IP...");
delay(10000);
// Printing the ESP IP address
Serial.println(WiFi.localIP());
}

// runs over and over again


void loop() {
// Listenning for new clients
WiFiClient client = server.available();

if (client) {
Serial.println("New client");
// bolean to locate when the http request ends
boolean blank_line = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();

if (c == '\n' && blank_line) {


// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
strcpy(celsiusTemp,"Failed");
strcpy(fahrenheitTemp, "Failed");
strcpy(humidityTemp, "Failed");
}
else{
// Computes temperature values in Celsius + Fahrenheit and Humidity
float hic = dht.computeHeatIndex(t, h, false);
dtostrf(hic, 6, 2, celsiusTemp);
float hif = dht.computeHeatIndex(f, h);
dtostrf(hif, 6, 2, fahrenheitTemp);
dtostrf(h, 6, 2, humidityTemp);
// You can delete the following Serial.print's, it's just for debugging purposes
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.print(" *F");
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t Temperature: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t Heat index: ");
Serial.print(hic);
Serial.print(" *C ");
Serial.print(hif);
Serial.println(" *F");
}
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close");
client.println();
// your actual web page that displays temperature and humidity
client

Step 5: Get the IP

You view the temperature & humidity we need to get the IP of webpage. So for
that make sure your esp8266 is connected to your PC and then open the serial
monitor and on the serial monitor you can see the IP of your ESP8266
webserver webpage.

Step 6: Check Your Temperature & Humidity on the Browser

So after getting the IP of your ESP8266 nodemcu , just open browser in PC or


Mobile but make sure your PC/mobile is connected with same network as your
Nodemcu/ESP8266 and then go to your browser ( if you are using mobile
please use default browser i.e. for Android use chrome ) and then type the IP we
got in previous step and the local webpage will b display with humidity &
temperature as mine shown in image.
So have fun making your room temperature & humidity monitor.
4A) Installation of Raspberry Pi OS using PI imager

Raspberry Pi Imager is free to install from the official Raspberry Pi


website. It is under the download page section of the website. It's
available for MacOS, Windows, Linux and Ubuntu systems.

Visit Raspberry Pi Software section


(https://www.raspberrypi.com/software/)

1. Download the latest version of Raspberry Pi Imager installer for


your Operating System.
2. Run the installer and follow the prompts to complete the setup.

3. Launch the Raspberry Pi Imager executable(exe) from the windows


start menu.

Setup on Linux : From the terminal run the following command:

sudo apt install rpi-imager

Steps to Follow to install pre-defined Images

1. Launch Raspberry Pi Imager.


2. Click Choose OS and choose Raspberry Pi OS.

3. Select an OS from the list of Raspberry Pi OS.


4. Click Choose SD card.

5. Select from the list the SD card you want to write to.
6. Click Write to begin the image writing process.

Steps to install custom images.


In order to utilize any custom images off the web, we must download
the image file before installing custom Raspberry Pi image files (like
.zip, .img, .tar, .gz, etc).

1. Launch Raspberry Pi Imager.

2. Click Choose OS.

3. Select Use custom to write an unlisted image.


4. Click Choose SD card.

5. Select from the list the SD card you want to write to.

6. Click Write to begin the image writing process.

Tutorial: Raspberry Pi Headless Setup


We can use Raspberry Pi Imager to setup a raspberry pi in the headless
mode without the need for additional peripherals such as monitor,
keyboard and mouse. By configuring our Wi-fi credentials and locale
settings into the OS we can use this imaging tool to write the OS onto
the SD card.

Requirements for the setup


1. Find the IP address of the raspberry pi. Windows users can open the
command prompt and Mac users can open the terminal to write the
command in the command line.

Windows: use ifconfig

MacOS: sudo ifconfig

2. Select the operating system image/ open source linux distribution


images from the vast array of images provided in the raspberry Pi
imager

3. Download SSH client (putty) to access the Raspberry Pi from the


main PC via Wi-Fi network
LINK(Putty): https://www.chiark.greenend.org.uk/~sgtatham/putty/lat
est.html

4. Micro sd card reader to read the SD card.

Steps for the Setup


Raspberry Pi Imager Now Comes with Advanced Options
Advanced menu which is hidden away can be activated by pressing
CTRL + SHIFT + X. We gain access to advanced options that enable
advanced users to customize the OS to meet their needs before they
write the software to a microSD card.

Get into the advanced options of the imager using, CTRL + SHIFT +
X. Here, we can disable over scan which is needed for headless setup.

1. Enable SSH and set up a custom Hostname. SSH enables us to


access the raspberry Pi remotely form another computer, with a
monitor.

2. Configure your Wi-Fi, by entering the SSID and password of your


Wi-Fi network and the country. We can also set up our time zone here.

3. Press SAVE and click on write

4. Once the writing is complete plug the SD card into the Raspberry Pi
5A) Accessing GPIO Pins using Python-Installing GPIO Library

Method 1 – Install from repository


If the package exists in the Raspbian repository is can be installed using apt-get.
First you need to update the available package versions :

sudo apt-get update


Then attempt to install the RPi.GPIO package :

sudo apt-get install rpi.gpio


If it isn’t already installed it will be installed. If it is already installed it will be
upgraded if a newer version is available.

Method 2 – Manual Installation


The package is available from http://pypi.python.org/pypi/RPi.GPIO and the
current version is 0.5.11 (February 2015). If this version is updated you will
need to make appropriate changes to the version number in the commands
below.

Step 1 – Download the library


wget https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.11.tar
.gz

Step 2 – Extract the archive to a new folder


tar -xvf RPi.GPIO-0.5.11.tar.gz

Step 3 – Browse to the new directory


cd RPi.GPIO-0.5.11

Step 4 – Install the library


sudo python setup.py install

Step 5 – Remove the directory and archive file


cd ~
sudo rm -rf RPi.GPIO-0.*
This will now mean you can use the library within Python.

Example Usage
1import RPi.GPIO as GPIO
2
3# to use Raspberry Pi board pin numbers
4GPIO.setmode(GPIO.BOARD)
5
6# set up the GPIO channels - one input and one output
7GPIO.setup(11, GPIO.IN)
8GPIO.setup(12, GPIO.OUT)
9
10# input from pin 11
11input_value = GPIO.input(11)
12
13# output to pin 12
14GPIO.output(12, GPIO.HIGH)
15
16# the same script as above but using BCM GPIO 00..nn numbers
17GPIO.setmode(GPIO.BCM)
18GPIO.setup(17, GPIO.IN)
19GPIO.setup(18, GPIO.OUT)
20input_value = GPIO.input(17)
21GPIO.output(18, GPIO.HIGH)
5B) Blinking an LED connected to one of the Pin.

Hardware components

Raspberry Pi 3 Model B × 1

LED (generic) × 1

Resistor 220 ohm × 1

Story

Rapberry Pi

This is the board of raspberry pi. The raspberry pi has 40 pins and it has 26
GPIO pins and 3 power and many other pins.

Here the pin description of Raspberry Pi:-


pin description

LED Blinking using a Raspberry Pi is a simple and popular project for


beginners in the field of electronics and programming. It involves connecting an
LED to one of the GPIO (General Purpose Input/Output) pins of the Raspberry
Pi and controlling its on and off state using Python programming.

Here are the steps to perform LED Blink using a Raspberry Pi

• Gather the required components: Raspberry Pi board, breadboard, LED,


resistor (220 Ohm), jumper wires.
• Connect the LED to the breadboard. Connect the anode (longer leg) of
the LED to the positive rail of the breadboard, and connect the cathode
(shorter leg) of the LED to a 220 Ohm resistor.
• Connect one end of the resistor to the cathode of the LED and the other
end to the negative rail of the breadboard.
• Connect the jumper wires to the GPIO pin of the Raspberry Pi. Use a
female to male jumper wire to connect the positive rail of the
breadboard to the 3.3V pin of the Raspberry Pi. Use another female to
male jumper wire to connect the negative rail of the breadboard to the
GND pin of the Raspberry Pi.
• Connect a male to male jumper wire to the GPIO pin that you want to use
for the LED. Connect the other end of the jumper wire to the anode of
the LED.
• Open the Python editor on the Raspberry Pi and write the Python code to
control the GPIO pin. Here is a sample code to blink an LED connected
to GPIO pin 17:
Save the Python file and run it using the command python
filename.py in the terminal.
• Save the Python file and run it using the command python
filename.py in the terminal.
• The LED connected to the GPIO pin 17 will blink on and off every
second.

Note: Always use a resistor in series with the LED to limit the current flowing
through the LED and prevent it from burning out. Also, be careful while
connecting the components to the Raspberry Pi and follow the proper wiring
diagram to avoid damaging the board.

Schematics
screenshot_(130)_gGocNDzTVQ.png
Code
Code for Led blink
Python
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module

GPIO.setwarnings(False) # Ignore warning for now


GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(18, GPIO.OUT, initial=GPIO.LOW) # Set pin 18 to be an output
pin and set initial value to low (off)

while True: # Run forever


GPIO.output(18, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(18, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second
5C) Adjusting the brightness of an LED from 0 to 100 using built-in PWM
Wavelength

• 2 pushbuttons
• 3 resistors (250-550Ω will work. Use a lower rating if the LED is too
dark.)
• 1 LED (any color)
• Breadboard
• Jumper wires
• Raspberry Pi (any model except the Pi Pico)

How to Use PWM to Control LED Brightness on a Raspberry Pi

In this guide, we are using use two buttons to make the LED shine brighter or
dimmer with PWM. Pressing the "brighter" button increases the PWM output,
while pressing the "dimmer" button decreases it.

Preparing the Circuit

1. Let's start with the LED. On the breadboard, place the LED and connect a
resistor to one side. The side the resistor is placed does not matter.
2. Connect a jumper to its cathode side. This one will point to pin 11 on the
Raspberry Pi. Add another jumper that leads to the blue rail on the
breadboard, then add another jumper from that blue rail to pin 9 on the
Raspberry Pi, which is GND.

Note: to find the right pin number on the Raspberry Pi, hold the board so that
the GPIO pin tray sits to the right. The top-left pin should be pin 1, to its right
should be pin 2, and below should be pin 3.
3. You'll need to build the pushbuttons. Place the pushbuttons on the
breadboard and add a resistor to one leg of each pushbutton. The other
side of the resistor should lead to the blue rail of the breadboard.

Tip: want to know more about pushbuttons? We have a full guide dedicated to
showing you how to use pushbuttons with Raspberry Pi GPIO pins.

4. Add jumper wires in a parallel connection with the resistor and


pushbutton. Connect the other side of these to pins 13 ("Brighter" button)
and 15 ("Dimmer" button).
5. Use a jumper wire to connect the pushbuttons to the side with the red rail
of the breadboard.
6. Connect the red rail to a 3.3V source on the Raspberry Pi, like pin 1.

If Python is your go-to programming language, learn how to install and manage
multiple Python versions in Linux.

Preparing the Code

On your favorite code-editing tool, make a new file and save it as "rpi-
lcdpwm.py."

1. Start with the code below, which gives you two ways of importing
modules on Python: the first imports the RPi.GPIO module and lets you
call it with just GPIO , and the second one imports only
the sleep() function from the entirety of the time module.

import RPi.GPIO as GPIO


from time import sleep

2. Define the pin numbers to make it easier to change pins in case you
change your mind later on.
ledPin = 11
brightenButton = 13
dimButton = 15

3. Optional: add the line GPIO.setwarnings(False) so that you can avoid


the GPIO warning message when you start the script later.

4. Set the pin selection method. BOARD is a good choice for beginners, as
it makes it easier to look for pins without having to consult the pinout.
The other method is BCM , which stands for "Broadcom." This uses the
Broadcom numbers assigned to each pin, which may differ based on your
Raspberry Pi's make.

GPIO.setmode(GPIO.BOARD)

5. Assign the GPIO pins as input or output. We're assigning ledPin as an


output pin and will always start its state as LOW . The next two lines
set brightenButton and dimButton as input pins that listen to your
button pushes. These should also be set as GPIO.PUD_DOWN to
designate them as using pulldown resistors.

GPIO.setup(ledPin, GPIO.OUT, initial=GPIO.LOW)


GPIO.setup(brightenButton, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(dimButton, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

6. Let's declare the PWM. pwmLEDPin is a variable that makes it easier to


type GPIO.PWM(ledPin, 100) later on, and the .start(0) command
begins the PWM process. We can now change the output of ledPin using
PWM.

pwmLEDPin = GPIO.PWM(ledPin, 100)


pwmLEDPin.start(0)
7. The duty cycle is the percentage of time that the pin is active during a
pulse wave. Here, we're setting the duty cycle to 100% first. We had a
rather lengthy discussion on this topic in our guide to using servo motors
with the Raspberry Pi, if you're interested.

dutyCycle = 100
GPIO.output(ledPin, GPIO.HIGH)

8. For the looping part, we are setting a while loop that runs virtually
forever.

while True:

9. At the beginning of this looping cycle, we are updating the duty cycle.

pwmLEDPin.ChangeDutyCycle(dutyCycle)

10.Let's program what the brightenButton does. When the Raspberry


detects electricity passing through the pin for brightenButton , it will
show a message that says "brightenButton is HIGH," which adds 5 to the
current value of the duty cycle until it reaches 100.

if GPIO.input(brightenButton) == GPIO.HIGH:
print("brightenButton is HIGH")
if dutyCycle < 100:
dutyCycle += 5
sleep(0.25)
else: dutyCycle = 100

11.When programming the dimButton function, it does the opposite,


reducing the value by 5 until it reaches 0.

elif GPIO.input(dimButton) == GPIO.HIGH:


print("dimButton is HIGH")
if dutyCycle > 0:
dutyCycle -= 5
sleep(0.25)
else: dutyCycle = 0

Final Code:

import RPi.GPIO as GPIO


from time import sleep

ledPin = 11
brightenButton = 13
dimButton = 15

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledPin, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(brightenButton, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(dimButton, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
pwmLEDPin = GPIO.PWM(ledPin, 100)
pwmLEDPin.start(0)
dutyCycle = 100
GPIO.output(ledPin, GPIO.HIGH)

while True:
pwmLEDPin.ChangeDutyCycle(dutyCycle)
if GPIO.input(brightenButton) == GPIO.HIGH:
print("brightenButton is HIGH")
if dutyCycle < 100:
dutyCycle += 5
sleep(0.25)
else: dutyCycle = 100
elif GPIO.input(dimButton) == GPIO.HIGH:
print("dimButton is HIGH")
if dutyCycle > 0:
dutyCycle -= 5
sleep(0.25)
else: dutyCycle = 0

Making It Work

First, you'll need a terminal. You can use the Raspberry Pi's built-in terminal
or control the Raspberry Pi through SSH on a separate computer. Through the
terminal, you should go to the Python script's directory and enter python3 rpi-
ledpwm.py or the filename you used.

Sometimes the LED will look like it's blinking. The PWM frequency is
probably too low, if that's the case. You can increase the frequency by
increasing the number in pwmLEDPin = GPIO.PWM(ledPin, 100) until the
blinking is no longer noticeable.

If you find the transitions to be grainy, lower the time in sleep(0.25) inside the
while loop. It does get faster as you lower it, though, so don't lower it too much.
6A) DHT11 Interfacing with Raspberry Pi

Overview of DHT11 Sensor

DHT11 Sensor
• DHT11 sensor measures and provides humidity and temperature values
serially over a single wire.
• It can measure relative humidity in percentage (20 to 90% RH) and
temperature in degree Celsius in the range of 0 to 50°C.
• It has 4 pins; one of which is used for data communication in serial form.
• Pulses of different TON and TOFF are decoded as logic 1 or logic 0 or
start pulse or end of a frame.

For more information about the DHT11 sensor and how to use it, refer the
topic DHT11 sensor in the sensors and modules topic.
Connection Diagram of DHT11 with Raspberry Pi

DHT11 Interfacing with Raspberry Pi 3


Read Temperature and Humidity using DHT11 and Raspberry Pi

• Here, we are going to interface the DHT11 sensor with Raspberry Pi 3


and display Humidity and Temperature on the terminal.
• We will be using the DHT Sensor Python library by Adafruit from
GitHub. The Adafruit Python DHT Sensor library is created to read the
Humidity and Temperature on Raspberry Pi or Beaglebone Black. It is
developed for DHT series sensors like DHT11, DHT22, or AM2302.

Download Adafruit DHT Sensor library from here.

• Extract the library and install it in the same root directory of the
downloaded library by executing the following command,

sudo python setup.py install

• Once the library and its dependencies have been installed, open the
example sketch named simpletest from the library kept in the examples
folder.
• In this code, raspberry Pi reads Humidity and Temperature from the
DHT11 sensor and prints them on the terminal. But, it read and displays
the value only once. So, here we made a change in the program to print
value continuously.

Note:

• Assign proper sensor type to the sensor variable in this library. Here, we
are using DHT11 sensor.

sensor = Adafruit_DHT.DHT11

• If anyone is using sensor DHT22 then we need to


assign Adafruit_DHT.DHT22 to the sensor variable shown above.
• Also, comment out the Beaglebone pin definition and uncomment pin
declaration for Raspberry Pi.
• Then assign pin no. to which the DHT sensor’s data pin is connected.
Here, data out of the DHT11 sensor is connected to GPIO4. As shown in
the above interfacing diagram.

DHT11 Python Program for Raspberry Pi


#!/usr/bin/python

# Copyright (c) 2014 Adafruit Industries


# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy


# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF A


NY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. I
N NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OT
HERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE O
R OTHER DEALINGS IN THE
# SOFTWARE.
import Adafruit_DHT

# Sensor should be set to Adafruit_DHT.DHT11,


# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11

# Example using a Beaglebone Black with DHT sensor


# connected to pin P8_11.
#pin = 'P8_11'

# Example using a Raspberry Pi with DHT sensor


# connected to GPIO4.
pin = 4

# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
while True:
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity
))

'''

# Note that sometimes you won't get a reading and

# the results will be null (because Linux can't

# guarantee the timing of calls to read the sensor).

# If this happens try again!

if humidity is not None and temperature is not None:

print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity


))

else:

print('Failed to get reading. Try again!')

'''
DHT11 Output
7) Webcam server with auto surveillance

Aim: Interfacing the regular USB webcam with the device and turn it into fully functional IP
webcam & test the functionality.

Components:

Raspberry pi

Usb webcam

LAN cable (RJ 45 cable)

Power source (5v 2A)

Procedure:

• Insert the SD card in the Pi.


• Connect the USB camera to any of the available four ports.
• Connect the LAN cable to your pi and another end to your router
• Power up the raspberry pi.

• Open the desktop of Raspbian and connect to WiFi by putting the correct password.

• When the raspbian is connected to the network by WiFi, then shut down the system.

• Now detach the LAN cable and restart. Then you must be connected to the Internet
via WiFi only.

• This will help to move your webcam and the pi anywhere without the RJ-45 cable.
Know your raspberry pi IP address.

Do the following steps to view Pi IP address.


1. Open your browser on laptop or mobile. ( laptop or mobile has to be in the same
network as the pi ).
2. Go to your Router settings by typing in the default IP address of your router. (
written somewhere on your router. )
3. Find the list of connected devices.
4. Find the corresponding IP address of the device named raspberry.
5. In our case, it is 192.168.0.107.

Connect to Your Pi by SSH Connection ( PUTTY )

Open up Putty and type in the IP address of your Pi and connect.

'pi' & 'raspberry' is the default 'login as' and 'password' in Raspbian

It is always a good practice to Update and Upgrade the system as soon as you log in.

To do it, type in the command 'sudo apt-get update' and 'sudo apt-get upgrade' one at a
time.

Install the Software and Do the Necessary Settings


Type in the command 'sudo apt-get install motion ' to start the installation.

Now to make sure that the camera is correctly detected.

Type in the command 'lsusb' and enter. You should see the name of your camera. If it is NOT
there, then there is some problem in your camera or the camera is not supported in 'motion'.

After the installation is complete, type in the command ' sudo nano /etc/motion/motion.conf
' and press enter.

Then you have to change some settings in the .conf file. It might be difficult sometimes to find
the settings but use 'ctrl + w' to find it. So follow the steps:

1. Make sure 'daemon' is ON.


2. Set 'framerate' anywhere in between 1000 to 1500.
3. Keep 'Stream_port' to 8081.
4. 'Stream_quality' should be 100.
5. Change 'Stream_localhost' to OFF.
6. Change 'webcontrol_localhost' to OFF.
7. Set 'quality' to 100.
8. Set 'width' & 'height' to 640 & 480.
9. Set 'post_capture' to 5.
10. Press ctrl + x to exit. Type y to save and enter to conform.

Again type in the command 'sudo nano /etc/default/motion ' and press enter.

Set ' start_motion_daemon ' to yes. Save and exit.

Start the Server


First of all your have to restart the motion software. To do it type in the command 'sudo
service motion restart' and press enter.

Again type in the command 'sudo motion' and press enter. Now your server is ready.

Output:
Now open up your browser. Type in the IP address of your raspberry Pi and the port number in
this way:

192.168.0.107:8081 (First there is the IP address, then a ':', then the port number). Press
Enter.

Now you can see the Live feed coming from your webcam directly on your laptop or
mobile or both at the same time.

You might also like