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

Embedded System

Uploaded by

santhoshvel30
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Embedded System

Uploaded by

santhoshvel30
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Embedded System:

Introduction:

An embedded system combines hardware and software designed to perform a specific


task within a larger device. Unlike regular computers, embedded systems focus on doing one
job well and are built into things like cars, home appliances, and industrial machines.

These systems use microcontrollers or microprocessors, which are small computers on a chip,
to carry out their tasks. They have limited resources, such as memory and processing power,
and the software that runs them is typically written in C or C++.

You can find embedded systems in many everyday items. For example, they control the engine
in your car, manage your smartphone, operate washing machines, and run industrial robots.
They are also crucial in medical devices like pacemakers and diagnostic equipment.

Key parts of an embedded system include:

 A microcontroller or microprocessor (the brain of the system).


 Memory (ROM for storing software and RAM for running programs).
 Input/output interfaces (connecting to sensors and actuators).
 A power supply.
 Communication interfaces (like USB or Ethernet).

Creating an embedded system involves several steps:

 Figuring out what the system needs to do.


 Designing the hardware and software.
 Writing the software and building the hardware.
 Testing and debugging to make sure everything works correctly.
 Integrating the system into the final product.
Internet Of Things (IOT):

The Internet of Things (IoT) connects everyday devices to the internet, allowing them
to collect and share data. These devices, equipped with sensors and software, can communicate
with each other and perform tasks automatically.

Key Points:

 Connectivity: Devices are linked to the internet.


 Sensors: Collect data from the environment (e.g., temperature, motion).
 Automation: Devices can perform tasks based on data.
 Interoperability: Different devices can work together.

Applications:

 Smart Homes: Smart thermostats, lights, and security cameras.


 Healthcare: Wearable devices and remote patient monitoring.
 Industry: Connected machines for efficient manufacturing.
 Transportation: Smart traffic management and vehicle tracking.
 Agriculture: Sensors for soil and crop monitoring.

Components:

 Devices: Objects with sensors and internet connectivity.


 Connectivity: Wi-Fi, Bluetooth, and cellular networks.
 Data Storage: Cloud platforms.
 Data Analytics: Tools to analyze collected data.
 User Interface: Apps and dashboards for control.

Future Trends:

 AI and Machine Learning: Smarter decision-making.


 5G Networks: Faster and more reliable connections.
Basic components:

1. IR SENSOR
2. FLAME SENSOR
3. MOISTURE SENSOR
4. RAIN SENSOR
5. GAS SENSOR
6. ULTRASONIC SENSOR
7. VOLTAGE SENSOR
8. DHT11 SENSOR
9. GYRO SENSOR
10. 10.GPS

Controllers:

1. Arduino(atmega832p)

2. Nodemcu(esp8266)
ARDUINO(ATMEGA832P):

Arduino is an open-source electronics platform that combines hardware and software


to make it easy for anyone to create interactive projects. It consists of microcontroller-based
boards and a user-friendly Integrated Development Environment (IDE) for programming.

Key Features:

 User-Friendly: Designed for beginners and experienced users alike, with a


straightforward programming interface.
 Open Source: Both hardware and software are open-source, allowing users to modify
and share designs.
 Versatile: Supports a wide range of applications, from simple LED projects to complex
robotics and IoT devices.

Arduino Boards:

 Arduino Uno: The most common board, ideal for beginners.


 Arduino Mega: Offers more input/output pins for larger projects.
 Arduino Nano: A compact version for space-constrained projects.

Arduino IDE:

The Arduino IDE allows users to write code (called "sketches") and upload it to the Arduino
board. It supports various libraries that simplify coding for specific sensors and components.

Getting Started:

 Download the IDE: Available for Windows, macOS, and Linux.


 Connect the Board: Use a USB cable to connect your Arduino to your computer.
 Write Your Code: Start with simple projects, like blinking an LED.
 Upload and Test: Use the IDE to upload your code and test your project.

Applications:

 Prototyping: Quickly develop and test ideas.


 Robotics: Build robots and automated systems.
 IoT Projects: Create internet-connected devices.
NODEMCU(ESP8266):

NodeMCU is an open-source firmware and development kit that allows you to create
IoT (Internet of Things) applications. It’s based on the ESP8266 Wi-Fi module, which provides
an easy way to connect to the internet.

