Practical 1
Practical 1
No Name
7 IR Sensor
 13
        MPU6050 (Accelerometer+Gyroscope) Interfacing with Raspberry Pi
                                                                          1
     14        Raspberry Pi IR Sensor Interface
The DHT11 has a sampling rate of 1Hz, which means it can provide new data once
every second.
                                                                                     2
DHT11 sensors typically require an external 10K pull-up resistor on the output pin for
proper communication between the sensor and the Arduino. However, because the
module already includes a pull-up resistor, you do not need to add one. The module
also includes a decoupling capacitor for filtering power supply noise.
Inside the DHT11 Sensor
If you remove the sensor’s casing, you will find an NTC thermistor and a humidity
sensing component inside.
The humidity sensing component has two electrodes with a moisture-holding substrate
(usually a salt or conductive plastic polymer) in between. As the humidity rises, the
substrate absorbs water vapor, resulting in the release of ions and a decrease in the
resistance between the two electrodes. This change in resistance is proportional to the
humidity, which can be measured to estimate relative humidity.
                                                                                      3
Technically, all resistors are thermistors in the sense that their resistance changes
slightly with temperature, but this change is typically very small and difficult to measure.
Thermistors are designed so that their resistance changes dramatically with
temperature (by 100 ohms or more per degree). The term “NTC” stands for “Negative
Temperature Coefficient,” which means that resistance decreases as temperature rises.
The sensor also includes an 8-bit SOIC-14 packaged IC. This IC measures and
processes the analog signal using stored calibration coefficients, converts the analog
signal to digital, and outputs a digital signal containing the temperature and humidity.
+ (VCC) pin provides power to the sensor. Despite the fact that the supply voltage of the
module ranges from 3.3V to 5.5V, a 5V supply is recommended. With a 5V power
supply, the sensor can be placed up to 20 meters away. With 3.3V supply voltage, the
sensor can be placed just 1 meter away; otherwise, the line voltage drop will cause
measurement errors.
Out pin is used for communication between the sensor and the microcontroller.
                                                                                          4
Wiring DHT11 Module to Arduino
Begin by connecting the + (VCC) pin to the Arduino’s 5V output and the – (GND) pin to
ground. Finally, connect the Out pin to digital pin #8.
The diagram below shows how to connect everything.
void setup() {
         Serial.begin(9600);
}
void loop() {
         int readData = DHT.read11(outPin);
        Serial.print("Temperature = ");
        Serial.print(t);
        Serial.print("°C | ");
        Serial.print((t*9.0)/5.0+32.0);   // Convert celsius to fahrenheit
        Serial.println("°F ");
        Serial.print("Humidity = ");
        Serial.print(h);
        Serial.println("% ");
        Serial.println("");
                                                                                    5
        delay(2000); // wait two seconds
}
After uploading the sketch, you should see the following output on the serial monitor.
Code Explanation:
The sketch begins by including the DHT library. Following that, we specify the Arduino
pin number to which our sensor’s Data pin is connected and create a DHT object.
#include <dht.h>
#define outPin 8
dht DHT;
In the setup, we initialize the serial communication.
void setup() {
  Serial.begin(9600);
}
In the loop, we use the read11() function to read the DHT11 module. This function takes
as a parameter the sensor’s Data pin number.
int readData = DHT.read11(outPin);
We can now retrieve the humidity and temperature values by accessing the DHT
object’s properties using dot . notation.
float t = DHT.temperature;       // Read temperature
float h = DHT.humidity;        // Read humidity
The DHT object returns the temperature in degrees Celsius (°C). It is easy to convert to
Fahrenheit (°F) using the following formula:
                                                                                         6
T(°F) = T(°C) × 9/5 + 32
Serial.print((t * 9.0) / 5.0 + 32.0);
we will learn how the HC-SR04 ultrasonic sensor works and how to use it
with Arduino
The HC-SR04 is an affordable and easy to use distance measuring sensor which has a
range from 2cm to 400cm (about an inch to 13 feet).
The sensor is composed of two ultrasonic transducers. One is transmitter which outputs
ultrasonic sound pulses and the other is receiver which listens for reflected waves. It’s
basically a SONAR which is used in submarines for detecting underwater objects.
Operating Voltage 5V DC
Accuracy 3mm
Dimension 45 x 20 x 5mm
                                                                                        7
HC-SR04 Ultrasonic Sensor Pinout
Here’s the pinout of the sensor:
The sensor has 4 pins. VCC and GND go to 5V and GND pins on the Arduino, and
the Trig and Echo go to any digital Arduino pin. Using the Trig pin we send the
ultrasound wave from the transmitter, and with the Echo pin we listen for the reflected
signal.
It emits an ultrasound at 40 000 Hz which travels through the air and if there is an object
or obstacle on its path It will bounce back to the module. Considering the travel time and
the speed of the sound you can calculate the distance.
                                                                                          8
In order to generate the ultrasound we need to set the Trig pin on a High State for 10
µs. That will send out an 8 cycle ultrasonic burst which will travel at the speed of sound.
The Echo pins goes high right away after that 8 cycle ultrasonic burst is sent, and it
starts listening or waiting for that wave to be reflected from an object. If there is no
object or reflected pulse, the Echo pin will time-out after 38ms and get back to low state.
If we receive a reflected pulse, the Echo pin will go down sooner than those 38ms.
According to the amount of time the Echo pin was HIGH, we can determine the distance
the sound wave travelled, thus the distance from the sensor to the object.
For that purpose, we are using the following basic formula for calculating distance:
The time is the amount of time the Echo pin was HIGH, and the speed is the speed of
sound which is 340m/s. There’s one additional step we need to do, and that’s divide the
end result by 2. and that’s because we are measuring the duration the sound wave
needs to travel to the object and bounce back.
                                                                                         9
Let’s say the Echo pin was HIGH for 2ms. If we want the get the distance result in cm,
we can convert the speed of sound value from 340m/s to 34cm/ms.
Distance = (Speed x Time) / 2 = (34cm/ms x 1.5ms) / 2 = 25.5cm.
So, if the Echo pin was HIGH for 2ms (which we measure using the pulseIn() function),
the distance from the sensor to the object is 34cm.
                                                                                   10
The Ground and the VCC pins of the module needs to be connected to the Ground and
the 5 volts pins on the Arduino Board respectively and the trig and echo pins to any
Digital I/O pin on the Arduino Board. HC-SR04 Ultrasonic Sensor Arduino Code. Here’s
a code for measuring distance using the HC-SR04 ultrasonic sensor and Arduino.
/*
  Ultrasonic Sensor HC-SR04 and Arduino Tutorial
 by Dejan Nedelkovski,
 www.HowToMechatronics.com
*/
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
// 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);
}
Code Explanation
First we have to define the Trig and Echo pins. In this case they are the pins number 9
and 10 on the Arduino Board and they are named trigPin and echoPin. Then we need a
Long variable, named “duration” for the travel time that we will get from the sensor and
an integer variable for the distance.
                                                                                      11
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;Code language: Arduino (arduino)
In the setup we have to define the trigPin as an output and the echoPin as an Input and
also start the serial communication for showing the results on the serial monitor.
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
}
In the loop first we have to make sure that the trigPin is clear so you have to set that pin
on a LOW State for just 2 µs. Now for generating the Ultra sound wave we have to set
the trigPin on HIGH State for 10 µs.
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
                                                                                         12
