Wa0002.
Wa0002.
Prepared by
D. Chaithanya
Assistant Professor
VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE
DEPARTMENT OF INFORMATION TECHNOLOGY
VISION
MISSION
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:
Type the following commands to get the source code and execute a Python script that displays
the distance:
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
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.
Once you have added all the code and checked it, save and exit the text editor
with “Ctrl + x” then “y” then “enter”.
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:
Circuit Diagram:
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).
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
long duration; // Variable to store time taken to the pulse// to reach receiver
void setup()
pinMode(trigPin,
// baudrate speed
Serial.begin(9600);
Serial.println(
delay(500);
void loop()
digitalWrite(trigPin, LOW);
trigPin,
digitalWrite(trigPin,
// pulse generation
// receiver
distance
Serial.print("Distance: ");
Serial.print(
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
• 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 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 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
• 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 −
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
Hardware Requirements
• NodeMCU
• HC-SR04 (Ultra-sonic Sensor)
• Bread Board
• Jumper Wires
• Micro USB Cable
Software Requirements
• Arduino IDE
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
Before you get started with coding you need Arduino IDE.
To download Arduino IDE and for NodeMCU setup, you can check my
previous instructacle.
Code:
// defines pins numbers
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
distance= duration*0.034/2;
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:
void loop() {
digitalWrite(LED, HIGH);// turn the LED off.(Note that LOW is the voltage lev
el but actually
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.
void loop() {
digitalWrite(LED, HIGH);// turn the LED off.(Note that LOW is the voltage lev
el but actually
Components Needed:
1x breadboard :. : https://www.utsource.net/itm/p/8031572.html
Step 2: Circuit
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 :
// 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";
// 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];
dht.begin();
WiFi.begin(ssid, password);
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();
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.
5. Select from the list the SD card you want to write to.
6. Click Write to begin the image writing process.
5. Select from the list the SD card you want to write to.
Get into the advanced options of the imager using, CTRL + SHIFT +
X. Here, we can disable over scan which is needed for headless setup.
4. Once the writing is complete plug the SD card into the Raspberry Pi
5A) Accessing GPIO Pins using Python-Installing GPIO Library
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
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.
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
• 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)
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.
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.
If Python is your go-to programming language, learn how to install and manage
multiple Python versions in Linux.
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.
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
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)
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)
if GPIO.input(brightenButton) == GPIO.HIGH:
print("brightenButton is HIGH")
if dutyCycle < 100:
dutyCycle += 5
sleep(0.25)
else: dutyCycle = 100
Final Code:
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
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
• Extract the library and install it in the same root directory of the
downloaded library by executing the following command,
• 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
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 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
))
'''
else:
'''
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
Procedure:
• 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.
'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.
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:
Again type in the command 'sudo nano /etc/default/motion ' 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.