Key Features:

 Wi-Fi Connectivity: Built-in Wi-Fi capabilities make it easy to connect to local


networks and the internet.
 Lua Script Support: Originally designed for Lua scripting, it also supports programming
with the Arduino IDE.
 Low Cost: Affordable, making it accessible for hobbyists and developers.

Hardware Overview:

 ESP8266 Chip: The heart of NodeMCU, featuring a powerful microcontroller with Wi-
Fi capabilities.
 GPIO Pins: Multiple General Purpose Input/Output pins for connecting sensors and
devices.
 USB Interface: Typically has a micro USB port for easy power supply and
programming.

Getting Started:

 Download the IDE: You can use the Arduino IDE or the NodeMCU firmware.
 Connect the Board: Use a USB cable to connect NodeMCU to your computer.
 Install Drivers: Ensure you have the necessary USB drivers installed.
 Write Your Code: Use the IDE to write your program.
 Upload: Upload your code to the NodeMCU board.

Applications:

 Home Automation: Control devices remotely using a smartphone or web interface.


 Weather Stations: Collect data from sensors and upload it to the cloud.
 Smart Agriculture: Monitor soil moisture and environmental conditions.
IR SENSOR:

An IR (Infrared) sensor is a device that detects infrared radiation, often used to measure
distance or proximity without physical contact.

Working Principle:

IR sensors work based on the principle that objects emit infrared radiation as heat. The
sensor detects this radiation and converts it into an electrical signal, which can be interpreted
to measure distance or presence.

Types of IR Sensors:

Passive Infrared (PIR) Sensors:

Detect changes in infrared radiation when an object passes in front of the sensor,
commonly used in motion detection systems.

Active Infrared Sensors:

Emit infrared radiation and then detect any reflection off an object to determine its
presence or distance.

Applications:

 Proximity Sensing: Used in mobile phones and robotics for obstacle detection.
 Motion Detection: Security systems, automatic doors, and lighting control.
 Object Counting: In industrial applications to count objects passing through a point.

Advantages:

 Works in darkness and varying lighting conditions.


 Fast response time.
 Non-contact sensing, which can be safer and more reliable in certain applications.

Limitations:

 Susceptible to interference from ambient infrared sources.


 Range and accuracy can vary based on environmental conditions.
 Some types may require calibration to achieve optimal performance.
FLAME SENSOR:

A flame sensor is a device that detects the presence of a flame. It's used to ensure safety
and proper operation in various applications. Here’s a simplified overview:

Types of Flame Sensors:

 Infrared (IR) Flame Sensors: Detects heat from a flame.


 Ultraviolet (UV) Flame Sensors: Detects UV light from a flame.
 Ionization Flame Sensors: Detects ions produced by a flame.
 Photoelectric Flame Sensors: Detects visible light from a flame.

How They Work:

 IR and UV Sensors: Sense specific light wavelengths emitted by flames.


 Ionization Sensors: Detect changes in air ionization caused by a flame.
 Photoelectric Sensors: Use light sensors to detect the flame's glow.

Common Uses:

 Fire Detection Systems: Provide early fire warnings in buildings.


 Industrial Furnaces and Boilers: Ensure safe combustion.
 Gas Heaters and Fireplaces: Confirm flame presence to prevent gas leaks.

Benefits:

 Quick Detection: Fast response to flames.


 Reliable: High sensitivity to flames.
 Non-contact: Detects flames without needing to be close.

Limitations:

 Environmental Factors: Can be affected by dust and smoke.


 Maintenance: Requires regular cleaning.
 Range: Limited detection distance
Moisture Sensor:

Soil moisture sensors measure the water content in soil. They are crucial in
agriculture, landscaping, and environmental science for monitoring and managing soil health
and irrigation.

Capacitive Soil Moisture Sensors:

Principle: Measures the soil's dielectric permittivity, which varies with moisture content.

Advantages: Durable, less prone to corrosion, and long-lasting.

Resistive Soil Moisture Sensors:

Principle: Measures electrical resistance between two probes inserted into the soil.

Advantages: Simple and inexpensive.

Time Domain Reflectometry (TDR):

Principle: Measures the time it takes for an electromagnetic pulse to travel through the soil.

Advantages: Highly accurate and can measure over a range of soil types.

Gypsum Block Sensors:


Principle: Uses gypsum blocks that change resistance with moisture.
Advantages: Suitable for long-term monitoring and is relatively inexpensive.

Applications:

Agriculture:

Irrigation Management: Helps farmers optimize watering schedules, reducing water usage
and improving crop yield.

Soil Health Monitoring: Ensures optimal moisture levels for different crops.
Gardening and Landscaping:

Water Conservation: Prevents overwatering and promotes healthy plant growth.

Automation: Can be integrated into automated watering systems.

Environmental Monitoring:

Drought Prediction: Helps in assessing drought conditions and planning for water resources.

Soil Erosion Prevention: Maintains soil stability by monitoring moisture levels.

Research:

Soil Studies: Used in scientific research to study soil properties and behavior under different
moisture conditions.

Advantages:

 Water Efficiency: Reduces water waste by providing precise moisture measurements.


 Crop Health: Improves plant health and yield by maintaining optimal soil moisture.
 Cost Savings: Lowers water and labor costs by optimizing irrigation.

Limitations:

 Calibration: May require regular calibration to maintain accuracy.


 Soil Variability: Different soil types can affect sensor readings.
 Maintenance: Sensors can be affected by soil salinity and require maintenance.
RAIN SENSOR:
A rain sensor detects precipitation and can trigger various actions based on its detection,
such as pausing irrigation systems or closing windows. They are used in a variety of
applications to conserve water, protect property, and automate responses to changing weather
conditions.

How Rain Sensors Work:


1. Optical Rain Sensors:
Principle: Uses an infrared LED and a photodiode. When raindrops hit the sensor, they scatter
the infrared light, which the photodiode detects.
Advantages: Quick response time, high sensitivity.
2. Conductive Rain Sensors:
Principle: Measures the change in electrical conductivity when rainwater creates a conductive
path between two electrodes.
Advantages: Simple and cost-effective.
3. Capacitive Rain Sensors:
Principle: Measures changes in capacitance caused by the presence of rainwater on the sensor
surface.
Advantages: Durable and less prone to corrosion.
Applications:
1. Irrigation Systems:
Function: Pauses or stops irrigation during rainfall to conserve water.
Benefit: Prevents overwatering and saves water.
2. Automotive:
Function: Automatically activates windshield wipers when rain is detected.

Benefit: Enhances driver convenience and safety.


3. Home Automation:
Function: Closes windows or skylights during rain.
Benefit: Protects interiors from water damage.
4. Weather Stations:
Function: Provides real-time data on precipitation.
Benefit: Useful for weather forecasting and climate studies.
Advantages:
 Water Conservation: Automatically adjusts irrigation to prevent water waste.
 Convenience: Automates responses to rain, reducing the need for manual intervention.
 Protection: Helps protect property from water damage by closing windows or halting
certain operations.
Limitations:
 Sensitivity: Some sensors may require calibration to accurately detect light rain.
 Maintenance: Sensors exposed to the elements can accumulate dirt and debris, affecting
performance.
 Cost: Advanced sensors, like optical ones, can be more expensive.
GAS SENSOR:

A gas sensor detects the presence and concentration of gases in the air. These sensors
are vital for safety, environmental monitoring, and various industrial processes.

Types of Gas Sensors:

1. Electrochemical Gas Sensors:

Principle: Uses a chemical reaction to produce an electrical signal proportional to the gas
concentration.

Common Gases Detected: Oxygen, carbon monoxide, hydrogen sulfide.

Advantages: High sensitivity, specificity to certain gases.

2. Semiconductor Gas Sensors:

Principle: Measures changes in electrical conductivity of a semiconductor material when


exposed to a gas.

Common Gases Detected: Methane, propane, butane.

Advantages: Low cost, long lifespan.

3. Catalytic Bead Sensors:

Principle: Oxidizes combustible gases on a catalyst-coated bead, causing a temperature rise


that changes the bead's resistance.

Common Gases Detected: Methane, propane, hydrogen.

Advantages: Good for detecting combustible gases.

4. Infrared (IR) Gas Sensors:


Principle: Measures the absorption of infrared light by gas molecules.

Common Gases Detected: Carbon dioxide, methane.

Advantages: Non-contact measurement, stable and long-lasting.

5. Photoionization Detectors (PID):

Principle: Uses ultraviolet light to ionize gas molecules, producing an electrical current
proportional to the concentration.