13
               Interface Smoke & Gas Sensor Module with Arduino
The MQ2 gas sensor operates on 5V DC and consumes approximately 800mW. It can
detect LPG, Smoke, Alcohol, Propane, Hydrogen, Methane and Carbon
Monoxide concentrations ranging from 200 to 10000 ppm.
Parts-per-million, or ppm for short, is the most commonly used unit for measuring gas
concentration. ppm is simply the ratio of one gas to another. For example, 500ppm of
carbon monoxide means that if you could count a million gas molecules, 500 would be
carbon monoxide and the remaining 999500 would be other gasses.
MQ2 gas sensor detects multiple gases, but cannot identify them! That is normal; most
gas sensors operate in this manner. Therefore, it is best suited for measuring changes
in a known gas density rather than detecting which one is changing.
                                                                                        14
element inside the sensor does not cause an explosion because we are sensing
flammable gasses.
It also protects the sensor and filters out suspended particles, allowing only gaseous
elements to pass through the chamber. A copper-plated clamping ring secures the
mesh to the rest of the body.
When the outer mesh is removed, the sensor looks like this. The sensing element and
six connecting legs that extend beyond the Bakelite base form the star-shaped
structure. Two (H) of the six leads are in charge of heating the sensing element and are
linked together by a Nickel-Chromium coil (a well-known conductive alloy).
The remaining four signal-carrying leads (A and B) are connected with platinum wires.
These wires are connected to the body of the sensing element and convey slight
variations in the current flowing through the sensing element.
The tubular sensing element is made of Aluminum Oxide (AL2O3) based ceramic with a
Tin Dioxide coating (SnO2). Tin Dioxide is the most important material because it is
                                                                                     15
sensitive to combustible gasses. The ceramic substrate, on the other hand, improves
heating efficiency and ensures that the sensor area is continuously heated to the
working temperature.
In the presence of reducing gasses, however, the surface density of adsorbed oxygen
decreases as it reacts with the reducing gasses, lowering the potential barrier. As a
result, electrons are released into the tin dioxide, allowing current to freely flow through
the sensor.
                                                                                         16
The sensor’s analog output voltage (at the A0 pin) varies in proportion to the
concentration of smoke/gas. The higher the concentration, the higher the output
voltage; the lower the concentration, the lower the output voltage. The animation below
shows the relationship between gas concentration and output voltage.
This analog signal is digitized by an LM393 High Precision Comparator and made
available at the Digital Output (D0) pin.
The module includes a potentiometer for adjusting the sensitivity of the digital output
(D0). You can use it to set a threshold so that when the gas concentration exceeds the
threshold value, the module outputs LOW otherwise HIGH. In addition, the module has
two LEDs. The Power LED illuminates when the module is turned on, and the Status
LED illuminates when the gas concentration exceeds the threshold value.
                                                                                     17
Technical Specifications
Operating voltage 5V
Load resistance 20 KΩ
Sensing Resistance 10 KΩ – 60 KΩ
VCC supplies power to the module. Connect it to the 5V output of your Arduino.
D0 indicates the presence of combustible gasses. D0 becomes LOW when the gas
concentration exceeds the threshold value (as set by the potentiometer), and HIGH
otherwise.
                                                                                        18
