MQ-02 & MQ-05 Gas Sensors – 3 Page Detailed Explanation
🔹 Introduction
MQ gas sensors are widely used in gas leak detection systems. They help in
identifying the presence of toxic and combustible gases in the environment.
Two popular sensors from this family are MQ-02 and MQ-05.
These sensors are used in smart homes, factories, safety systems, and IoT-
based monitoring devices to detect gas leakage and prevent hazards. They are
low-cost, reliable, and easy to use with microcontrollers like Arduino.
🔹 What is MQ-02 Sensor?
• MQ-02 is a gas and smoke detection sensor.
• It can detect flammable gases like Hydrogen (H₂), Liquefied
Petroleum Gas (LPG), Methane (CH₄), Carbon Monoxide (CO),
alcohol vapors, and smoke.
• It is sensitive and has both digital and analog outputs.
➤ Key Features:
• Operating Voltage: 5V
• Output: Analog (A0) & Digital (D0)
• Preheat time: ~20 seconds
• Sensitivity: Adjustable using the onboard potentiometer
• Cheap and widely available
🔹 What is MQ-05 Sensor?
• MQ-05 is mainly designed for LPG, Natural Gas, and Methane (CH₄).
• It is not sensitive to smoke, so it is not used in fire or smoke detection
applications.
• Less used in comparison to MQ-02.
🔹 Pinout of MQ-02/MQ-05
Pin
Function
Name
Vcc Connect to 5V power supply
Pin
Function
Name
GND Connect to Ground
A0 Analog output (gives gas value)
Digital output (High/Low based on
D0
threshold)
🔹 Working Principle of MQ-02/05
Let’s break it down simply:
• Inside the MQ sensor, there is a heating coil and a chemical-sensitive
layer made of SnO₂ (Tin Dioxide).
• In clean air, this layer has high resistance.
• When gas is present, the gas reacts with the sensor surface, and
resistance drops.
• As resistance decreases, voltage increases at the output pin (especially
A0).
• The microcontroller (like Arduino) reads this analog voltage to detect the
gas level.
🔥 Summary:
• Gas Present → Resistance ↓ → Voltage ↑
• No Gas → Resistance ↑ → Voltage ↓
So, the sensor outputs high voltage if gas is detected, and low voltage if there
is no gas.
🔹 Interfacing MQ-02 with Arduino Uno
Connecting the MQ-02 sensor to Arduino is very easy. Let’s look at the step-by-
step connection:
MQ-02
Arduino Pin
Pin
Vcc 5V
GND GND
A0 A0
Optional, use if digital threshold
D0
required
Circuit Notes:
• Vcc provides power.
• A0 reads analog voltage (sensor reading).
• D0 can be used for basic gas alert (HIGH/LOW).
• You can use Serial Monitor in Arduino IDE to display gas levels.
🔹 Arduino Code for MQ-02
Here’s the basic code for reading MQ-02 sensor data using Arduino:
int gas_level;
void setup() {
pinMode(A0, INPUT); // A0 is used to read analog values
Serial.begin(9600); // Start serial communication at 9600 baud
void loop() {
gas_level = analogRead(A0); // Read analog value from sensor
Serial.print("Gas Level : ");
Serial.println(gas_level); // Print the gas level on Serial Monitor
delay(500); // Wait half a second
🔹 Code Explanation:
• Line 1: Declare a variable to store sensor data.
• setup() function:
• pinMode(A0, INPUT) – Sets analog pin A0 as input.
• Serial.begin(9600) – Starts communication with PC.
• loop() function:
• Reads sensor data using analogRead(A0).
• Serial.print() displays the gas level continuously.
• delay(500) slows down the output to make it readable.
6. Applications of MQ-02 Sensor
• 🏠 Home gas leakage detectors
• 🧪 Air quality monitoring systems
• 🚗 Vehicle gas detection systems
• 🏭 Industrial safety alarms
• 🔥 Fire detection systems
7. Advantages
• ✅ Low cost and easily available
• ✅ Detects multiple gases
• ✅ Simple interfacing with Arduino
• ✅ Analog and digital output
⚠️8. Limitations
• ❌ Takes 24-48 hours for first-time calibration ("burn-in" time)
• ❌ Sensitive to humidity and temperature
• ❌ Needs regular recalibration for accurate readings
❌ Not suitable for precise measurement—more for alerts
🔹 Comparison: MQ-02 vs MQ-05
Feature MQ-02 MQ-05
Detects
✅ Yes ❌ No
Smoke
Detects
✅ Yes ❌ No
Alcohol
Detects LPG ✅ Yes ✅ Yes
Detects CH₄ ✅ Yes ✅ Yes
Sensitivity High (Multi-Gas) Medium (CH₄-focused)
Output Analog + Digital Analog + Digital
Smoke, fire, gas, Mainly LPG & CH₄
Use Case
alcohol detection
🔹 Conclusion
The MQ-02 and MQ-05 sensors are highly effective for detecting gases. While
MQ-02 is multi-purpose and can detect smoke, alcohol, and multiple gases, MQ-
05 is specific to methane and LPG, making it more suitable for gas-only
applications.
These sensors are plug-and-play and can be easily interfaced with Arduino,
Raspberry Pi, or any microcontroller. They are reliable for early gas leak
detection and form the backbone of smart safety systems in modern IoT
applications.
With proper calibration and sensitivity tuning, these sensors can help prevent
major accidents and save lives. That’s why they are a core part of any gas safety
setup in smart systems.
#################################################
#####
Obstacle Sensor – Detailed Theory
Answer
📌 Definition:
An Obstacle Sensor is an electronic device used to detect the presence of any
physical object or obstacle within its sensing range. It works using infrared
(IR) technology and provides a digital (binary) output, making it suitable for
integration with microcontrollers like Arduino.
📌 Nature of Output:
• The sensor provides digital output, i.e., either:
• 1 (HIGH) → No obstacle detected
• 0 (LOW) → Obstacle detected
• This output is easy to interpret in Arduino or other digital circuits.
📌 Adjustable Range:
• The detection range of the sensor can be changed using the inbuilt
potentiometer.
• By rotating this potentiometer, the threshold of obstacle detection can
be increased or decreased.
📌 Pin Configuration (Pinout):
Pin
Function Connection
Name
Vcc Power supply input Connect to 5V
GND Ground Connect to GND
Digital output pin Connect to Digital I/O pin of Arduino
OUT/D0
(signal) (e.g., pin 2)
Obstacle Sensor – Working Principle
📌 Basic Concept:
The obstacle sensor works based on the principle of infrared (IR) light
reflection. It uses an IR emitter-receiver pair to detect whether an obstacle
(such as a wall, hand, or any object) is present in front of the sensor or not.
🔸 IR Emitter and IR Receiver:
• The IR emitter (LED) continuously transmits infrared rays in the
forward direction.
• The IR receiver (photodiode) is placed next to the emitter and is
responsible for receiving the reflected IR rays from any nearby object.
🔄 How Detection Happens:
✅ Case 1: Obstacle is Present
• The IR rays from the emitter hit the obstacle and get reflected back.
• The reflected rays are received by the IR receiver.
• If the reflected signal strength (amplitude) is greater than a set
threshold (adjusted by the potentiometer), then:
• The sensor considers this as obstacle detected
• It gives a digital output of 0 (LOW)
🚫 Case 2: Obstacle is Not Present
• The IR rays do not hit any surface, so there is no reflection.
• The IR receiver gets little or no IR signal.
• In this case, the sensor gives a digital output of 1 (HIGH) indicating no
obstacle detected.
🧠 Important Note:
• The threshold level for detection is adjustable using a potentiometer
on the sensor module.
• This helps in changing the detection range, making it more or less
sensitive to obstacles.
📊 Summary Table:
IR Output
Situation Meaning
Reflection Signal
Obstacle Obstacle
Yes 0 (LOW)
Present Detected
No Obstacle No Obstacle
No 1 (HIGH)
Present Detected
✅ Conclusion:
The obstacle sensor functions by using IR light and the principle of reflection
from surfaces. When an obstacle reflects the IR signal back to the sensor with
sufficient strength, the output becomes LOW (0), indicating the presence of an
object. If there's no reflection, the output remains HIGH (1), signaling that the
path is clear. This simple yet effective technique makes it ideal for use in robots,
automation systems, and object detection applications.
Obstacle Sensor – Interfacing with
Arduino
📘 Introduction:
The Obstacle Sensor can be easily interfaced with the Arduino Uno for
detecting nearby objects in real-time. It provides a digital output, making it
suitable for directly connecting to any of Arduino’s digital input pins.
🔗 Pin Connections:
The obstacle sensor typically has three pins:
Sensor Arduino
Description
Pin Connection
Power supply input (5
Vcc 5V
volts)
Sensor Arduino
Description
Pin Connection
GND GND Ground connection
OUT Digital output signal from
Digital Pin 2
(D0) sensor
⚙️How the Interfacing Works:
• The Vcc and GND pins of the sensor are connected to the 5V and GND
pins of the Arduino to power the sensor.
• The OUT pin of the sensor is connected to digital pin 2 of the Arduino Uno.
• The Arduino reads the sensor’s output using digitalRead(2) in the code.
• If the sensor detects an obstacle, it outputs LOW (0).
• If no obstacle is detected, it outputs HIGH (1).
✅ Conclusion:
Interfacing an obstacle sensor with Arduino is simple and efficient. By connecting
the sensor’s Vcc and GND to Arduino’s 5V and GND, and the sensor’s digital
output to a digital input pin (like pin 2), the Arduino can easily detect obstacle
presence. This setup forms the foundation of smart robots, auto-detection
systems, and object-avoiding mechanisms.
Obstacle Sensor – Code Explanation
(Line by Line)
The obstacle sensor is interfaced with the Arduino Uno, and the following
program is used to detect the presence of an obstacle and indicate it using the
onboard LED on pin 13.
✅ Complete Code:
cpp
CopyEdit
int obstacle_pres = 0;
void setup() {
pinMode(2, INPUT); // Sensor output pin connected to digital pin 2
pinMode(13, OUTPUT); // LED connected to digital pin 13
Serial.begin(9600); // Start serial communication at 9600 baud rate
void loop() {
obstacle_pres = digitalRead(2); // Read digital input from pin 2
if (obstacle_pres == LOW) {
Serial.print("Obstacle is present");
digitalWrite(13, HIGH); // Turn ON LED if obstacle detected
else {
digitalWrite(13, LOW); // Turn OFF LED if no obstacle
delay(1000); // Wait 1 second before next check
🧠 Line-by-Line Code Explanation
🔸 int obstacle_pres = 0;
• Declares an integer variable obstacle_pres to store the digital reading
from the obstacle sensor.
🔸 void setup()
• The setup() function is called once when the program starts.
• Used to configure pin modes and initialize serial communication.
Inside setup():
Code Explanation
Configures digital pin 2 as an input pin to receive signal from the
pinMode(2, INPUT);
sensor.
pinMode(13,
Configures digital pin 13 as an output pin to control an LED.
OUTPUT);
Code Explanation
Starts serial communication at a baud rate of 9600 bits per
Serial.begin(9600);
second for debugging output in the Serial Monitor.
🔸 void loop()
• The loop() function runs repeatedly, checking for obstacles in real time.
Inside loop():
Code Explanation
obstacle_pres = Reads the digital value from pin 2 and stores it in the
digitalRead(2); variable obstacle_pres. Value is either LOW (0) or HIGH (1).
🔸 if (obstacle_pres == LOW)
• If the sensor detects an obstacle, it outputs LOW (0).
• In this case:
• "Obstacle is present" is printed on the Serial Monitor.
• The LED (pin 13) is turned ON using digitalWrite(13, HIGH);
🔸 else { digitalWrite(13, LOW); }
• If no obstacle is detected, the output is HIGH (1).
• The LED is turned OFF.
🔸 delay(1000);
• Adds a delay of 1000 milliseconds (1 second) between each reading.
• Prevents rapid blinking of the LED or spamming the serial monitor.
⚙️Function Used: digitalRead()
➤ Syntax:
cpp
CopyEdit
digitalRead(pin);
➤ Description:
• This function reads the digital input (either 0 or 1) from a specified pin.
• Returns:
• LOW (0) → if the voltage is close to 0V
• HIGH (1) → if the voltage is close to 5V
🧪 Output Behavior:
Obstacle Sensor LED
Serial Output
Condition Output Status
Obstacle “Obstacle is
LOW (0) ON
Detected present”
No Obstacle (No message
HIGH (1) OFF
Detected displayed)
✅ Conclusion:
This code successfully detects obstacles using an IR-based sensor and indicates it
using an LED and Serial Monitor. It uses basic Arduino functions like
digitalRead(), digitalWrite(), pinMode(), and Serial.print() to interact with the
sensor and provide real-time feedback. This simple but powerful setup forms the
base for robotics, automation, and safety applications.
#################################################
#####.
HC-SR04 Ultrasonic Sound Sensor – Detailed
Notes
🧠 What is it?
• The HC-SR04 is an Ultrasonic Distance Measuring Sensor.
• It uses ultrasonic waves (sound waves beyond human hearing) to detect
the distance of an object.
• It works on the echo principle — like how bats navigate using
echolocation.
🎯 Key Features:
• Measures Distance: It detects how far an object is — from 2 cm to 400
cm (or 4 meters) with good accuracy.
• Does Not Detect Object Type: It only tells how far something is — it
can’t recognize what the object actually is (e.g., person, wall, box, etc.).
• Other Name: Also called an Ultrasonic Proximity Sensor or Ultrasonic
Range Finder.
Pinout of HC-SR04 Sensor:
Pin
Description
Name
Vcc Power supply pin — connect to 5V
Gnd Ground pin — connect to GND of Arduino
Trigger Input pin — used to send ultrasonic wave
Output pin — receives reflected wave
Echo
from the object
Pin Function Explanation:
• Vcc:
• This is the power input pin.
• It should be connected to a 5V supply (usually from Arduino).
• Gnd (Ground):
• Common ground connection between sensor and microcontroller.
• Trigger:
• Acts like a start button for the sensor.
• When a HIGH pulse of at least 10 microseconds is given, it sends
an ultrasonic wave at 40kHz.
• Echo:
• This pin goes HIGH when the reflected signal is received.
• The duration of this HIGH pulse is used to calculate the distance.
🔄 Typical Use-Case Circuit (with Arduino):
• Vcc → 5V (Arduino)
• Gnd → GND (Arduino)
• Trigger → Any digital pin (e.g., pin 9)
• Echo → Any digital pin (e.g., pin 10)
Working Principle:
1. Trigger Pulse:
• The microcontroller (like Arduino) sends a high pulse (of 10
microseconds) to the Trigger pin.
• This activates the sensor to emit ultrasonic waves at 40 kHz
through the transmitter.
2. Sound Wave Propagation:
• The ultrasonic waves travel through the air.
• When they hit an object, they bounce back (this is called an echo).
3. Receiving Echo:
• The Echo pin goes HIGH and the sensor measures the time
between sending and receiving the pulse.
4. Time to Distance Calculation:
• The time taken by the ultrasonic wave to return is used to calculate
the distance using the speed of sound.
• Speed of sound is 343 m/s (or 0.0343 cm/µs).
5. Distance Formula:
Distance=Time×Speed of sound2\text{Distance} = \frac{\text{Time} \
times \text{Speed of sound}}{2}Distance=2Time×Speed of sound
Why divide by 2? Because the wave travels to the object and
comes back – so we only need half of the round-trip time.
6. Output:
• The distance is calculated in centimeters and can be printed on a
serial monitor or used in a robot to avoid obstacles.
L;DR Version:
🔹 You give a signal → sensor sends sound
🔹 It waits for sound to come back → ECHO pin = HIGH
🔹 As soon as it hears it back → ECHO = LOW
🔹 You measure how long ECHO was HIGH = that gives distance.
Key Points:
• Very commonly used in IoT, robotics, automatic parking, and security
systems.
• Safe and accurate for short-range object detection (typically up to 400
cm).
• Doesn’t work well with soft materials (like cloth or sponge) as they absorb
sound.
HC-SR04 Ultrasonic Sound Sensor – Interfacing
with Arduino
• The HC-SR04 ultrasonic sensor is used for measuring distance using
ultrasonic waves.
• It has 4 pins: Vcc, Gnd, Trigger, and Echo.
✅ Basic Interfacing Setup:
• Vcc pin of HC-SR04 is connected to 5V pin of Arduino.
• Gnd pin of HC-SR04 is connected to GND pin of Arduino.
• Trigger pin is connected to digital pin 11 of Arduino.
• Echo pin is connected to digital pin 12 of Arduino.
⚙️Explanation of Pin Functions:
• Trigger pin (input): This pin is used to generate ultrasonic waves.
Arduino sends a 10µs HIGH pulse to this pin to trigger the sensor.
• Echo pin (output): This pin goes HIGH once the echo is received back after
reflection. The duration of this HIGH pulse helps calculate the distance.
Interfacing HC-SR04 with Arduino
📌 Connections
• Vcc of HC-SR04 → 5V on Arduino
• GND of HC-SR04 → GND on Arduino
• Trigger Pin of HC-SR04 → Digital Pin 11 on Arduino
• Echo Pin of HC-SR04 → Digital Pin 12 on Arduino
🧠 How HC-SR04 Works
• HC-SR04 sends an ultrasonic wave when Trigger pin is HIGH for 10
microseconds.
• The wave reflects back from an object and is received by the Echo pin.
• Echo pin stays HIGH for the duration of wave travel (to the object and
back).
• Using the time and speed of sound, we calculate distance.
Arduino Code with Explanation
cpp
CopyEdit
int trigPin = 11; // Pin to send signal to sensor (Trigger)
int echoPin = 12; // Pin to receive signal from sensor (Echo)
long duration; // Stores the time taken for echo to return
long cm, inches; // Stores calculated distance in cm and inches
void setup() {
Serial.begin(9600); // Start Serial Monitor at 9600 baud rate
pinMode(trigPin, OUTPUT); // Set trigger pin as OUTPUT
pinMode(echoPin, INPUT); // Set echo pin as INPUT
void loop() {
digitalWrite(trigPin, LOW); // Clear Trigger
delayMicroseconds(5); // Short delay
digitalWrite(trigPin, HIGH); // Trigger the sensor by HIGH pulse
delayMicroseconds(10); // 10 microsecond pulse
digitalWrite(trigPin, LOW); // Turn trigger back to LOW
// Read the time for echo to return
duration = pulseIn(echoPin, HIGH);
// Calculate distance:
// speed of sound = 343 m/s = 0.0343 cm/µs
// time = to and fro → so divide by 2
cm = (duration / 2) / 29.1; // Convert time to distance (cm)
inches = (duration / 2) / 74; // Convert time to distance (inches)
// Print values
Serial.print(inches);
Serial.print(" in, ");
Serial.print(cm);
Serial.print(" cm");
Serial.println();
delay(250); // Wait for a short time before next reading
📐 Why divide by 29.1 or 74?
Because:
• Speed of sound = 343 m/s = 0.0343 cm/µs
• So:
Distance=Speed×Time\text{Distance} = \text{Speed} \times \
text{Time}Distance=Speed×Time
• But we get total time (go + return), so:
Distance=Time2×0.0343\text{Distance} = \frac{Time}{2} \times
0.0343Distance=2Time×0.0343
⇒ divide by 29.1 (1 / 0.0343) to convert to cm
⇒ divide by 74 for inches
📌 Key Functions
Function Description
pinMode(pin, mode) Sets pin as INPUT or OUTPUT
digitalWrite(pin, state) Sends HIGH or LOW signal
delayMicroseconds(time) Pauses code for specific µs
Measures how long pin stays HIGH
pulseIn(pin, HIGH)
(in µs)
Function Description
Serial.begin(9600) Starts serial communication
Serial.print() / println() Prints data on Serial Monitor
Code Breakdown: HC-SR04 Ultrasonic Sensor
cpp
CopyEdit
int trigPin = 11; // Trigger pin
int echoPin = 12; // Echo pin
long duration, cm, inches;
• trigPin sends out the ultrasonic sound pulse.
• echoPin waits to receive the pulse after it bounces back from an object.
• duration holds how long it took the pulse to return.
• cm and inches store the calculated distance.
⚙️setup() Function
cpp
CopyEdit
void setup() {
Serial.begin (9600); // Start serial communication at 9600 bps
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
• Serial.begin(9600) lets the Arduino talk to your PC.
• We set trigPin as OUTPUT because we’re sending a signal.
• We set echoPin as INPUT because we’re receiving a signal.
🔁 loop() Function
cpp
CopyEdit
digitalWrite(trigPin, LOW); // Clear the trigger pin
delayMicroseconds(5); // Wait 5 microseconds
digitalWrite(trigPin, HIGH); // Send a HIGH signal
delayMicroseconds(10); // For 10 microseconds (the pulse)
digitalWrite(trigPin, LOW); // Turn the trigger off
• We clear the pin, give a tiny delay, then send a 10 microsecond pulse to
"ping" an object.
cpp
CopyEdit
duration = pulseIn(echoPin, HIGH); // Waits for echo and measures time in µs
• pulseIn() reads how long the echoPin stayed HIGH, i.e., how long the pulse
took to bounce back.
📏 Calculating Distance
cpp
CopyEdit
cm = (duration / 2) / 29.1;
inches = (duration / 2) / 74;
But wait… why /2 and /29.1?
Let’s break the physics:
• Sound travels at 343 m/s = 0.0343 cm/µs
• Distance = Speed × Time
• But the time we measure (duration) is round-trip (to the object and back)
• So we divide by 2 to get one-way
• So,
makefile
CopyEdit
distance = (duration / 2) × 0.0343 cm/µs
≈ (duration / 2) / 29.1
📤 Displaying Output
cpp
CopyEdit
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(250);
• Prints the distance in inches and cm.
• delay(250) gives a short pause (250 ms) before repeating.
🔍 Arduino Functions Used
✅ delayMicroseconds(µs)
• Pauses the program for µs microseconds.
• Used for super short delays (like when sending a 10µs pulse).
Syntax:
cpp
CopyEdit
delayMicroseconds(10); // waits 10 microseconds
✅ pulseIn(pin, value)
• Watches a pin and measures the time it stays HIGH or LOW.
Syntax:
cpp
CopyEdit
pulseIn(echoPin, HIGH);
• Returns duration in microseconds (µs).
• We use HIGH because we want to measure the time when the echo is
received back (which makes the echoPin go HIGH).
Final Output
You’ll see something like:
go
CopyEdit
10in, 25cm
Every 250 milliseconds, it shows how far an object is from the sensor.
💡 Summary
Part Function
trigPin Sends the ping
echoPin Waits for echo
Part Function
pulseIn() Measures echo duration
/2 For one-way trip
To convert time to distance
/29.1
in cm
delayMicroseconds() For precise timing
#################################################
#####
Alright, here’s the easy but detailed difference between LDR, PIR, and DHT
sensors — perfect for your IoT notes and viva.
INTRODUCTION TO LDR SENSOR (Light
Dependent Resistor)
📘 Definition
An LDR (Light Dependent Resistor), also known as a photoresistor, is an
electronic component whose resistance changes with the intensity of
light falling on it. It is a passive sensor, meaning it doesn’t produce any signal on
its own — it just reacts to light levels.
🧠 Basic Principle
LDR works on the principle of photoconductivity.
Photoconductivity is the property of a material to change its
electrical conductivity when exposed to light.
So, when light hits the LDR:
• More light → more conductivity (less resistance)
• Less light → less conductivity (more resistance)
Construction & Material
LDRs are usually made from semiconductor materials like cadmium sulfide
(CdS). These materials are photosensitive, meaning they react to light.
They have a zig-zag track (resistive path) of CdS material laid out between two
metal contacts, enclosed in a plastic or epoxy casing with a transparent top so
that light can fall on the surface.
⚙️Working Principle of LDR (Ohm’s Law
Based)
LDRs follow Ohm’s Law (V = I × R). Their working is simple but smart:
1. When light intensity increases, more photons hit the CdS material.
2. This releases more charge carriers (electrons), making it easier for
current to flow.
3. So, resistance decreases.
4. As per Ohm’s law, this causes the voltage across LDR to change.
💡 Hence, more light = less resistance = higher current = measurable
voltage change.
📊 How It Detects Light
In a voltage divider circuit:
• One side is the LDR,
• The other is a known resistor.
• The output voltage is taken from between them.
Depending on how much light hits the LDR:
• You get a different output voltage.
• This voltage can be measured using Arduino, Raspberry Pi, or any
microcontroller.
LDR Sensor – Arduino Code Explanation
Filename: Light-intensity-measure.ino
✅ 1. Objective of the Code
The code reads light intensity using an LDR sensor connected to analog pin A0
of the Arduino. Based on the amount of light detected, it prints:
• "Darker" if it’s too dark
• "Too Bright" if the light is too intense
✅ 2. Code Listing
cpp
CopyEdit
void setup()
{
pinMode(A0, INPUT); // Set pin A0 as input (optional, analogRead handles this by default)
Serial.begin(9600); // Initialize Serial Monitor at 9600 baud rate
void loop()
int light_intensity = analogRead(A0); // Read analog value (0-1023) from LDR
if (light_intensity > 800) // Condition for low light (dark area)
Serial.println("Darker"); // Print "Darker" on Serial Monitor
else if (light_intensity < 500) // Condition for high light (bright area)
Serial.println("Too Bright"); // Print "Too Bright" on Serial Monitor
delay(1000); // Wait for 1 second before next reading
✅ 3. Detailed Line-by-Line Explanation
🔸 void setup()
• This function runs once at the start.
• pinMode(A0, INPUT);
• Sets analog pin A0 as an input (optional, as analogRead() does this
automatically).
• Serial.begin(9600);
• Starts communication with the Serial Monitor at 9600 bits/sec, so
we can see the output on the computer.
🔸 void loop()
• This function repeats continuously.
• int light_intensity = analogRead(A0);
• Reads the voltage (converted to a value between 0–1023) from LDR.
• Higher value → darker environment.
• Lower value → brighter environment.
🔸 if (light_intensity > 800)
• If the light level is too low (i.e., environment is dark), analog value is high.
• It prints:
👉 "Darker"
🔸 else if (light_intensity < 500)
• If the light level is very high (i.e., environment is bright), analog value is
low.
• It prints:
👉 "Too Bright"
🔸 delay(1000);
• Waits for 1000 milliseconds (1 second) before reading again.
• This prevents the messages from printing too quickly on the Serial Monitor.
✅ 4. Sample Output
analogRead Output on Serial
Light Condition
Value Monitor
Very Bright
< 500 "Too Bright"
(daylight)
Dim / Dark room > 800 "Darker"
Medium light (500–
-- (No message printed)
800)
#################################################
#####
GPS Sensor – Detailed Notes (Point-wise Format)
✅ 1. Purpose of GPS Sensor
• A GPS (Global Positioning System) sensor is used to determine the exact
geographical location of the place where it is placed.
• It provides information like latitude, longitude, altitude, and sometimes
time and speed.
✅ 2. Working Principle
• The GPS sensor receives signals from multiple satellites orbiting the
Earth.
• By calculating the time taken for signals to reach the sensor, it determines
its position through trilateration.
✅ 3. Data Format – NMEA
• The data sent by the GPS sensor is in NMEA (National Marine
Electronics Association) format.
• NMEA is a standard communication format used globally, especially by
the marine department for navigation and communication.
• It includes structured sentences that begin with $ and provide data like:
• Time
• Latitude & Longitude
• Altitude
• Number of satellites
• Fix status
✅ 4. Market Variants
• Multiple types of GPS sensors are available in the market.
• The selection of a specific sensor depends on:
• Accuracy required
• Power consumption
• Antenna type
• Size and budget of the project
✅ 5. Sensor Used – GY-GPS6MV2
• In this case, the GY-GPS6MV2 module is used.
• It is a commonly used GPS sensor in Arduino-based projects.
• It is known for being compact, reliable, and beginner-friendly.
✅ 6. Pinout of GY-GPS6MV2 GPS Module
Pi Nam
Function Connection
n e
Provides power to the sensor
1 Vcc Connected to Arduino 5V
module
Common ground for the module
2 GND Connected to Arduino GND
and Arduino
Transmits serial data (NMEA Connects to Arduino’s RX pin (or
3 TX
sentences) SoftwareSerial RX)
Usually not used unless advanced
4 RX Receives serial data (optional)
configuration is needed
✅ 7. Usage Summary
• The GPS module is connected to Arduino using serial communication.
• Arduino receives the location data in NMEA format via the TX pin of the
sensor.
• This data can be used in applications like:
• Vehicle tracking
• Navigation systems
• Drones
• Outdoor automation
• Geo-fencing
GPS Sensor – Working Principle (Point-wise
Explanation)
✅ 1. Placement of the Sensor
• The GPS sensor is installed in the system (such as a vehicle, device, or
object) whose real-time location needs to be tracked.
• This could be any mobile or stationary system depending on the application.
✅ 2. Communication with GPS Satellites
• Once powered, the GPS sensor initiates communication with multiple
GPS satellites orbiting the Earth.
• These satellites continuously broadcast their position and time data.
✅ 3. Receiving Location Information
• The GPS satellite sends back the current geographic coordinates to the
GPS device.
• The location information is provided in the form of:
• Latitude
• Longitude
• These two values together represent the exact position of the system on
the Earth’s surface.
✅ 4. Data Format and Transmission
• The GPS sensor transmits this location data to the microcontroller
(like Arduino) using a predefined standard format.
• Typically, this format is NMEA, which includes structured sentences
readable by the microcontroller.
✅ 5. Data Extraction by Microcontroller
• The microcontroller receives the transmitted data from the GPS
sensor.
• From this data, we can extract the tracked location values (latitude and
longitude).
• These values can then be displayed, stored, or used for further control logic
like navigation, alerts, or mapping.
Visual Summary (Based on Your Description)
pgsql
CopyEdit
[GPS Device with Antenna]
⇅
[Communicates with Satellites]
[Receives Latitude & Longitude]
[Transmits to Microcontroller in predefined format]
[Tracked Location is Extracted]
GPS Sensor – Interfacing with Arduino Uno
1. Basic Connection:
• Connect Vcc pin of GPS sensor to Arduino's 5V.
• Connect GND pin to Arduino's GND.
2. Serial Communication:
• GPS uses serial communication to send data.
• Connect:
• Tx pin of GPS to Arduino's Rx
• Rx pin of GPS to Arduino's Tx (only if bidirectional
communication is needed; mostly Tx is enough for receiving
data).
3. Why Use Software Serial:
• Arduino Uno has only one hardware serial port (connected to USB
for Serial Monitor).
• So, to read GPS data and show it on Serial Monitor
simultaneously, we use SoftwareSerial library in Arduino.
• This allows us to assign any two digital pins as extra serial
communication pins (e.g., D3 and D4).
GPS Sensor – Code Explanation
🔹 Header Files and Object Initialization
cpp
CopyEdit
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
1. <TinyGPS++.h>:
• A library that provides functions to parse GPS data such as location,
time, speed, etc.
• Makes working with raw NMEA data easier.
2. <SoftwareSerial.h>:
• Enables serial communication on digital pins (not default pins 0 and
1).
• Essential when using multiple serial devices.
cpp
CopyEdit
static const int RXPin = 3, TXPin = 2;
static const uint32_t GPSBaud = 9600;
TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);
3. RXPin = 3, TXPin = 2:
• Defines the digital pins used for receiving and transmitting GPS data.
4. GPSBaud = 9600:
• Sets the baud rate for GPS module (usually 9600 bps for most
modules).
5. TinyGPSPlus gps;:
• Creates a gps object to access GPS functions like gps.location.lat().
6. SoftwareSerial ss(RXPin, TXPin);:
• Initializes a ss (software serial) object on pins 3 (Rx) and 2 (Tx).
🔹 setup() Function
cpp
CopyEdit
void setup() {
Serial.begin(115200);
ss.begin(GPSBaud);
7. Serial.begin(115200);:
• Starts the Serial Monitor for displaying output to the user.
8. ss.begin(GPSBaud);:
• Starts communication with the GPS module via software serial.
🔹 loop() Function
cpp
CopyEdit
void loop() {
while (ss.available() > 0)
gps.encode(ss.read());
displayInfo();
if (millis() > 5000 && gps.charsProcessed() < 10) {
Serial.println("No GPS detected: Check wiring.");
while (true);
9. ss.available() > 0:
• Checks if GPS is sending any data.
10.gps.encode(ss.read()):
• Reads the incoming data byte-by-byte and encodes/parses it using
TinyGPS++.
11.displayInfo();:
• A custom function that prints the current GPS location.
12.GPS Not Detected Check:
• If no GPS data is processed in 5 seconds (gps.charsProcessed() < 10), the
system prints a warning.
🔹 displayInfo() Function
cpp
CopyEdit
void displayInfo() {
Serial.print("Location: ");
if (gps.location.isValid()) {
Serial.print(gps.location.lat(), 6);
Serial.print(",");
Serial.print(gps.location.lng(), 6);
Serial.println();
13.gps.location.isValid():
• Returns true if GPS has locked on a satellite and the location data is valid.
14.gps.location.lat(), 6:
• Fetches the latitude with 6 decimal points precision.
15.gps.location.lng(), 6:
• Fetches the longitude with 6 decimal points precision.
16.Displays Output:
• The format printed to the Serial Monitor is: Location:
<latitude>,<longitude>
📝 Summary
• GPS Sensor provides real-time location using serial communication.
• Uses SoftwareSerial to avoid conflict with USB communication.
• TinyGPS++ simplifies parsing raw GPS data.
• The code reads, encodes, and displays location with proper error handling if
GPS is not detected.
#################################################
#####.
GYRO SENSOR – Detailed Theoretical
Notes
✅ Introduction
The Gyro sensor is an essential component in many modern electronic systems,
especially in wearable devices. It plays a key role in detecting the movement
and orientation of a device or body. This ability makes it useful in fitness bands,
smartwatches, motion-sensing games, and healthcare wearables.
✅ Purpose of the Gyro Sensor
• The main purpose of a gyro sensor is to determine the position and angle
of rotation of the body it is attached to.
• In simple terms, it helps the system understand whether the object is
tilting, turning, or spinning.
✅ Primary Functions / What It Senses
The gyro sensor is built to sense:
1. Rotational Motion
• This refers to the spinning or angular movement of a device.
• For example, if a person turns their wrist while wearing a smartwatch,
the gyro sensor detects that turning motion.
2. Changes in Orientation
• It helps identify shifts in direction or tilt of a device in space.
• This is useful in determining if the body or gadget has changed its
position from horizontal to vertical or vice versa.
✅ Communication with Microcontroller – I2C Protocol
• The gyro sensor communicates with the microcontroller (like Arduino,
ESP32, etc.) using a protocol known as I2C.
• I2C stands for Inter-Integrated Communication.
• It is one of the most efficient and advanced two-wire communication
methods used in embedded systems.
✅ Key Features of I2C Communication
1. Two-wire Communication
• I2C only requires two lines to communicate:
• SDA (Serial Data Line)
• SCL (Serial Clock Line)
• This makes it easy to connect multiple devices with fewer pins and
wires.
2. Device Addressing
• Every I2C device (like a gyro sensor) is assigned a unique address.
• When communication starts, the microcontroller refers to this address
to identify and talk to that specific sensor.
3. Data Frames
• Communication happens in the form of data frames, which contain:
• The device address
• Read/Write instructions
• Data to be transferred
• These frames are exchanged between the sensor and microcontroller.
✅ Why I2C is Preferred
• I2C is particularly useful when there are many devices connected in a
single system (e.g., Gyro, Accelerometer, Magnetometer).
• Instead of using multiple communication lines, all devices share the same
two wires (SDA and SCL), which saves space and simplifies circuit design
MPU-6050 Gyro Sensor – Working
Principle
✅ 1. Basic Principle
• The MPU-6050 is a sensor module that detects gravitational force and
calculates the inclination or tilt of a device.
• It works by continuously sensing the gravitational pull acting on it in all
directions.
✅ 2. How It Works – Step by Step
🔹 Step 1: Sensor Placement
• First, the MPU-6050 sensor is placed inside the device whose inclination
(tilt/angle) is to be measured.
• Example: A robot, phone, or wearable band where tilt movement is involved.
🔹 Step 2: Detecting Gravity via Axes
• The sensor reads acceleration or motion along three axes:
• X-axis: side-to-side movement
• Y-axis: forward-backward tilt
• Z-axis: up-down vertical movement
• The output values are given as X, Y, Z coordinates, representing the
acceleration due to gravity on each axis.
🔹 Step 3: Sample Values from Sensor
• The MPU-6050 outputs values like:
• x, y, z = 507, 506, 617
• x, y, z = 507, 504, 616
• x, y, z = 506, 505, 617
• x, y, z = 506, 506, 618
• These values keep changing based on how the device is tilted.
🔹 Step 4: Calculating the Elevation Angle
• After receiving raw values from the sensor, the next step is to
mathematically calculate the elevation angle.
• Using formulas like arctangent or vector math, we can determine:
• Pitch (tilt up/down)
• Roll (tilt side to side)
• Yaw (rotation)
Example:
Angle = arctangent (X / √(Y² + Z²)) — depending on which angle you
want to compute.
✅ 3. Summary of Function
Ste
Action
p
1️⃣ Sensor detects gravitational force on it
It is placed in the device where tilt is to
2️⃣
be measured
3️⃣ It outputs X, Y, Z coordinate values
Using math, we calculate the angle of
4️⃣
inclination
✅ Conclusion
The MPU-6050 Gyro Sensor works by detecting gravitational force and then
calculating the inclination angle of a device by analyzing the X, Y, and Z-axis
data. With continuous reading, it allows accurate tracking of tilt and
orientation in real time.
MPU-6050 Gyro Sensor – Interfacing
with Arduino
✅ 1. Introduction
• The MPU-6050 Gyro sensor can be easily interfaced with Arduino Uno to
detect motion, tilt, and angular velocity.
• It communicates with Arduino using the I2C protocol, making the wiring
minimal and efficient.
✅ 2. Power Connection
• The Vcc pin of the MPU-6050 is connected to the 5V pin of the Arduino
Uno.
• The GND pin of the sensor is connected to the GND (Ground) of the
Arduino.
🔋 This ensures that the sensor receives proper power to function.
✅ 3. I2C Communication Pins
• The MPU-6050 communicates using I2C, which requires two lines:
• SCL (Serial Clock Line)
• SDA (Serial Data Line)
🔹 Arduino Side:
• On Arduino Uno, A5 acts as SCL, and A4 acts as SDA.
• So,
• Connect SCL of MPU-6050 → A5 of Arduino
• Connect SDA of MPU-6050 → A4 of Arduino
🧠 These are analog pins, but they serve dual functions. I2C is one of
those alternate roles.
✅ 4. Interrupt Pin (INT)
• The INT pin of the MPU-6050 is used to generate interrupts.
• This pin sends a signal when the angular velocity goes beyond a set
threshold.
• This helps the Arduino detect sudden or fast motion without constantly
checking the sensor.
🔹 Arduino Side:
• The INT pin of MPU-6050 is connected to digital pin 2 of Arduino Uno.
• Pin 2 supports external interrupts, making it ideal for this purpose.
✅ 5. Summary of Connections
MPU-6050 Connects To (Arduino
Function
Pin Uno)
Power
Vcc 5V
Supply
GND GND Ground
I2C Clock
SCL A5
Line
I2C Data
SDA A4
Line
Interrupt
INT D2
Signal
✅ Conclusion
The MPU-6050 can be easily connected to Arduino Uno using just a few wires,
thanks to the I2C protocol. The A4 and A5 pins of Arduino serve as SDA and SCL
lines respectively, and the INT pin enhances performance by enabling interrupt-
driven event detection when motion exceeds the defined threshold. This setup
is ideal for motion tracking, wearable tech, and robotics.
Heartbeat Sensor – Working
Principle (In Easy Words)
✅ 1. How it Senses the Heartbeat
• The heartbeat sensor works by detecting the blood flow in the body.
• Every time your heart beats, blood flows through your veins in a
rhythm.
• The sensor notices these changes in blood flow and uses them to sense
each heartbeat.
✅ 2. Output Signals from the Sensor
• For each heartbeat, the sensor sends out a pulse signal.
• These signals show how fast or slow your heart is beating.
• The output is in the form of square pulses (like ON-OFF signals), which
match your heart's rhythm.
✅ 3. From Pulse to Analog Signal
• These pulse signals are treated as PWM waves (Pulse Width Modulated).
• But microcontrollers work better with smooth signals.
• So, these PWM waves are converted into analog signals — meaning
now the signal has a smooth up-down flow instead of sharp ON-OFF pulses.
✅ 4. From Analog to Digital
• The analog signal (smooth wave) is then converted into digital
numbers using something called ADC (Analog to Digital Converter).
• Now the microcontroller can read the digital values and calculate the
heart rate in beats per minute (BPM).
✅ 5. Simple Step-by-Step Flow
Ste
What Happens
p
Sensor detects heartbeat through blood
1️⃣
circulation
2️⃣ It sends out a pulse for every heartbeat
3️⃣ These pulses are seen as PWM signals
4️⃣ PWM is converted to an analog signal
5️⃣ Analog signal is converted to digital
Microcontroller calculates heart rate from
6️⃣
digital data
✅ Conclusion (In Simple Words)
The heartbeat sensor checks how blood flows when your heart beats. It gives
out pulses that are turned into smooth signals, then into numbers. These
numbers tell the system how fast your heart is beating. Simple, smart, and
useful for health tracking! 💓💻
Heartbeat Sensor – Interfacing with Arduino
• The heartbeat sensor needs to be connected properly with the Arduino
Uno to read the heart rate data.
• There are three main pins on the heartbeat sensor module:
• Vcc – This pin supplies power to the sensor. It should be connected to
the 5V pin of Arduino, so the sensor gets the required voltage to
work.
• GND – This is the ground pin. It should be connected to the GND pin
of Arduino, so that there is a complete electrical circuit.
• A0 (Analog Output) – This is the signal pin. It sends out the pulse
data as analog signals. That’s why it is connected to an analog input
pin on Arduino, typically A0.
• Since the output from the sensor is analog (not just 0 or 1), we need to use
an analog input pin to read the heart rate value. Arduino will then convert
this analog signal to a readable value.
💡 In short:
• Give power (5V) and ground (GND) to the sensor.
• Read the heartbeat signal through analog pin A0.
• This setup lets Arduino measure the person’s heartbeat
continuously.
Heartbeat Sensor – Arduino Code Explanation
🧾 Code Variables (Lines 1–8)
cpp
CopyEdit
int UpperThreshold = 518;
int LowerThreshold = 490;
int reading = 0;
float BPM = 0.0;
bool IgnoreReading = false;
bool FirstPulseDetected = false;
unsigned long FirstPulseTime = 0;
unsigned long SecondPulseTime = 0;
unsigned long PulseInterval = 0;
What it does:
• UpperThreshold & LowerThreshold: These are used to detect when the pulse
crosses a certain range.
👉 When the analog reading goes above 518, it means a heartbeat is
detected.
👉 Below 490 means pulse is over and ready to detect next.
• reading: Stores the current analog value from the sensor.
• BPM: This will hold the final beats per minute.
• IgnoreReading: Prevents double-counting the same beat.
• FirstPulseDetected: Used to know if this is the first beat or not.
• FirstPulseTime & SecondPulseTime: Used to store the timestamps of
detected beats.
• PulseInterval: Time gap between two pulses in milliseconds.
Setup Function (Lines 10–12)
cpp
CopyEdit
void setup(){
Serial.begin(9600);
}
Explanation:
• This starts the serial communication between Arduino and computer at
9600 bps (bits per second), so we can see the BPM value on the Serial
Monitor.
🔁 Loop Function – Pulse Detection Logic (Lines 14–36)
cpp
CopyEdit
void loop(){
reading = analogRead(0); // Read analog value from A0
• Reads the sensor value from analog pin A0 and stores it in reading.
cpp
CopyEdit
if(reading > UpperThreshold && IgnoreReading == false){
• If the current reading is above the threshold and we’re not ignoring it, it
means a new pulse has been detected.
cpp
CopyEdit
if(FirstPulseDetected == false){
FirstPulseTime = millis();
FirstPulseDetected = true;
• If this is the first pulse, save the current time using millis() and mark that
the first pulse is detected.
cpp
CopyEdit
else{
SecondPulseTime = millis();
PulseInterval = SecondPulseTime - FirstPulseTime;
FirstPulseTime = SecondPulseTime;
• If it's the second or later pulse, record the time and calculate the pulse
interval by subtracting the times.
• Then update FirstPulseTime for the next interval.
cpp
CopyEdit
IgnoreReading = true;
}
• This line avoids counting the same pulse multiple times while it’s still high.
⬇️Reset for Next Pulse (Lines 30–31)
cpp
CopyEdit
if(reading < LowerThreshold){
IgnoreReading = false;
• When the signal drops below the lower threshold, it resets
IgnoreReading so we can detect the next beat.
📏 Calculate BPM and Print (Lines 32–36)
cpp
CopyEdit
BPM = (1.0 / PulseInterval) * 60.0 * 1000;
Serial.print(BPM);
Serial.println(" BPM");
Serial.flush();
• Heartbeat rate is calculated using the formula:
BPM=(1PulseInterval)×60×1000\text{BPM}
Why? Because:
• PulseInterval is in milliseconds
• 1Time\frac{1}{\text{Time}}Time1 = Rate
• Multiply by 60,000 to convert milliseconds into beats per minute
• Then it prints the BPM to the Serial Monitor.
Note on millis() Function
cpp
CopyEdit
millis()
• It returns the number of milliseconds since the Arduino started running
the current program.
• Used to measure time between pulses.
✅ Summary Flow:
1. Sensor detects heartbeat (based on analog value).
2. Time between two pulses is recorded.
3. BPM is calculated using time difference.
4. Result is printed to Serial Monitor.
#################################################
#####
Alright Prachi, let’s design this like a boss-level IoT engineer but explained like
you’re chilling on a Sunday afternoon with chai. ☕
We’ll make a simple temperature-based fan control system using Arduino,
a temperature sensor, and a fan as the actuator. Let’s go step-by-step like
you're wiring this on Tinkercad or a real breadboard. ⚡
🔧 Project Title: Temperature Controlled Fan
using Arduino
🧩 Components Used:
Component Description
The brain of the system – processes temperature and
Arduino UNO
controls fan
LM35 / DHT11 Temperature sensor (LM35 gives analog output, DHT11
Sensor gives digital)
Relay Module / Acts as a switch to turn fan ON/OFF (since fan runs on
Transistor 12V/230V)
DC Fan The actuator – it turns ON when temperature is high
Resistors & Wires For safe connection and signal routing
Breadboard For easy prototyping
Arduino (via USB) and external fan power (battery or
Power Supply
adapter)
⚙️Working Logic (Simple Words):
"If the temperature crosses a certain level (say 30°C), the fan
should turn ON. Else, it remains OFF."
1. The temperature sensor continuously reads ambient temperature.
2. Arduino checks the temperature value.
3. If it’s greater than or equal to 30°C, it activates the relay/transistor,
which powers the fan.
4. If it’s below 30°C, the fan remains OFF.
5. Optionally, we can display temperature on Serial Monitor or LCD.
🔁 Logic in Steps:
Read temperature from sensor
Check: Is temperature >= 30°C?
|—— Yes → Turn ON fan
|—— No → Turn OFF fan
💡 Code (for LM35 sensor):
int tempPin = A0; // LM35 connected to analog pin A0
int fanPin = 8; // Fan control pin (via relay/transistor)
float temp; // To store temperature value
void setup() {
pinMode(fanPin, OUTPUT);
Serial.begin(9600);
void loop() {
int reading = analogRead(tempPin);
temp = reading * 0.488; // Convert analog value to Celsius
Serial.print("Temperature: ");
Serial.println(temp);
if (temp >= 30.0) {
digitalWrite(fanPin, HIGH); // Turn fan ON
} else {
digitalWrite(fanPin, LOW); // Turn fan OFF
delay(1000); // Read every second
🪛 Circuit Diagram (Textual Description if Drawing Not
Possible):
[LM35 Sensor]
Vcc -> 5V on Arduino
GND -> GND on Arduino
OUT -> A0 on Arduino
[Relay Module]
IN -> D8 on Arduino
Vcc -> 5V
GND -> GND
[Fan]
One wire -> NO (Normally Open) of Relay
Other wire -> External 12V Power
Common (COM) of Relay -> Ground of external power
👉 If using transistor, connect:
• Base to Arduino pin via 1kΩ resistor
• Collector to fan (-)
• Emitter to GND
• Fan (+) to external power (+)
🔎 Extra Add-ons (For Viva):
• Threshold temperature can be made adjustable using a potentiometer.
• Can send temperature data to cloud via ESP8266 for monitoring.
• Add an LCD to show real-time temperature.
• Use PWM to control fan speed instead of simple ON/OFF.
✅ Conclusion:
This system showcases the basic concept of automation using IoT:
✅ Sensing (LM35)
✅ Processing (Arduino)
✅ Acting (Fan via Relay)
It’s a real-world example of smart climate control, like in ACs, coolers, or
greenhouses.
Wanna see it on a Tinkercad diagram or turn this into a mini-project report?
Say the word and I’m on it.