Common Gases Detected: Volatile organic compounds (VOCs).

Advantages: High sensitivity to low concentrations of organic vapors.

Applications:

1. Safety Systems:

Function: Detect hazardous gases to prevent poisoning, explosions, and fire.

Applications: Industrial plants, laboratories, mines.

2. Environmental Monitoring:

Function: Monitor air quality and pollution levels.

Applications: Urban areas, industrial zones, environmental research.

3. Industrial Processes:

Function: Control gas concentrations in various manufacturing processes.

Applications: Chemical manufacturing, food processing, HVAC systems.

4. Edical Applications:

Function: Monitor respiratory gases and detect specific gases for diagnosis.

Applications: Anesthesia machines, respiratory therapy, patient monitoring.

Advantages:

 Safety: Provides early warning of dangerous gas levels, preventing accidents.


 Environmental Protection: Helps monitor and control pollution.
 Process Control: Ensures optimal conditions in industrial processes.
Limitations:

 Calibration: Requires regular calibration for accurate readings.


 Selectivity: Some sensors may respond to multiple gases, leading to false readings.
 Environmental Factors: Temperature and humidity can affect sensor performance.
Ultrasonic Sensor:

An ultrasonic sensor measures distance using sound waves, commonly used for
obstacle detection, level sensing, and distance measurement in various applications.

How Ultrasonic Sensors Work:

Principle:

Sound Waves: Emits high-frequency sound waves (ultrasound) that are beyond the range of
human hearing (typically 20 kHz to 200 kHz).

Echo: The sensor sends out a sound wave and listens for the echo that bounces back from an
object.
Distance Calculation: The time taken for the echo to return is used to calculate the distance
to the object using the speed of sound (approximately 343 meters per second in air at room
temperature).
Components:
 Transmitter: Emits the ultrasonic sound waves.
 Transmitter: Emits the ultrasonic sound waves.
 Control Circuit: Calculates the time interval between the emission and reception of the
sound wave to determine the distance.

Applications:

 Robotics: Navigation and obstacle avoidance.


 Industrial Automation: Measuring distance to objects or levels in tanks.
 Obstacle Detection:
 Automotive: Parking sensors in cars.
 Drones: Avoiding obstacles during flight.

Level Sensing:
 Water Tanks: Monitoring liquid levels.
 Silos: Measuring levels of solids like grains.
 Object Detection and Counting:
 Conveyor Belts: Detecting and counting objects.

Advantages:

 Non-contact Measurement: Measures distance without physical contact.


 Versatility: Works with various materials (solids, liquids, powders).
 Reliability: Provides accurate and consistent measurements.
 Safety: Safe for use in hazardous environments.

Limitations:

 Environmental Conditions: Affected by temperature, humidity, and air pressure.


 Surface Requirements: Works best with flat, hard surfaces. Soft or irregular surfaces
can scatter sound waves.
 Range: Limited by the sensor’s sensitivity and the distance sound waves can travel.
VOLTAGE SENSOR:

A voltage sensor measures the voltage level in an electrical circuit. It is essential in


various applications for monitoring and controlling electrical systems, ensuring safety, and
optimizing performance.

Principle:

 Direct Measurement: Measures the voltage directly across two points in a circuit.
 Indirect Measurement: Uses a transducer to convert voltage into a readable signal (e.g.,
voltage-to-frequency or voltage-to-current conversion).

Components:

 Sensing Element: Detects the voltage.


 Signal Conditioning: Amplifies, filters, and processes the signal.
 Output: Provides a readable signal (analog or digital).

Types of Voltage Sensors:

Analog Voltage Sensors:

 Principle: Provides a continuous analog output signal proportional to the voltage


measured.
 Applications: Simple monitoring systems, signal processing.

Digital Voltage Sensors:

 Principle: Converts the voltage measurement into a digital signal.


 Applications: Microcontroller-based systems, digital signal processing.

Differential Voltage Sensors:

 Principle: Measures the difference in voltage between two points.


 Applications: Monitoring voltage drops across components, battery management
systems.

Applications:

1. Power Systems:

Function: Monitor voltage levels to ensure stable power supply.

Applications: Power grids, transformers, and distribution systems.

2. Battery Management:

Function: Monitor battery voltage to optimize charging and discharging.

Applications: Electric vehicles, renewable energy storage systems.