When first used after a long period of storage (a month or more), the sensor must be
fully warmed up for 24-48 hours to ensure maximum accuracy.
If the sensor has recently been used, it will only take 5-10 minutes to fully warm up.
During the warm-up period, the sensor typically reads high and gradually decreases
until it stabilizes.
Experiment 1 – Measuring Gas Concentration using Analog Output (A0)
In our first experiment, we will read the analog output to determine the concentration of
the gas and see if it is within acceptable limits.
Wiring
Let us connect the MQ2 gas sensor to the Arduino.
Begin by connecting the VCC pin to the Arduino’s 5V pin and the GND pin to the
Arduino’s Ground pin. Finally, connect the module’s A0 output pin to Analog pin #0 on
the Arduino.
The following image shows the wiring.
#define MQ2pin 0
void setup() {
         Serial.begin(9600); // sets the serial port to 9600
         Serial.println("MQ2 warming up!");
         delay(20000); // allow the MQ2 to warm up
                                                                                      19
}
void loop() {
         sensorValue = analogRead(MQ2pin); // read analog input pin 0
Arduino Code
The sketch below determines whether the gas concentration is within acceptable limits.
#define MQ2pin 0
void setup() {
         Serial.begin(9600); // sets the serial port to 9600
         Serial.println("MQ2 warming up!");
         delay(20000); // allow the MQ2 to warm up
}
void loop() {
 sensorValue = analogRead(MQ2pin); // read analog input pin 0
    Serial.println("");
    delay(2000); // wait 2s for next reading
}
                                                                                     20
Detecting the Presence of Smoke/Gas using Digital Output (D0)
In our second experiment, we will use digital output to detect the presence of
smoke/gas.
Wiring
We’ll reuse the previous experiment’s circuit. Simply disconnect the connection to the
ADC pin and connect the D0 pin on the module to the Arduino’s digital pin #8.
                                                                                    21
Setting the threshold
The module has a built-in potentiometer for setting the gas concentration threshold
above which the module outputs LOW and the status LED lights up.
Now, to set the threshold, place the gas sensor near the smoke/gas you want to detect
and turn the pot until the Status LED begins to glow. Then, turn the pot the other way
just until the LED goes off.
Arduino Code
Now, upload the sketch below to your Arduino.
#define MQ2pin 8
int sensorValue; //variable to store sensor value
void setup() {
         Serial.begin(9600); // sets the serial port to 9600
         Serial.println("MQ2 warming up!");
         delay(20000); // allow the MQ2 to warm up
}
void loop() {
         sensorValue = digitalRead(MQ2pin); // read digital output pin
         Serial.print("Digital Output: ");
         Serial.print(sensorValue);
                                                                                    22
                           Interface PIR Module with Arduino
Whether you want to build a home burglar alarm or a trail camera, or perhaps you want
to wake up animated Halloween props when trick-or-treaters come to your door, then
you should definitely consider getting an HC-SR501 Passive Infrared (PIR) sensor for
yourself.
The PIR sensor allows you to detect when a person or animal moves in or out of sensor
range. This sensor is what you’ll find in most modern security systems, automatic light
switches, garage door openers and similar applications where we want to react to
motion.
Before getting into the nitty-gritty, let’s first understand how a PIR sensor actually works.
                                                                                           23
A PIR sensor consists of two main parts:
   1. A pyroelectric sensor, which you can see in the image below as a round metal
      with a rectangular crystal in the center.
   2. A special lens called a fresnel lens which Focuses the infrared signals on the
      pyroelectric sensor.
When there is no movement around the sensor, both slots detect the same amount of
infrared radiation, resulting in a zero output signal.
But when a warm body like a human or an animal passes by, it first intercepts half of the
sensor. This causes a positive differential change between the two halves. When the
warm body intercepts the other half of the sensor (leaves the sensing region), the
opposite happens, and the sensor produces a negative differential change. By reading
this change in voltage, motion is detected.
                                                                                       24
The Fresnel Lens
You may feel that the Fresnel lens used here is not really doing anything. In fact, this is
what increases the range and field of view of the PIR sensor. Its slim, lightweight
construction and excellent light gathering capability make it extremely useful for making
PIRs small in size yet powerful.
A Fresnel lens consists of a series of concentric grooves carved into the plastic. These
contours act as individual refracting surfaces, gathering parallel light rays at a focal
point. As a result a Fresnel lens, although smaller in size, is able to focus light similarly
to a conventional optical lens.
In reality, to increase the range and field of view of the PIR sensor, the lens is divided
into several facet-sections, each section of which is a separate Fresnel lens.
                                                                                          25
HC-SR501 PIR Sensor Hardware Overview
For most of our Arduino projects that require detecting whether someone has left or
entered the area, the HC-SR501 PIR sensor is a great choice. It is low power, low cost,
easy to interface and extremely popular among hobbyists.
This PIR sensor itself is pretty straightforward and works out of the box. Simply apply
power 5V – 12V and ground. The sensor output goes HIGH when motion is detected
and goes LOW when idle (no motion detected).
By connecting this output to the microcontroller, you can react to motion by turning
lights ON/OFF, enabling a fan, enabling a Halloween prop, or perhaps taking a picture
of an intruder.
And the best part is that it consumes less than 2mA of current and can detect motion up
to 7 meters (21 ft) with sensitivity control.
BISS0001 PIR Controller
At the heart of the module is a passive infrared (PIR) controller IC – BISS0001.
Because of the noise immunity it provides, the BISS0001 is one of the most stable PIR
controllers available.
This chip takes the output from the Pyroelectric sensor and does some minor
processing on it to emit a digital output pulse.
                                                                                     26
Power
The module comes with a 3.3V precision voltage regulator, so it can be powered by any
DC voltage from 4.5 to 12 volts, although 5V is commonly used. The module comes
with a protection diode (also known as a safety diode) to protect the module from
reverse voltage and current. So even if you accidentally connect the power with
incorrect polarity, your module will not be damaged.
Sensitivity Adjustment
The PIR sensor has a potentiometer on the back to adjust the sensitivity.
This potentiometer sets the maximum detection range. Sensitivity can be adjusted over
a range of approximately 3 meters to 7 meters (9 to 21 feet). However the topology of
your room can affect the actual range you get. Rotating the pot clockwise will increase
the sensitivity and thus the range, and vice versa.
Time-Delay Adjustment
There is another potentiometer on the back of the PIR sensor to adjust the Time-Delay.
This potentiometer sets how long the output will remain HIGH after motion is detected. It
can be adjusted from 1 second to about 3 minutes. Turning the potentiometer clockwise
increases the delay, while turning the potentiometer counter-clockwise decreases the
delay.
                                                                                      27
Trigger Selection Jumper
There are two trigger modes that determine how the sensor will react when motion is
detected.
Single Trigger Mode: The constant motion will cause a single trigger.
Multiple Trigger Mode: The constant motion will cause a series of triggers.
The board comes with a berg jumper (some modules have a solder bridge jumper)
allowing you to choose one of two modes:
L – Selecting this will set the single trigger mode. In this mode the output goes HIGH as
soon as motion is detected and remains HIGH for a period determined by the Time-
Delay potentiometer. Further detection is blocked until the output returns to LOW at the
end of the time delay. If there is still motion, the output will go HIGH again. As you can
see in the image below, Motion #3 is completely ignored.
H – Selecting this will set the multiple trigger mode. In this mode the output goes HIGH
as soon as motion is detected and remains HIGH for a period determined by the Time-
Delay potentiometer. Unlike single trigger mode, further detection is not blocked, so the
time delay is reset each time motion is detected. Once the motion stops, the output
returns to LOW only after a time delay. Hence the name multiple trigger mode.
                                                                                       28
RT – This connection is for a thermistor or temperature-sensitive resistor. Adding this
allows the HC-SR501 to be used in extreme temperatures. This also increases the
accuracy of the detector to some extent.
RL – This connection is for Light Dependent Resistor (LDR) or Photoresistor. Adding
this component allows the HC-SR501 to operate in the dark. This is useful for building
motion-sensitive lighting systems.
These additional components can be soldered directly to the module or extended to
remote locations using wires and connectors.
Technical Specifications
Here are the specifications:
                 Operating Voltage             4.5 – 20V (typically 5V)
                                                                                     29
VCC is the power supply for the sensor. You can connect an input voltage anywhere
between 5 to 12V to this pin, although 5V is commonly used.
Output pin is the 3.3V TTL logic output. It goes HIGH when motion is detected and goes
LOW when idle (no motion detected).
Remember that once you power up the circuit you need to wait 30-60 seconds for the
PIR to adapt to the infrared energy in the room. The LED may blink a bit during that
time. Wait until the LED is completely off and then walk around in front of it or wave a
hand and watch the LED light up accordingly.
This PIR output can be connected directly to a relay module if you want to turn
something ON/OFF based on motion.
Wiring a PIR Sensor to an Arduino
Now that we have a complete understanding of how the PIR sensor works, we can start
connecting it to our Arduino!
Connecting the PIR sensor to the Arduino is really simple. Power the PIR with 5V and
connect ground to ground. The PIR acts as a digital output, so all you have to do is
listen to the output pin. So connect the output to Arduino’s digital pin #8.
For the HC-SR501 to function correctly, set the jumper to the H (Multiple Trigger Mode)
position. You will also need to set the Time-Delay to at least 3 seconds, turn the Time-
                                                                                        30
Delay potentiometer counterclockwise as far as it will go. Finally set the sensitivity
potentiometer to any position you like or, if you are not sure, set it to the midpoint.
The following table lists the pin connections:
                           HC-SR501       PIR
                                                 Arduino
                           Sensor
VCC 5V
GND GND
OUT 8
The image below shows how to connect HC-SR501 PIR sensor to the Arduino.
Now you are ready to upload some code and get the PIR working.
Arduino Example Code
The code is very simple. It basically just keeps track of whether the input to pin #8 is
HIGH or LOW.
int ledPin = 13;             // choose the pin for the LED
int inputPin = 8;            // choose the input pin (for PIR sensor)
int pirState = LOW;             // we start, assuming no motion detected
int val = 0;              // variable for reading the pin status
void setup() {
 pinMode(ledPin, OUTPUT);           // declare LED as output
 pinMode(inputPin, INPUT);        // declare sensor as input
    Serial.begin(9600);
}
void loop(){
                                                                                      31
 val = digitalRead(inputPin); // read input value
   if (val == HIGH)         // check if the input is HIGH
 {
   digitalWrite(ledPin, HIGH); // turn LED ON
   if (pirState == LOW)
           {
     Serial.println("Motion detected!");       // print on output change
     pirState = HIGH;
   }
 }
 else
 {
   digitalWrite(ledPin, LOW); // turn LED OFF
   if (pirState == HIGH) {
     Serial.println("Motion ended!");// print on output change
     pirState = LOW;
   }
 }
}
With the sensor pointing up, swipe your hand over the sensor. You should see a
“Motion Detected” message printed on the serial terminal.
                                                                            32
                Interface Soil Moisture Sensor Module with Arduino
When you hear the term “smart garden,” one of the first things that comes to mind is a
system that monitors the moisture level of the soil and automatically supplies the
necessary amount of water to the plants. With this system, plants can be watered only
when required, avoiding over- or under-watering. If you want to build such a system,
you will undoubtedly require a Soil Moisture Sensor.
How Does a Soil Moisture Sensor Work?
The soil moisture sensor operates in a straightforward manner. The fork-shaped probe
with two exposed conductors acts as a variable resistor (similar to a potentiometer)
whose resistance varies with the soil’s moisture content.
Hardware Overview
A typical soil moisture sensor consists of two parts.
The Probe
The sensor includes a fork-shaped probe with two exposed conductors that is inserted
into the soil or wherever the moisture content is to be measured.
                                                                                    33
As previously stated, it acts as a variable resistor, with resistance varying according to
soil moisture.
The Module
In addition, the sensor includes an electronic module that connects the probe to the
Arduino.
The module generates an output voltage based on the resistance of the probe, which is
available at an Analog Output (AO) pin.
The same signal is fed to an LM393 High Precision Comparator, which digitizes it and
makes it available at a Digital Output (DO) pin.
The module includes a potentiometer for adjusting the sensitivity of the digital output
(DO).
You can use it to set a threshold, so that when the soil moisture level exceeds the
threshold, the module outputs LOW otherwise HIGH.
This setup is very useful for triggering an action when a certain threshold is reached.
For example, if the moisture level in the soil exceeds a certain threshold, you can
activate a relay to start watering the plant.
Rotate the knob clockwise to increase sensitivity and counterclockwise to decrease it.
                                                                                         34
The module also includes two LEDs. The Power LED illuminates when the module is
turned on, and the Status LED illuminates when the soil moisture level exceeds the
threshold value.
Soil Moisture Sensor Pinout
The soil moisture sensor is extremely simple to use and only requires four pins to
connect.
AO (Analog Output) generates analog output voltage proportional to the soil moisture
level, so a higher level results in a higher voltage and a lower level results in a lower
voltage.
DO (Digital Output) indicates whether the soil moisture level is within the limit. D0
becomes LOW when the moisture level exceeds the threshold value (as set by the
potentiometer), and HIGH otherwise.
VCC supplies power to the sensor. It is recommended that the sensor be powered from
3.3V to 5V. Please keep in mind that the analog output will vary depending on the
voltage supplied to the sensor.
void setup() {
         pinMode(sensorPower, OUTPUT);
         Serial.begin(9600);
}
void loop() {
         //get the reading from the function below and print it
                                                                                     36
         Serial.print("Analog output: ");
         Serial.println(readSensor());
         delay(1000);
}
This test may require some trial and error. Once you have the readings, you can use
them as a threshold to trigger an action.
Arduino Code
The sketch below estimates the level of soil moisture using the following threshold
values:
                                                                                    37
/* Change these values based on your calibration values */
#define soilWet 500 // Define max value we consider soil 'wet'
#define soilDry 750 // Define min value we consider soil 'dry'
// Sensor pins
#define sensorPower 7
#define sensorPin A0
void setup() {
         pinMode(sensorPower, OUTPUT);
         Serial.begin(9600);
}
void loop() {
         //get the reading from the function below and print it
         int moisture = readSensor();
         Serial.print("Analog Output: ");
         Serial.println(moisture);
                                                                                    39
Now, to set the threshold, stick the probe into the soil when your plant needs watering
and turn the pot clockwise until the Status LED is on. Then, turn the pot back counter
clockwise just until the LED goes off.
That’s all there is to it; your module is now ready to use.
Arduino Code
Now, upload the sketch below to your Arduino.
// Sensor pins
#define sensorPower 7
#define sensorPin 8
void setup() {
         pinMode(sensorPower, OUTPUT);
         Serial.begin(9600);
}
void loop() {
         //get the reading from the function below and print it
         int val = readSensor();
         Serial.print("Digital Output: ");
         Serial.println(val);
                                                                                     40
      Interface MPU6050 Accelerometer and Gyroscope Sensor with Arduino
Assuming that the cube is in outer space, where everything is weightless, the ball will
simply float in the center of the cube.
Now, assume that each wall represents a specific axis.
If we suddenly move the box to the left with acceleration 1g (a single G-force 1g is
equivalent to gravitational acceleration 9.8 m/s2), the ball will undoubtedly hit the wall X.
If we measure the force the ball exerts on wall X, we can obtain an output value of 1g
along the X axis.
Let’s see what happens when we place that cube on Earth. The ball will simply fall on
the wall Z, exerting a force of 1g as shown in the diagram below:
                                                                                          41
In this case, the box isn’t moving, but we still get a 1g reading on the Z axis. This is
because gravity (which is actually a form of acceleration) is pulling the ball downward
with a force of 1g.
While this model does not exactly represent how a real-world accelerometer sensor is
built, it is often useful in understanding why an accelerometer’s output signal is typically
specified in ±g, or why an accelerometer reads 1g in the z-axis at rest, or what
accelerometer readings you can expect at different orientations.
In the real world, accelerometers are based on Micro-Electro-Mechanical Systems
(MEMS fabrication technology). So, let’s find out how a MEMS accelerometer works.
How Does a MEMS Accelerometer Work?
A MEMS (Micro-Electro-Mechanical System) accelerometer is a micro-machined
structure built on top of a silicon wafer.
This structure is suspended by polysilicon springs. It allows the structure to deflect when
accelerated along the X, Y, and/or Z axes.
As a result of deflection, the capacitance between fixed plates and plates attached to
the suspended structure changes. This change in capacitance is proportional to the
acceleration along that axis.
The sensor processes this change in capacitance and converts it into an analog output
voltage.
                                                                                         42
How Does a Gyroscope Work?
While accelerometers measure linear acceleration, gyroscopes measure angular
rotation. To accomplish this, they measure the force generated by the Coriolis Effect.
Coriolis Effect
The Coriolis Effect states that when a mass (m) moves in a specific direction with a
velocity (v) and an external angular rate (Ω) is applied (Red arrow), the Coriolis Effect
generates a force (Yellow arrow) that causes the mass to move perpendicularly. The
value of this displacement is directly related to the angular rate applied.
                                                                                      43
When we begin to rotate the structure, the Coriolis force acting on the moving proof
mass causes the vibration to change from horizontal to vertical.
There are three modes depending on the axis along which the angular rotation is
applied.
Roll Mode:
When an angular rate is applied along the X-axis, M1 and M3 will move up and down
out of the plane due to the coriolis effect. This causes a change in the roll angle, hence
the name Roll Mode.
Pitch Mode:
When an angular rate is applied along the Y-axis, M2 and M4 will move up and down
out of the plane. This causes a change in the pitch angle, hence the name Pitch Mode.
Yaw Mode:
When an angular rate is applied along the Z-axis, M2 and M4 will move horizontally in
opposite directions. This causes a change in the yaw angle, hence the name Yaw
Mode.
                                                                                       44
Whenever the coriolis effect is detected, the constant motion of the driving mass will
cause a change in capacitance (∆C) that is detected by the sensing structure and
converted into a voltage signal.
For your information, this is what the MEMS structure die of a 3-axis digital gyroscope
looks like. Thanks to Adam McCombs for sharing this image of a decaped L3GD20HTR
MEMS gyroscope.
                                                                                     45
The module includes an on-board LD3985 3.3V regulator, so you can safely use it with
a 5V logic microcontroller like Arduino.
The MPU6050 consumes less than 3.6mA during measurements and only 5μA when
idle. Because of its low power consumption, it can be used in battery-powered devices.
Additionally, the module has a Power LED that illuminates when the module is powered
on.
Measuring Acceleration
The MPU6050 has an on-chip accelerometer that can measure acceleration over four
programmable full scale ranges of ±2g, ±4g, ±8g, and ±16g.
The MPU6050 is equipped with three more 16-bit analog-to-digital converters that
simultaneously sample the three axes of rotation (along the X, Y, and Z axes). The
sampling rate can be adjusted from 3.9 to 8000 samples per second.
Measuring Temperature
The MPU6050 includes an embedded temperature sensor that can measure
temperatures from -40 to 85°C with a ±1°C accuracy.
Note that this temperature measurement is of the silicon die itself, not the ambient
temperature. These measurements are typically used to compensate for accelerometer
                                                                                    46
and gyroscope calibration or to detect temperature changes rather than measuring
absolute temperatures.
The I2C Interface
The module communicates with the Arduino via the I2C interface. It supports two
different I2C addresses: 0x68HEX and 0x69HEX. This allows two MPU6050s to be used on
the same bus or to avoid address conflicts with other devices on the bus.
The ADO pin determines the I2C address of the module. This pin is pulled down with a
4.7K resistor. Therefore, when you leave the ADO pin unconnected, the default I2C
address is 0x68HEX; when you connect it to 3.3V, the line is pulled HIGH, and the I2C
address becomes 0x69HEX.
Adding External Sensors
You can improve the accuracy of the MPU6050 module even further by connecting
external sensors to it. These external sensors can be connected to the MPU6050 via a
second, completely independent I2C bus (XDA and XCL).
This external connection is usually used to attach a magnetometer, which can measure
magnetic fields along three axes. The MPU6050 has six Degrees of Freedom (DOF),
three for the accelerometer and three for the gyroscope combined. The addition of a
magnetometer increases the sensor’s degree of freedom from 6 to 9 DOF.
Technical Specifications
Here are the specifications:
                                                                                   47
         Gyroscope Range                           ±250°/s, ±500°/s, ±1000°/s, ±2000°/s
XDA is the external I2C data line. The external I2C bus is for connecting external
sensors, such as a magnetometer.
AD0 allows you to change the I2C address of the MPU6050 module. It can be used to
avoid conflicts between the module and other I2C devices or to connect two MPU6050s
to the same I2C bus. When you leave the ADO pin unconnected, the default I2C
address is 0x68HEX; when you connect it to 3.3V, the I2C address changes to 0x69HEX.
INT is the Interrupt Output pin. The MPU6050 can be programmed to generate an
interrupt upon detection of gestures, panning, zooming, scrolling, tap detection, and
shake detection.
                                                                                          48
Wiring an MPU6050 Module to an Arduino
Let’s hook the MPU6050 module to the Arduino.
Connections are straightforward. Begin by connecting the VCC pin to the Arduino’s 5V
output and the GND pin to ground.
Now we are left with the pins that are used for I2C communication. Note that each
Arduino board has different I2C pins that must be connected correctly. On Arduino
boards with the R3 layout, the SDA (data line) and SCL (clock line) are on the pin
headers close to the AREF pin. They are also referred to as A5 (SCL) and A4 (SDA).
Check out the table below for quick reference.
SCL SDA
Arduino Uno A5 A4
Arduino Nano A5 A4
Arduino Mega 21 20
Leonardo/Micro 3 2
Library Installation
Setting up the MPU6050 module to begin capturing the device’s raw data output is fairly
simple. Manipulating the data into something meaningful, on the other hand, is more
difficult, but there are some libraries at our disposal.
To install the library, navigate to Sketch > Include Library > Manage Libraries… Wait for
the Library Manager to download the library index and update the list of installed
libraries.
                                                                                      49
Filter your search by entering ‘mpu6050’. Look for the Adafruit                MPU6050
Library by Adafruit. Click on that entry and then choose Install.
The Adafruit MPU6050 library makes use of the Adafruit Unified Sensor
Driver and Adafruit Bus IO Library internally. So, search the library manager for Adafruit
Unified Sensor and BusIO and install them as well.
                                                                                       50
Arduino Example Code
Here is a simple program that reads the linear acceleration, angular rotation, and
temperature from the MPU6050 module and prints them on the serial monitor.
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
void setup(void) {
         Serial.begin(115200);
        // Try to initialize!
        if (!mpu.begin()) {
                   Serial.println("Failed to find MPU6050 chip");
                   while (1) {
                     delay(10);
                   }
        }
        Serial.println("MPU6050 Found!");
        delay(100);
}
void loop() {
         /* Get new sensor events with the readings */
         sensors_event_t a, g, temp;
                                                                                51
         mpu.getEvent(&a, &g, &temp);
         Serial.print("Rotation X: ");
         Serial.print(g.gyro.x);
         Serial.print(", Y: ");
         Serial.print(g.gyro.y);
         Serial.print(", Z: ");
         Serial.print(g.gyro.z);
         Serial.println(" rad/s");
         Serial.print("Temperature: ");
         Serial.print(temp.temperature);
         Serial.println(" degC");
         Serial.println("");
         delay(500);
}
Make sure you set the baud rate to “115200” in the serial port monitor. Because the
MPU6050 returns an excessive amount of data, this higher speed is required to display
it.
There will be a lot of information displayed, such as linear acceleration, angular rotation,
and temperature. Move your sensor around and observe how the data changes.
                                                                                         52
Code Explanation:
At the beginning of the sketch, all the necessary libraries are included. As previously
stated, the Adafruit_MPU6050 library implements the hardware functions of the
MPU6050, while the Adafruit_Sensor library implements the unified sensor abstraction
layer. Wire.h, which allows us to communicate with I2C devices, is also included.
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Next, an instance of the Adafruit_MPU6050 class is created in order to access its
associated methods.
Adafruit_MPU6050 mpu;
In the setup section of the code, we first initialize the serial communication with the PC
and call the begin() function. The begin() function initializes the I2C interface and
verifies that the chip ID is correct. It then soft-resets the chip and waits for the sensor to
calibrate after wake-up.
Serial.begin(115200);
// Try to initialize!
if (!mpu.begin()) {
           Serial.println("Failed to find MPU6050 chip");
           while (1) {
             delay(10);
           }
}
The following three functions are then used to configure the measurement range of the
MPU6050.
setAccelerometerRange(mpu6050_accel_range_t)
The setAccelerometerRange() function sets the accelerometer measurement range.
This function accepts the following values:
Keep in mind that the smaller the range, the more sensitive the accelerometer readings
will be.
                                                                                           53
setGyroRange(mpu6050_gyro_range_t)
The setGyroRange() function sets the gyroscope measurement range. This function
accepts the following values:
setFilterBandwidth(mpu6050_bandwidth_t)
The setFilterBandwidth() function sets the bandwidth of the Digital Low-Pass Filter. This
function accepts the following values:
The bandwidth selection allows you to alter the low-pass filter’s cutoff frequency,
allowing you to smooth out the signal by removing high-frequency noise.
In this example, we set the accelerometer range to ±8G, the gyro range to ±500°/s, and
the filter bandwidth to 21 Hz.
mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
mpu.setGyroRange(MPU6050_RANGE_500_DEG);
mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
                                                                                       54
The measurement range is the maximum acceleration or angular velocity that your
MPU6050 can read. Think about what you are measuring and set limits based on that.
Do you need to measure the rotational speed of a record player (which is extremely
slow) or a spinning wheel (which can be extremely fast)?
In the loop section of the code, we create three objects of type sensors_event_t to hold
our results. sensors_event_t is simply a user-defined datatype (structures in C) that
stores a variety of sensor data such as acceleration, gyro, temperature, light, pressure,
and many others. More information is available on github.
sensors_event_t a, g, temp;
The function getEvent() is then called. This function reads a new set of values from the
sensor (a sensor “event”), converts them to the correct SI units and scale, and then
assigns the results to our mpu object.
mpu.getEvent(&a, &g, &temp);
Finally, the values are displayed on the serial monitor.
Serial.print("Acceleration X: ");
Serial.print(a.acceleration.x);
Serial.print(", Y: ");
Serial.print(a.acceleration.y);
Serial.print(", Z: ");
Serial.print(a.acceleration.z);
Serial.println(" m/s^2");
Serial.print("Rotation X: ");
Serial.print(g.gyro.x);
Serial.print(", Y: ");
Serial.print(g.gyro.y);
Serial.print(", Z: ");
Serial.print(g.gyro.z);
Serial.println(" rad/s");
Serial.print("Temperature: ");
Serial.print(temp.temperature);
Serial.println(" degC");
Arduino Example Code – Plotting MPU6050 data
Simply looking at the raw data from the MPU6050 will not help. Use a Serial Plotter if
you really want to see how your MPU6050 reacts when you move it around.
The Arduino IDE includes a useful tool called the serial plotter. It can provide real-time
visualizations of variables. This is extremely useful for visualizing data, debugging code,
and visualizing variables as waveforms.
Let’s give it a shot with the updated code below. Compile and upload the program
below, then navigate to Tools > Serial Plotter (Ctrl+Shift+L). The code uses a baud rate
of 115200; ensure that the serial plotter is also set to 115200.
                                                                                        55
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;
void setup(void) {
         Serial.begin(115200);
        // Try to initialize!
        if (!mpu.begin()) {
                   Serial.println("Failed to find MPU6050 chip");
                   while (1) {
                     delay(10);
                   }
        }
        delay(100);
}
void loop() {
         /* Get new sensor events with the readings */
         sensors_event_t a, g, temp;
         mpu.getEvent(&a, &g, &temp);
                                                                    56
        Serial.println("");
        delay(10);
}
When you move the module up and down the Z axis, you should see something like
this.
Code Explanation:
You’ll notice that the majority of this sketch is identical to the previous one, with the
exception of:
   ●   All other readings are printed in such a way that they form a comma-separated
       list of values.
                                                                                        57
This is similar to the topic Interface of Switch as an input to Arduino board and gets
output, but here we replace the switch with an IR sensor. This is like an automatic
switch which gives signal on obstacle detection.
PINOUT:
           1. VCC: 3.3V-5V power input pin
         2. GND: 0V power pin
         3. OUT: Digital Output Pin
TECHNICAL SPECIFICATION/RATING
       ● Operating Voltage: 3.0V – 6.0V
REQUIRED HARDWARE
         S.No.      Item                                     Quantity
1 Arduino Uno 1
2 Breadboard 1
3 IR Sensor 1
4 LED 1
                                                                                    58
 13                                         Anode (+)
VCC VCC
GND GND
10 OUTPUT (O)
void setup() {
  pinMode(LEDpin, OUTPUT);
  pinMode(obstaclePin, INPUT);
  Serial.begin(9600);
}
void loop() {
 hasObstacle = digitalRead(obstaclePin);
if (hasObstacle == HIGH) {
                                                          59
  Serial.println("Stop something is ahead!!");
  digitalWrite(LEDpin, HIGH);
 }
 else {
   Serial.println("Path is clear");
   digitalWrite(LEDpin, LOW);
 }
 delay(200);
}
IR SENSOR ARDUINO CODE EXPLANATION
Here we define an integer type variable LED and assign 13 to it. Then we define
another integer type variable obstaclePin and assign 10 to it. Then we define another
variable hasObstacle and set its state to LOW (0), this is used for the reading status of
pin number 7 of the arduino. Status either LOW or HIGH means is obstacle present
then HIGH if not then LOW.
int LEDpin = 13;
int obstaclePin = 10;
int hasObstacle = LOW; // LOW MEANS NO OBSTACLE
Now in void setup(), define pin-mode that is LED as output and obstaclePin as input
means where we use term LED it is 13 there and where we use obstaclePin it is 10
there. Then for serial communication we are setting a baud rate of 9600 by using the
function Serial.begin(). We will discuss baud rate and serial communication in a later
chapter (Communication System).
void setup() {
  pinMode(LEDpin, OUTPUT);
  pinMode(obstaclePin, INPUT);
  Serial.begin(9600);
}
In void loop(), first we are reading obstaclePin(10) state is it either HIGH or LOW, as we
connected IR sensor over there, as IR sensor detects any obstacle by transmitting and
receiving waves it gives a HIGH signal which in turn sets obstaclePin(10) of arduino to
HIGH and If the sensor does not detect any obstacle it gives a LOW signal which in turn
sets obstaclePin(10) of arduino to LOW. This signal will be stored in variable
hasObstacle. So there are two conditions for hasObstacle either HIGH or LOW.
Then we will check it in ‘if block’, if it is HIGH, if condition matched then we print a
message on the serial monitor “Stop something is ahead!” & Turn LED on by doing
LEDpin(13) HIGH.
Otherwise the signal will LOW, so in ‘else block’ we print a message on the serial
monitor “Path is clear”& Turns LED off.
This complete cycle will be delayed by 200 milliseconds or 0.2 seconds.
void loop() {
 hasObstacle = digitalRead(obstaclePin);
if (hasObstacle == HIGH) {
                                                                                       60
  Serial.println("Stop something is ahead!!");
  digitalWrite(LEDpin, HIGH);
 }
 else {
   Serial.println("Path is clear");
   digitalWrite(LEDpin, LOW);
 }
 delay(200);
}
OUTPUT
As an obstacle will be detected a message will print on the serial monitor & LED turned
ON and if there is no obstacle detected, LED will be turned OFF.
                                                                                        61
Components Required
  ● Raspberry Pi 3 Model B
Circuit Design
If you observe the circuit diagram, there is not a lot of stuff going on with respect to the
connections. All you need to do is to connect the VCC and GND pins of the DHT11 Sensor to
+5V and GND of Raspberry Pi and then connect the Data OUT of the Sensor to the GPIO4 i.e.
Physical Pin 7 of the Raspberry Pi.
Code:
import sys
         import Adafruit_DHT
         import time
while True:
                                                                                         62
Working
Make the connections as per the circuit diagram and install the library. Use the above python
program                 to                   see                   the                 results.
                                                                                            63
The Raspberry Pi needs to read the Echo pin to calculate the time and hence the corresponding
GPIO pin on the Raspberry Pi must be configured as Input So, before connecting the Echo Pin to
the Raspberry Pi, it must be given to a level converter.
Circuit Diagram:
The following image shows the connections between the Raspberry Pi and the HC-SR04
Ultrasonic Sensor. This circuit diagram is made with Fritzing Software.
Components Required
  ● Raspberry Pi 3 Model B
                                                                                           64
ECHO = 18
i=0
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG, False)
print "Calibrating....."
time.sleep(2)
print "Place the object......"
try:
   while True:
     GPIO.output(TRIG, True)
     time.sleep(0.00001)
     GPIO.output(TRIG, False)
     while GPIO.input(ECHO)==0:
        pulse_start = time.time()
     while GPIO.input(ECHO)==1:
        pulse_end = time.time()
     pulse_duration = pulse_end - pulse_start
     distance = pulse_duration * 17150
     distance = round(distance+1.15, 2)
       if distance<=20 and distance>=5:
        print "distance:",distance,"cm"
        i=1
     if distance>20 and i==1:
        print "place the object...."
        i=0
     time.sleep(2)
except KeyboardInterrupt:
    GPIO.cleanup()
Applications
In this project, we have seen how to interface HC-SR04 Ultrasonic Sensor with Raspberry Pi.
This setup can be used in a lot applications like:
     ● Obstacle Avoiding
   ●   Proximity Detection
   ●   Distance Measurement
   ●   Range Meter
                                                                                         65
The smoke sensor we will use is the MQ-2. This is a sensor that is not only sensitive to smoke,
but also to flammable gas.
The MQ-2 smoke sensor reports smoke by the voltage level that it outputs. The more smoke
there is, the greater the voltage that it outputs. Conversely, the less smoke that it is exposed to,
the less voltage it outputs.
The MQ-2 also has a built-in potentiometer to adjust the sensitivity to smoke. By adjusting the
potentiometer, you can change how sensitive it is to smoke, so it's a form of calibrating it to
adjust how much voltage it will put out in relation to the smoke it is exposed to
Components Needed
  ● Raspberry Pi board
So to power the smoke sensor, we connect pin 2 of the smoke sensor to the 5V terminal of the
raspberry pi and terminal 3 to the GND terminal of the raspberry pi. This gives the smoke sensor
the 5 volts it needs to be powered.
The output of the sensor goes into the MCP3002 pin CH0, which is pin 2 of the MCP3002. This
is one of the analog input pins of the MCP3002. The MCP3002 needs to convert this analog
signal from the smoke sensor into a digital signal, which is the only type of signal that the
Raspberry pi can interpret
Through these connections, the Raspberry Pi can read the analog voltage output from the sensor.
We will make it in our code that if the smoke sensor voltage exceeds a certain threshold, which
we will specify, we will make it so that our program outputs the statement, "Smoke detected."
Code
The code to read the value of a smoke sensor with a Raspberry Pi is shown below.
/* MQ-2 Smoke Sensor Circuit with Raspberry Pi */
                                                                                                 66
import time
import botbook_mcp3002 as mcp #
smokeLevel= 0
def readSmokeLevel():
global smokeLevel
smokeLevel= mcp.readAnalog()
def main():
while True: #
readSmokeLevel() #
print ("Current smoke level is %i " % smokeLevel) #
if smokeLevel > 120:
print("Smoke detected")
time.sleep(0.5) # s
if_name_=="_main_":
main()
In the first block of code, the first 2 lines, we import libraries into our code. The botbook.com
library for MCP3002 is one that saves a lot of coding and makes it easy to read analog values.
This above file that you have just written must be in the same directory as the
botbook_mcp3002.py library. You must also install the spidev library, which is imported by
botbook_mcp3002.
In our next line, we create a variable named SmokeLevel and initialize it to 0. Just as the name
implies, it will hold the value of the smoke level, which will be the analog voltage output by the
smoke sensor.
In our next block of code, we create a function, readSmokeLevel, which reads the analog value
from the smoke sensor, which represents the smoke level. This is done by the readAnalog()
function.
The next block is our main code. This repeats the program forever, whic his common for
embedded devices. When you use While True, it's recommended thtat you add some delay at the
end of the loop. This gives the loop some time to pause before executing again, kind of like a
breather. All that's needed is just a few milliseconds of delay. In our code, we give it 0.5s, which
is 500 milliseconds. In our main code, we call the readSmokeLevel() function, which allows us
to read the smoke sensor value, and then we output this value. If the smokeLevel is above 120,
then we output the line, "Smoke detected."
And this is how our a smoke sensor circuit can be built with a Raspberry Pi.
                                                                                                 67
The main advantage of the PIR Motion Sensor using Raspberry Pi over all the above mentioned
projects is that Raspberry Pi can be easily connected to the Internet and allows IoT based
application of the project.
Circuit Diagram
The following Fritzing based images shows all the connections with respect to the PIR Motion
Sensor using Raspberry Pi.
Components Required
  ● Raspberry Pi 3 Model B
   ●   PIR Sensor
   ●   5V Buzzer
   ●   Connecting Wires
   ●   Mini Breadboard
   ●   Power Supply
   ●    Computer
Circuit Design:
Connect the VCC and GND pins of the PIR Motion Sensor to +5V and GND pins of the
Raspberry Pi. Connect the DATA Pin of the PIR Sensor to GPIO23 i.e. Physical Pin 16 of the
Raspberry Pi.
A 5V Buzzer is connected to GPIO24 i.e. Physical Pin 18 of the Raspberry Pi. The other pin of
the buzzer is connected to GND.
                                                                                          68
Code
The Programming part of the project is implemented using Python. The following is the Python
Script for the PIR Motion Sensor using Raspberry Pi.
        import RPi.GPIO as GPIO
        import timesensor = 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()
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 Motion Sensor using Raspberry Pi project have already been
mentioned. Some of them are:
    ● Automatic Room Light
   ●   Motion Detection
   ●   Intruder Alert
   ●   Automatic Door Opening
   ●   Home Security System
                                                                                         69
Simple operation lies at the heart of the soil moisture sensor. The two exposed wires on the fork-shaped
probe function as a variable resistor whose resistance changes as the soil's moisture level does.
This GIF animation of a soil moisture sensor demonstrates how its analog output varies with soil
moisture. When water is introduced to soil, the voltage immediately reduces from 5V to 0V, as seen here.
When you water the ground, the indicator light on the board lights up, as shown. For clarity, we have not
displayed the digital pin in action in the preceding GIF. The module has a potentiometer (blue) that
adjusts how sensitively the digital pin changes state from low to high when water is introduced into the
soil.
There are typically two components that make up a soil moisture sensor.
The Probe
Two exposed conductors on a fork-shaped probe are put wherever moisture levels need to be
determined. As was previously mentioned, its function is that of a variable resistor whose
resistance changes as a function of soil moisture.
The Module
The sensor also has an electronic module that interfaces the probe with the Arduino. The module
produces a voltage proportional to the probe's resistance and makes it available through an
Analog Output pin. The same signal is then sent to a Digital Output pin on an LM393 High
Accuracy Comparator, which is digitized.
                                                                                                      70
    The module features a potentiometer (DO) for fine-tuning the digital output sensitivity. It can be
    used to establish a threshold, at which point the module will output LOW if the moisture level
    exceeds the threshold and HIGH otherwise. This setup works great for initiating an event when a
    given value is reached. For instance, a relay might be set off to begin watering the plant if the
    soil moisture level rises above a given threshold.
    In addition to the IC, the module has two LEDs. When the component is activated, the Power
    LED will light up, and the Condition LED will light up if the moisture level is above the
    setpoint.Pinout Of A Soil Moisture Sensor
    Four pins are included on the FC-28 soil moisture sensor.
                                                                                                   71
Code:
import RPi.GPIO as GPIO
import time
#GPIO SETUP
channel = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
def callback(channel):
     if GPIO.input(channel):
           print ("Water Detected!")
     else:
           print ("Water Detected!")
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
while True:
     time.sleep(0)
Output:
Conclusion:
There's been a moisture detection! Once the humidity level is detected, you can change the code
to perform any action you like. You could activate a motorized or audible alarm, for instance.
You can do anything with this! Following is a tutorial on connecting a photoresistor to a
Raspberry Pi.
                                                                                            72
MPU6050              (Accelerometer+Gyroscope)
Interfacing with Raspberry Pi
                                                                                            73
#include <stdio.h>
#include <wiringPi.h>
int fd;
void MPU6050_Init(){
          }
short read_raw_data(int addr){
          short high_byte,low_byte,value;
          high_byte = wiringPiI2CReadReg8(fd, addr);
          low_byte = wiringPiI2CReadReg8(fd, addr+1);
          value = (high_byte << 8) | low_byte;
          return value;
}
int main(){
          float Acc_x,Acc_y,Acc_z;
          float Gyro_x,Gyro_y,Gyro_z;
          float Ax=0, Ay=0, Az=0;
          float Gx=0, Gy=0, Gz=0;
                                                                                                  74
       fd = wiringPiI2CSetup(Device_Address); /*Initializes I2C with device Address*/
       MPU6050_Init();                       /* Initializes MPU6050 */
       while(1)
       {
               /*Read raw value of Accelerometer and gyroscope from MPU6050*/
               Acc_x = read_raw_data(ACCEL_XOUT_H);
               Acc_y = read_raw_data(ACCEL_YOUT_H);
               Acc_z = read_raw_data(ACCEL_ZOUT_H);
               Gyro_x = read_raw_data(GYRO_XOUT_H);
               Gyro_y = read_raw_data(GYRO_YOUT_H);
               Gyro_z = read_raw_data(GYRO_ZOUT_H);
               Gx = Gyro_x/131;
               Gy = Gyro_y/131;
               Gz = Gyro_z/131;
       }
       return 0;
}
MPU6050 Output
The output window will show all values mentioned below
Gx = Gyro X-axis data in degree/seconds
Gy = Gyro Y-axis data in degree/seconds
Gz = Gyro Z-axis data in degree/seconds
Ax = Accelerometer X-axis data in g
Ay = Accelerometer Y-axis data in g
Az = Accelerometer Z-axis data in g
                                                                                            75
Interfacing IR Sensor with Raspberry Pi
Infrared Sensors or IR Sensors are one of the frequently used sensor modules by
electronics hobbyists and makers. They are often used as Obstacle Detecting Sensors or
Proximity Sensors.
                                                                                    76
IR Sensors are also used in Contactless Digital Tachometers. Some of the other
applications where IR Sensors are implemented are Line Follower Robots, Obstacle
Avoiding Robots, Edge Avoiding Robots and many more.
An IR Sensor Module basically consists of three parts: an IR Transmitter, an IR Detector
and a control circuit.
Usually, an IR LED is used as an IR Transmitter and a Photo Diode or a Photo
Transistor (less often) is used as an IR Detector. The control circuit consists of a
Comparator IC with necessary components.
Based on the application and requirement, IR Sensors can be implemented in two ways.
In the first method, both the IR Transmitter and the IR Detector are placed side-by-side.
In the second setup, the IR Transmitter and the IR Detector are placed facing each other.
The first way of implementation is known as Reflective Type IR Sensor. In this setup, the
IR Transmitter continuously emits infrared light and if there is any obstacle/object in
front of the sensor, the infrared light hits the object and bounces back. The reflected
signal is captured by the IR Detector and the control circuit will reflect a Logic HIGH on
its output.
The second way of implementation, where the IR Transmitter and Detector are positioned
face-t-face, is known as Transmissive Type IR Sensor. Here, the infrared light from the
IR Transmitter always falls on the Detector.
If there is an object in between the Transmitter and Detector, then there will be an
obstruction to the infrared light and the control circuit will detect this and produces
appropriate output.
The IR Sensor used in this project is a Reflective Type IR Sensor. You can easily build
this type of IR Sensor as a DIY Project as the circuit is very simple.
                                                                                       77
Components Required
  ● Raspberry Pi 3 Model B
   ●   IR Sensor
   ●   5V Buzzer
   ●   Mini Breadboard
   ●   Connecting Wires
   ●   Power Supply
   ●    Computer
Circuit Design
The IR Sensor Module has only three Pins: VCC, GND and Data. Connect the VCC and GND
pins of the IR Sensor to +5V and GND pins of the Raspberry Pi.
Then connect the Data pin of the IR Sensor to GPIO23 i.e. Physical Pin 16 of the Raspberry Pi.
In order to indicate the alarm, I have used a simple 5V Buzzer. Connect one terminal of the
buzzer to GND of Raspberry Pi and the other terminal (usually marked +) to GPIO24 i.e.
Physical Pin 18 of Raspberry Pi.
Code
The following is the code for interfacing IR Sensor with Raspberry Pi. It is written in
Python.
    import RPi.GPIO as GPIO
    import time
    sensor = 16
    buzzer = 18
                                                                                           78
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(sensor,GPIO.IN)
    GPIO.setup(buzzer,GPIO.OUT)
    GPIO.output(buzzer,False)
    print "IR Sensor Ready....."
    print " "
    try:
      while True:
         if GPIO.input(sensor):
            GPIO.output(buzzer,True)
            print "Object Detected"
            while GPIO.input(sensor):
               time.sleep(0.2)
         else:
            GPIO.output(buzzer,False)
    except KeyboardInterrupt:
      GPIO.cleanup()
Applications
As mentioned in the earlier sections, Proximity Sensor or Obstacle Detection is the main
application of interfacing IR Sensor with Raspberry Pi. Some of the common applications
include:
    ● Contactless Tachometer
79