3. Industrial Automation:

Function: Control and monitor machinery and processes.

Applications: Factory automation, robotics, and control systems.

4. Consumer Electronics:

Function: Monitor and control voltage in electronic devices.

Applications: Smartphones, laptops, and household appliances.

5. Automotive Systems:

Function: Monitor voltage in various vehicle systems.

Applications: Engine control units, battery monitoring, and infotainment systems.

Advantages:

 Accuracy: Provides precise voltage measurements.


 Safety: Helps prevent overvoltage and undervoltage conditions.
 Efficiency: Optimizes performance by ensuring proper voltage levels.

Limitations:

 Range: Limited by the sensor’s designed voltage range.


 Calibration: Requires regular calibration for accurate measurements.
 Environmental Factors: Sensitive to temperature and electromagnetic interference.
DHT11 SENSOR:

The DHT11 sensor is a popular, low-cost sensor used to measure temperature and
humidity. It is widely used in hobbyist projects, weather stations, home automation systems,
and various environmental monitoring applications due to its simplicity and ease of use.

Features of the DHT11 Sensor:

Temperature Measurement:
 Range: 0 to 50°C (32 to 122°F)
 Accuracy: ±2°C
Humidity Measurement:
 Range: 20% to 90% Relative Humidity (RH)
 Accuracy: ±5% RH
 Operating Voltage: 3.5V to 5.5V
 Output: Digital signal via a single data pin
 Sampling Rate: Approximately 1 reading per second (1 Hz)

Components:

 Humidity Sensor: Measures the relative humidity in the air.


 Thermistor: Measures the ambient temperature.
 Microcontroller: Processes the readings from the humidity sensor and thermistor and
outputs a digital signal.
 Pin Configuration
 VCC: Power supply (3.5V to 5.5V)
 Data: Serial data output
 NC: Not connected (used as a spacer in the 4-pin version)
 GND: Ground
How It Works:

1. Humidity Measurement: The DHT11 uses a capacitive humidity sensor to measure the
moisture in the air. The sensor contains a pair of electrodes with a moisture-holding substrate
between them. The capacitance changes with the humidity level, which the sensor converts into
a digital signal.
2. Temperature Measurement: The sensor uses a thermistor to measure the temperature.
The resistance of the thermistor changes with temperature, and this change is converted into a
digital signal.
3. Data Transmission: The DHT11 sensor uses a proprietary 1-wire protocol to transmit
the temperature and humidity data to a microcontroller or other receiving device.

Applications:

 Weather Stations: Used to monitor and record temperature and humidity.


 Home Automation: Integrates into systems for controlling heating, ventilation, and air
conditioning (HVAC) based on environmental conditions.
 Greenhouses: Monitors and maintains optimal temperature and humidity for plant
growth.
 Industrial Automation: Ensures proper environmental conditions in manufacturing and
storage facilities.
 IoT Projects: Commonly used in Internet of Things (IoT) applications for remote
environmental monitoring.

Advantages:

 Low Cost: Affordable sensor for basic environmental monitoring.


 Ease of Use: Simple interface and easy integration with microcontrollers.
 Compact Size: Small footprint makes it suitable for various applications.

Limitations:

 Accuracy: Limited accuracy compared to more advanced sensors.


 Range: Narrower measurement range for temperature and humidity.
 Sampling Rate: Slower sampling rate compared to other sensors.
GYRO SENSOR:

A gyroscope sensor (gyro sensor) measures the rate of rotation around an axis. It is
widely used in applications requiring precise motion sensing and control, such as in
smartphones, drones, gaming controllers, and robotics.

How Gyro Sensors Work:

Principle:

Gyro sensors use the Coriolis effect to measure rotational movement. When the sensor is
rotated, the Coriolis force causes a displacement in the vibrating structure within the sensor,
which is detected and converted into a measurable signal.

Types of Gyro Sensors:

 Mechanical Gyroscopes: Traditional gyroscopes with spinning rotors.


 MEMS Gyroscopes: Micro-Electro-Mechanical Systems (MEMS) gyroscopes are
compact, electronic gyroscopes widely used in modern devices.
 Optical Gyroscopes: Use light (usually lasers) to measure rotation based on the
interference of light paths (e.g., fiber optic gyroscopes).

Components:

 Sensing Element: Detects the rotational movement.


 Signal Conditioning: Amplifies, filters, and processes the signal.
 Output: Provides a readable signal (analog or digital).

Applications:

1. Smartphones and Tablets:

Function: Detects orientation and motion for screen rotation, gaming, and augmented reality
applications.
Benefit: Enhances user experience with intuitive motion controls.

2. Drones and UAVs:

Function: Stabilizes flight and controls orientation.

Benefit: Ensures smooth and controlled flight for various aerial maneuvers.

3. Gaming Controllers:

Function: Detects motion and orientation for interactive gaming.

Benefit: Provides a more immersive gaming experience.

4. Automotive Systems:

Function: Monitors vehicle dynamics for stability control and navigation.

Benefit: Enhances vehicle safety and performance.

5. Robotics:

Function: Controls robot movement and orientation.

Benefit: Improves precision and efficiency in robotic operations.

6. Wearable Devices:

Function: Tracks movement and orientation for fitness and health monitoring.

Benefit: Provides accurate motion tracking for health and fitness applications.

Advantages:

 Precision: Provides accurate measurement of rotational movement.


 Compact Size: MEMS gyroscopes are small and can be integrated into various devices.
 Versatility: Suitable for a wide range of applications across different industries.

Limitations:

 Drift: Gyroscopes can experience drift over time, leading to inaccuracies.


 Sensitivity to Vibration: External vibrations can affect the sensor’s accuracy.
 Cost: High-precision gyroscopes can be expensive.
LCD:

An LCD (Liquid Crystal Display) 16x2 module is a type of electronic display used frequently
in various applications, including embedded systems, for displaying alphanumeric characters.
The "16x2" specifies that the display has 16 columns and 2 rows, which means it can show 32
characters at a time. These modules are popular because they are relatively easy to interface
with microcontrollers and other digital electronics.

Features of a 16x2 LCD:

 Character Display: Each character is displayed within a 5x8 or 5x10 pixel matrix.
 Controller IC: Typically, they use a Hitachi HD44780 or a compatible controller.
 Backlight: Many models come with a backlight for better visibility in low-light
conditions.
 Interface: They can be interfaced using either 4-bit or 8-bit parallel communication.
 Customization: Allows for the creation of custom characters.

Pin Configuration:

A typical 16x2 LCD module has 16 pins, with the following functions:
 VSS: Ground
 VDD: +5V Power Supply
 V0: Contrast Adjustment
 RS: Register Select (0 = Instruction Register; 1 = Data Register)
 RW: Read/Write (0 = Write; 1 = Read)
 E: Enable Signal
 7-14. D0-D7: Data Pins
 A: LED+ (Backlight Anode)
 K: LED- (Backlight Cathode)
 Interfacing with a Microcontroller (e.g., Arduino):
 Here's an example of how to connect and use a 16x2 LCD with an Arduino:

Wiring:

 VSS to GND
 VDD to 5V
 V0 to a 10k potentiometer (for contrast adjustment)
 RS to Arduino Pin 12
 RW to GND
 E to Arduino Pin 11
 D4-D7 to Arduino Pins 5, 4, 3, 2 respectively
 A to 5V (with a current-limiting resistor)
 K to GND

Applications:

 Embedded Systems: Displaying sensor data, status messages, etc.


 DIY Projects: Clocks, counters, or any project needing a simple display.
 Industrial Control: Displaying process parameters and states.
CODES:

IRSENSOR:

const int irSensorPin = 7; // IR sensor connected to digital pin 7

const int ledPin = 13; // Built-in LED pin (you can connect an external LED to another pin
if you prefer)

void setup() {

pinMode(irSensorPin, INPUT); // Set the IR sensor pin as input

pinMode(ledPin, OUTPUT); // Set the LED pin as output

Serial.begin(9600); // Start serial communication at 9600 bps

void loop() {

int sensorValue = digitalRead(irSensorPin); // Read the value from the IR sensor

if (sensorValue == LOW) { // When the sensor detects an object (most IR sensors output LOW
when an object is detected)

digitalWrite(ledPin, HIGH); // Turn on the LED

Serial.println("Object detected!"); // Print message to serial monitor

} else {

digitalWrite(ledPin, LOW); // Turn off the LED

delay(100); // Small delay to debounce the sensor

}
FLAME SENSOR:

const int flameSensorPin = 7; // Flame sensor connected to digital pin 7

const int buzzerPin = 8; // Buzzer connected to digital pin 8

const int ledPin = 13; // Built-in LED pin (you can connect an external LED to another pin
if you prefer)

void setup() {

pinMode(flameSensorPin, INPUT); // Set the flame sensor pin as input

pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as output

pinMode(ledPin, OUTPUT); // Set the LED pin as output

Serial.begin(9600); // Start serial communication at 9600 bps

void loop() {

int sensorValue = digitalRead(flameSensorPin); // Read the value from the flame sensor

if (sensorValue == LOW) { // When the sensor detects a flame (most flame sensors output
LOW when a flame is detected)

digitalWrite(buzzerPin, HIGH); // Turn on the buzzer

digitalWrite(ledPin, HIGH); // Turn on the LED

Serial.println("Flame detected!"); // Print message to serial monitor

} else {

digitalWrite(buzzerPin, LOW); // Turn off the buzzer

digitalWrite(ledPin, LOW); // Turn off the LED

delay(100); // Small delay to debounce the sensor

}
MOISTURE SENSOR:

const int moistureSensorPin = A0; // Moisture sensor connected to analog pin A0

const int ledPin = 13; // Built-in LED pin (you can connect an external LED to another
pin if you prefer)

void setup() {

pinMode(ledPin, OUTPUT); // Set the LED pin as output

Serial.begin(9600); // Start serial communication at 9600 bps

void loop() {

int sensorValue = analogRead(moistureSensorPin); // Read the value from the moisture sensor

Serial.print("Moisture Sensor Value: ");

Serial.println(sensorValue); // Print the sensor value to the serial monitor

// Assume a threshold value of 300 for dry soil, adjust according to your sensor

if (sensorValue < 300) {

digitalWrite(ledPin, HIGH); // Turn on the LED if the soil is dry

Serial.println("Soil is dry!");

} else {

digitalWrite(ledPin, LOW); // Turn off the LED if the soil is moist

Serial.println("Soil is moist.");

delay(1000); // Wait for 1 second before taking another reading

}
RAIN SENSOR :

const int rainSensorPin = 7; // Rain sensor connected to digital pin 7

const int ledPin = 13; // Built-in LED pin (you can connect an external LED to another pin
if you prefer)

void setup() {

pinMode(rainSensorPin, INPUT); // Set the rain sensor pin as input

pinMode(ledPin, OUTPUT); // Set the LED pin as output

Serial.begin(9600); // Start serial communication at 9600 bps

void loop() {

int sensorValue = digitalRead(rainSensorPin); // Read the value from the rain sensor

if (sensorValue == LOW) { // When the sensor detects rain (most rain sensors output LOW
when rain is detected)

digitalWrite(ledPin, HIGH); // Turn on the LED

Serial.println("Rain detected!"); // Print message to serial monitor

} else {

digitalWrite(ledPin, LOW); // Turn off the LED

delay(100); // Small delay to debounce the sensor

}
GAS SENSOR :

const int gasSensorPin = 7; // Gas sensor connected to digital pin 7

const int ledPin = 13; // Built-in LED pin (you can connect an external LED to another pin
if you prefer)

void setup() {

pinMode(gasSensorPin, INPUT); // Set the gas sensor pin as input

pinMode(ledPin, OUTPUT); // Set the LED pin as output

Serial.begin(9600); // Start serial communication at 9600 bps

void loop() {

int sensorValue = digitalRead(gasSensorPin); // Read the value from the gas sensor

if (sensorValue == LOW) { // When the sensor detects gas (most gas sensors output LOW
when gas is detected)

digitalWrite(ledPin, HIGH); // Turn on the LED

Serial.println("Gas detected!"); // Print message to serial monitor

} else {

digitalWrite(ledPin, LOW); // Turn off the LED

delay(100); // Small delay to debounce the sensor

}
ULTRASONIC SENSOR

// Define the pin for the IR sensor

const int irSensorPin = 2; // IR sensor output pin

const int ledPin = 13; // LED pin (optional)

// Variable to store the sensor value

int sensorValue = 0;

void setup() {

// Initialize the serial communication

Serial.begin(9600);

// Set the IR sensor pin as an input

pinMode(irSensorPin, INPUT);

// Set the LED pin as an output

pinMode(ledPin, OUTPUT);

void loop() {

// Read the value from the IR sensor

sensorValue = digitalRead(irSensorPin);
// Print the sensor value to the serial monitor

Serial.println(sensorValue);

// If the sensor detects an object, turn on the LED

if (sensorValue == HIGH) {

digitalWrite(ledPin, HIGH); // Turn on the LED

} else {

digitalWrite(ledPin, LOW); // Turn off the LED

// Small delay to avoid too many prints

delay(100);

}
VOLTAGE SENSOR;

#define VOLTAGE_SENSOR_PIN A0

#define REFERENCE_VOLTAGE 5.0

#define VOLTAGE_DIVIDER_RATIO 5.0 // Change this based on your voltage divider

void setup() {

Serial.begin(9600);

void loop() {

// Read the value from the voltage sensor

int sensorValue = analogRead(VOLTAGE_SENSOR_PIN);

// Convert the analog reading (0 - 1023) to a voltage (0 - 5V)

float voltage = sensorValue * (REFERENCE_VOLTAGE / 1023.0);

// Adjust the voltage based on the voltage divider ratio

float actualVoltage = voltage * VOLTAGE_DIVIDER_RATIO;

// Print the voltage to the Serial Monitor

Serial.print("Voltage: ");

Serial.print(actualVoltage);

Serial.println(" V");

delay(1000); // Wait for a second before measuring again

}
DHT11 SENSOR

#include "DHT.h"

#define DHTPIN 2 // Pin which is connected to the DHT sensor

#define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE);

void setup() {

Serial.begin(9600);

dht.begin();

void loop() {

// Wait a few seconds between measurements.

delay(2000);

// Reading temperature or humidity takes about 250 milliseconds!

float humidity = dht.readHumidity();

// Read temperature as Celsius (the default)

float temperature = dht.readTemperature();

// Read temperature as Fahrenheit (isFahrenheit = true)

float temperatureF = dht.readTemperature(true);


// Check if any reads failed and exit early (to try again).

if (isnan(humidity) || isnan(temperature) || isnan(temperatureF)) {

Serial.println("Failed to read from DHT sensor!");

return;

// Compute heat index in Fahrenheit (the default)

float heatIndex = dht.computeHeatIndex(temperatureF, humidity);

// Compute heat index in Celsius (isFahrenheit = false)

float heatIndexC = dht.computeHeatIndex(temperature, humidity, false);

Serial.print("Humidity: ");

Serial.print(humidity);

Serial.print(" %\t");

Serial.print("Temperature: ");

Serial.print(temperature);

Serial.print(" °C ");

Serial.print(temperatureF);

Serial.print(" °F\t");

Serial.print("Heat index: ");

Serial.print(heatIndex);

Serial.print(" °F ");

Serial.print(heatIndexC);

Serial.println(" °C");
}

GYRO SENSOR

#include <Wire.h>

#include <MPU6050.h>

MPU6050 mpu;

void setup() {

Serial.begin(9600);

// Initialize MPU-6050

Serial.println("Initializing MPU-6050...");

mpu.initialize();

// Check if the connection is successful

if (mpu.testConnection()) {

Serial.println("MPU-6050 connection successful");

} else {

Serial.println("MPU-6050 connection failed");

void loop() {

// Variables to hold raw data


int16_t ax, ay, az;

int16_t gx, gy, gz;

// Read accelerometer and gyroscope data

mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// Print accelerometer data

Serial.print("aX = "); Serial.print(ax);

Serial.print(" | aY = "); Serial.print(ay);

Serial.print(" | aZ = "); Serial.println(az);

// Print gyroscope data

Serial.print("gX = "); Serial.print(gx);

Serial.print(" | gY = "); Serial.print(gy);

Serial.print(" | gZ = "); Serial.println(gz);

// Wait a bit before reading again

delay(500);

}
LCD

#include <LiquidCrystal.h>

// Initialize the library with the numbers of the interface pins

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {

// Set up the LCD's number of columns and rows

lcd.begin(16, 2);

// Print a message to the LCD

lcd.print("Hello, World!");

void loop() {

// Set the cursor to column 0, line 1

// Line 1 is the second row, since counting begins with 0

lcd.setCursor(0, 1);

// Print the number of seconds since reset

lcd.print(millis() / 1000);

You might also like