0% found this document useful (0 votes)
11 views41 pages

Configure Arduino & Raspberry Pi for Sensors

The document outlines practical exercises for configuring Arduino UNO and Raspberry Pi boards for sensor interfacing, controlling LEDs with switches, and displaying messages on an LCD using I2C. It details the hardware connections, software configurations, and example code for each practical, emphasizing the importance of digital and analog inputs/outputs. The document also introduces the control of a DC motor using an L298N motor driver, highlighting the need for safe current management and speed control techniques.

Uploaded by

yadavishita0306
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views41 pages

Configure Arduino & Raspberry Pi for Sensors

The document outlines practical exercises for configuring Arduino UNO and Raspberry Pi boards for sensor interfacing, controlling LEDs with switches, and displaying messages on an LCD using I2C. It details the hardware connections, software configurations, and example code for each practical, emphasizing the importance of digital and analog inputs/outputs. The document also introduces the control of a DC motor using an L298N motor driver, highlighting the need for safe current management and speed control techniques.

Uploaded by

yadavishita0306
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🔌 Practical 2: To Configure the Boards for Interfacing

with Sensors
Aim
To configure the Arduino UNO and Raspberry Pi boards by preparing their hardware and
software environments, and writing a basic initialization program to enable the Digital
Input/Output (I/O) and Analog Input pins for subsequent sensor interfacing.

Theory
Interfacing a sensor requires two main steps:
1.​ Hardware Connection: Connecting the sensor's output (voltage) to the board's
appropriate pin (Digital or Analog).
2.​ Software Configuration: Writing code that initializes the pin, sets its mode (INPUT or
OUTPUT), and reads the incoming data.
<!-- end list -->
●​ Digital I/O: Pins that can only be \text{HIGH} (e.g., 5V or 3.3V) or \text{LOW} (0V). Used
for simple ON/OFF switches, buttons, and sensors that output binary data.
●​ Analog Input: Pins found primarily on Arduino (and often accessed via an external ADC
on Raspberry Pi) that measure a continuous range of voltages and convert it into a
discrete digital value (e.g., 0-1023 for a 10-bit ADC). This is essential for sensors like
temperature, light, and humidity that have variable output.
Board Digital I/O (GPIO) Analog Input Typical Voltage Level
Arduino UNO \text{Pins } 0-13 \text{Pins A0-A5} 5\text{V}
(Onboard 10-bit ADC)
Raspberry Pi \text{All GPIO pins} None (Requires 3.3\text{V}
External ADC)
Code & Configuration
1. Arduino UNO Configuration (Using C++)

This code sets up a Digital Pin (2) as an INPUT to read a switch and an Analog Pin (A0) to
read a variable voltage sensor.
// Arduino C++ Code​
const int digitalPin = 2; // Pin for digital sensor (e.g., switch)​
const int analogPin = A0; // Pin for analog sensor (e.g., LDR)​

void setup() {​
// 1. Initialize Serial Communication for debugging​
[Link](9600);​

// 2. Configure Digital Pin as an INPUT​
pinMode(digitalPin, INPUT);​

// NOTE: Analog pin configuration is automatic in Arduino​
// when using analogRead(), so no explicit pinMode() is needed.​
[Link]("Arduino configured for sensor interfacing.");​
}​

void loop() {​
// Read Digital Sensor (will be HIGH or LOW)​
int digitalState = digitalRead(digitalPin);​

// Read Analog Sensor (will be 0 to 1023)​
int analogValue = analogRead(analogPin);​

// Print values for verification​
[Link]("Digital State: ");​
[Link](digitalState);​
[Link](" | Analog Value: ");​
[Link](analogValue);​

delay(500); // Wait half a second​
}​

2. Raspberry Pi Configuration (Using Python)

This code uses the \text{[Link]} library to configure a GPIO pin (17) as a Digital Input.
Note: As the RPi has no internal Analog-to-Digital Converter (ADC), you must use an external
component (like the \text{MCP3008}) for analog input. This code focuses on the mandatory
digital configuration.
# Raspberry Pi Python Code​
import [Link] as GPIO​
import time​

digital_pin = 17 # Use BCM numbering for GPIO 17​

# 1. Set the GPIO mode​
[Link]([Link]) ​

# 2. Configure the Digital Pin as an INPUT​
[Link](digital_pin, [Link]) ​

print("Raspberry Pi configured for sensor interfacing.")​

try:​
while True:​
# Read Digital Sensor (will be 0 or 1)​
digital_state = [Link](digital_pin)​

# Print value for verification​
print(f"Digital State (GPIO 17): {digital_state}")​

[Link](0.5)​

except KeyboardInterrupt:​
# 3. Clean up the GPIO settings on exit​
[Link]()​
print("GPIO cleanup complete.")​

Conclusion
The practical successfully configured both the Arduino UNO and Raspberry Pi platforms for
sensor interfacing. The Arduino was initialized to use both Digital Input and its built-in Analog
Input (A0), demonstrating its direct capability for variable sensor reading. The Raspberry Pi
was configured for Digital Input using the \text{[Link]} library in Python, highlighting its
reliance on digital signals and the need for external hardware for analog measurements. These
configurations lay the groundwork for connecting and processing data from any subsequent
sensor in the practical list.
💡 Practical 3: Interface, Control & Program LED
Using Switch
Aim
To interface a tactile switch (input) and a Light Emitting Diode (LED) (output) with an
Arduino UNO board and program the board such that the LED toggles its state (ON or OFF)
every time the switch is pressed.

Theory
This practical utilizes basic Digital Input and Digital Output.
1.​ LED (Output): An LED is a diode that requires current limiting. We connect it to a digital
pin (output) through a current-limiting resistor (typically 220\text{ }\Omega or 330\text{
}\Omega) to prevent it from burning out. Setting the digital pin to \text{HIGH} turns the
LED ON, and \text{LOW} turns it OFF.
2.​ Switch (Input): A tactile switch acts as a momentary button. To read its state, we use a
digital input pin. To ensure the pin reads a stable \text{LOW} when the switch is not
pressed, we use a pull-down resistor (e.g., 10\text{ k}\Omega) connected to ground.
When the switch is pressed, the pin is connected to 5\text{V} and reads \text{HIGH}.
3.​ State Toggling Logic: The program uses a state variable to track the current ON/OFF
status of the LED. It also employs edge detection logic (checking for a transition from
\text{LOW} to \text{HIGH} on the switch) to ensure the LED state changes only once per
press, not multiple times while the button is held down.

Components Required
●​ Arduino UNO Board
●​ LED
●​ Tactile Switch (Push button)
●​ 220\text{ }\Omega Resistor (for LED)
●​ 10\text{ k}\Omega Resistor (for switch pull-down)
●​ Breadboard and connecting wires

Circuit Diagram (Conceptual)


●​ LED Connection: Connect the long leg (Anode) of the LED to Digital Pin 13 (via the
220\text{ }\Omega resistor). Connect the short leg (Cathode) to GND.
●​ Switch Connection: Connect one end of the switch to 5\text{V}. Connect the other end of
the switch to Digital Pin 2. Also, connect a 10\text{ k}\Omega pull-down resistor from this
second end (Pin 2) to GND.
\

Code (Arduino C++)


// Define the pins used​
const int LED_PIN = 13; // Digital pin for the LED​
const int SWITCH_PIN = 2; // Digital pin for the switch​

// Variables for state management​
int LED_State = LOW; // Tracks the current state of the
LED (LOW/HIGH)​
int lastSwitchState = LOW; // Tracks the previous state of the
switch pin​

void setup() {​
// Initialize the LED_PIN as an output​
pinMode(LED_PIN, OUTPUT);​
// Initialize the SWITCH_PIN as an input (using internal PULLUP is
also possible)​
// We'll use the external pull-down resistor here for clarity.​
pinMode(SWITCH_PIN, INPUT);​

[Link](9600);​
[Link]("LED Switch Toggler Initialized.");​
}​

void loop() {​
// Read the current state of the switch​
int currentSwitchState = digitalRead(SWITCH_PIN);​

// Check if the button is pressed (HIGH) AND if it was LOW in the
last loop​
// This is the "edge detection" logic.​
if (currentSwitchState == HIGH && lastSwitchState == LOW) {​

// Switch the LED state​
if (LED_State == LOW) {​
LED_State = HIGH; // Change state to ON​
} else {​
LED_State = LOW; // Change state to OFF​
}​

// Update the physical LED state​
digitalWrite(LED_PIN, LED_State);​
[Link]("LED state changed to: ");​
[Link](LED_State == HIGH ? "ON" : "OFF");​

// Add a small delay for debouncing (prevents multiple triggers
from one press)​
delay(50);​
}​

// Save the current switch state for the next loop iteration​
lastSwitchState = currentSwitchState;​

// A small loop delay to keep the microcontroller running smoothly​
delay(1); ​
}​

Conclusion
The objective was successfully achieved. By configuring Digital Pin 2 as an input (with a
pull-down resistor) to read the switch and Digital Pin 13 as an output to control the LED, a
simple control system was created. The program uses edge detection logic (if
(currentSwitchState == HIGH && lastSwitchState == LOW)) to distinguish a new button press
from a held button, ensuring that the LED's state toggles exactly once with each press. This
demonstrates fundamental control flow and I/O management, which is essential for creating
interactive IoT devices.
🖥️ Practical 4: Interface, Control & Program LCD
Display Using a Switch
Aim
To interface a 16 \times 2 Liquid Crystal Display (LCD) with an I2C module and a tactile
switch to an Arduino UNO board. The program will display different messages on the LCD
based on whether the switch is pressed or released.

Theory
This practical combines Digital Input (from the switch) with Digital Output to a complex display
device (LCD).
1.​ I2C 16 \times 2 LCD: Standard parallel 16 \times 2 LCDs require many GPIO pins (at
least 6). The I2C (Inter-Integrated Circuit) module is an adapter that reduces the
required connections to just two data lines: SDA (Serial Data) and SCL (Serial Clock),
plus power (VCC) and ground (GND). This conserves valuable GPIO pins for other
sensors.
2.​ Arduino I2C Pins: On the Arduino UNO, the I2C lines are typically connected to Analog
Pin 4 (SDA) and Analog Pin 5 (SCL), though they may also be available on dedicated
pins near the \text{AREF} header.
3.​ Switch Input: The switch is configured as a Digital Input using a pull-down resistor (as
in Practical 3) to give a clean \text{LOW} (released) or \text{HIGH} (pressed) signal.
4.​ Logic: The program continuously checks the switch state. If \text{HIGH}, it displays one
message; if \text{LOW}, it displays a different message.

Components Required
●​ Arduino UNO Board
●​ 16 \times 2 LCD with I2C module (PCF8574)
●​ Tactile Switch (Push button)
●​ 10 \text{ k}\Omega Resistor (for switch pull-down)
●​ Breadboard and connecting wires

Circuit Diagram (Conceptual)


●​ LCD (I2C) Connection:
○​ I2C's \text{VCC} to Arduino 5\text{V}.
○​ I2C's \text{GND} to Arduino \text{GND}.
○​ I2C's \text{SDA} to Arduino \text{A4} (SDA).
○​ I2C's \text{SCL} to Arduino \text{A5} (SCL).
●​ Switch Connection:
○​ One end of the switch to Arduino 5\text{V}.
○​ The other end of the switch to Digital Pin 2.
○​ 10 \text{ k}\Omega pull-down resistor from Digital Pin 2 to \text{GND}.
\

Code (Arduino C++)


This code requires the LiquidCrystal_I2C library, which must be installed via the Arduino IDE
Library Manager.
#include <Wire.h> ​
#include <LiquidCrystal_I2C.h>​

// Set the LCD address (commonly 0x27 or 0x3F) and dimensions​
// If 0x27 doesn't work, try 0x3F.​
LiquidCrystal_I2C lcd(0x27, 16, 2); ​

const int SWITCH_PIN = 2; // Digital pin for the switch​

void setup() {​
// Initialize the LCD​
[Link](); ​
[Link]();​

// Set the switch pin as an input​
pinMode(SWITCH_PIN, INPUT);​

// Initial message display​
[Link](0, 0); // Column 0, Row 0​
[Link]("LCD Switch Control");​
[Link](0, 1); // Column 0, Row 1​
[Link]("Release to Start");​

[Link](9600);​
[Link]("LCD Switch Practical Initialized.");​
}​

void loop() {​
// Read the current state of the switch​
int switchState = digitalRead(SWITCH_PIN);​

// Check the switch state and display the corresponding message​
if (switchState == HIGH) {​
// Switch is pressed​
[Link]();​
[Link](1, 0); ​
[Link]("SWITCH PRESSED!");​
[Link](0, 1);​
[Link]("Processing Data...");​
} else {​
// Switch is released​
[Link]();​
[Link](3, 0); ​
[Link]("Switch is:");​
[Link](6, 1);​
[Link]("FREE");​
}​

delay(200); // Small delay to prevent display flicker and rapid
reading​
}​

Conclusion
The practical successfully demonstrated the interface of both an input device (switch) and an
output device (I2C LCD) with the Arduino UNO. By leveraging the I2C communication
protocol, pin utilization was minimized. The program successfully implemented decision logic
(if/else) based on the switch's digital input state, resulting in a dynamic change of the displayed
text on the LCD. This establishes a foundation for creating user interfaces where physical inputs
trigger information updates, a common requirement in many IoT monitoring devices.
Yes, here is the fifth practical on your list: Interfacing and controlling a DC Motor. This shifts
the focus from passive outputs (LEDs, LCDs) to controlling an actuator, which is crucial for

⚙️ Practical 5: Interface & Control a DC Motor


robotics and smart automation in IoT.

Aim
To interface a small DC motor with an Arduino UNO board using an L298N H-Bridge Motor
Driver and program the Arduino to control the motor's speed and direction.

Theory
Directly connecting a DC motor to an Arduino's GPIO pins will damage the board because
motors draw significantly more current than the pins can safely supply (typically 20-40\text{
mA}).
1.​ Motor Driver (L298N): This is an \text{H}-bridge circuit designed to handle the high
current required by motors, using a separate power supply. It acts as an interface and
power amplifier between the low-current digital signals of the Arduino and the
high-current requirements of the motor.
2.​ Direction Control: The L298N module typically uses two input pins (e.g., IN1 and IN2)
per motor. By setting one \text{HIGH} and the other \text{LOW}, the motor rotates in one
direction. Reversing the signals reverses the direction.
3.​ Speed Control (PWM): To control the motor's speed, we use Pulse Width Modulation
(PWM). PWM is a technique that rapidly switches the power ON and OFF. The duty cycle
(the percentage of time the power is ON) determines the effective voltage supplied to the
motor, thus controlling its speed. On the Arduino UNO, PWM is available on specific
digital pins (marked with a \sim, e.g., Pins 3, 5, 6, 9, 10, 11).

Components Required
●​ Arduino UNO Board
●​ L298N H-Bridge Motor Driver Module
●​ Small DC Motor (3\text{V} to 12\text{V})
●​ External Power Supply (e.g., 9\text{V} battery or power adapter) for the motor driver
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ L298N \text{GND} to Arduino \text{GND}.
○​ L298N +\text{VDC} terminal to the External Power Supply positive terminal.
●​ Motor Connection:
○​ DC Motor leads to the \text{OUT1} and \text{OUT2} screw terminals on the L298N.
●​ Control Signals (Arduino to L298N):
○​ \text{IN1} (Direction A) to Arduino Digital Pin 7.
○​ \text{IN2} (Direction B) to Arduino Digital Pin 8.
○​ \text{ENA} (Enable/Speed Control) to Arduino PWM Pin 9.
\

Code (Arduino C++)


// Define the pins used for control​
const int IN1 = 7; // Motor direction Pin A​
const int IN2 = 8; // Motor direction Pin B​
const int ENA = 9; // Motor speed (PWM) Pin​

// Define speed values (0 to 255)​
const int FULL_SPEED = 255;​
const int HALF_SPEED = 127;​
const int STOP_SPEED = 0;​

void setup() {​
// Set the control pins as outputs​
pinMode(IN1, OUTPUT);​
pinMode(IN2, OUTPUT);​
pinMode(ENA, OUTPUT); ​

[Link](9600);​
[Link]("DC Motor Control Initialized.");​
}​

void loop() {​
// --- PHASE 1: Forward at Half Speed ---​
[Link]("Forward at Half Speed...");​
setMotorDirection(HIGH, LOW);​
setMotorSpeed(HALF_SPEED);​
delay(3000); // Run for 3 seconds​

// --- PHASE 2: Stop ---​
[Link]("Stopping...");​
setMotorSpeed(STOP_SPEED);​
delay(2000); // Stop for 2 seconds​

// --- PHASE 3: Reverse at Full Speed ---​
[Link]("Reverse at Full Speed...");​
setMotorDirection(LOW, HIGH);​
setMotorSpeed(FULL_SPEED);​
delay(3000); // Run for 3 seconds​

// --- PHASE 4: Stop ---​
[Link]("Stopping...");​
setMotorSpeed(STOP_SPEED);​
delay(2000); // Stop for 2 seconds​
}​

// Function to set motor direction​
void setMotorDirection(int dirA, int dirB) {​
digitalWrite(IN1, dirA);​
digitalWrite(IN2, dirB);​
}​

// Function to set motor speed using PWM​
void setMotorSpeed(int speed) {​
// analogWrite() is used for PWM output on the Arduino​
analogWrite(ENA, speed); ​
}​

Conclusion
The practical successfully interfaced and controlled a DC motor using an L298N motor driver
to safely bridge the power gap between the Arduino and the high-current motor. By manipulating
the digital \text{IN1} and \text{IN2} pins, the motor's direction was controlled (forward and
reverse). More importantly, the use of the analogWrite() function on the dedicated PWM pin (Pin
9) allowed for the effective control of the motor's speed, demonstrating a fundamental principle
of actuator control in IoT and embedded systems.
Would you like me to proceed with the sixth practical: "Interface & program a stepper
motor," which involves a motor requiring more precise rotational control?
🧭 Practical 6: Interface & Program a Stepper Motor
Aim
To interface a unipolar/bipolar stepper motor with an Arduino UNO board using a suitable
motor driver (e.g., ULN2003 for unipolar, L298N for bipolar) and program the Arduino to
control the motor to rotate a specific number of steps in both clockwise (CW) and
counter-clockwise (CCW) directions.

Theory
A stepper motor is a brushless DC electric motor that divides a full rotation into a number of
equal steps. This allows for precise control of position and speed without any feedback
mechanism (open-loop control).
1.​ Stepping: The motor moves in discrete steps, typically 1.8^\circ per step (200 steps per
revolution) or 5.625^\circ per step (64 steps per revolution for a common 28\text{BYJ}-48
geared motor).
2.​ Motor Driver: Stepper motors have multiple coils that must be energized in a precise
sequence.
○​ Unipolar Stepper: Often uses a ULN2003 Darlington Array driver, which
simplifies the wiring and sequencing.
○​ Bipolar Stepper: Requires an \text{H}-bridge driver like the L298N (used in
Practical 5) or a specialized driver like the A4988 for current control.
3.​ Control: The Arduino controls the stepping sequence by sending digital signals to the
driver. The sequence defines the direction and amount of rotation. We typically use the
Arduino Stepper Library to handle the complex coil sequencing.

Components Required
●​ Arduino UNO Board
●​ 28\text{BYJ}-48 Stepper Motor (Unipolar, with gear reduction)
●​ ULN2003 Stepper Motor Driver Board
●​ External Power Supply (5\text{V} for the motor)
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ ULN2003 \text{GND} to Arduino \text{GND}.
○​ ULN2003 \text{VCC} to Arduino 5\text{V} (or external 5\text{V} supply).
●​ Motor Connection:
○​ The motor's 5-pin connector plugs directly into the \text{J1} socket on the ULN2003
board.
●​ Control Signals (Arduino to ULN2003):
○​ \text{IN1} to Arduino Digital Pin 8.
○​ \text{IN2} to Arduino Digital Pin 9.
○​ \text{IN3} to Arduino Digital Pin 10.
○​ \text{IN4} to Arduino Digital Pin 11.
\

Code (Arduino C++)


This code uses the built-in Stepper library for simplicity and control accuracy. For the common
28\text{BYJ}-48 with its standard gear ratio, it takes \text{2048} steps for a full 360^\circ rotation.
#include <Stepper.h>​

// Define the number of steps per revolution for the motor.​
// (2048 for the common 28BYJ-48 motor)​
const int stepsPerRevolution = 2048; ​

// Initialize the Stepper library:​
// Stepper(steps, pin1, pin2, pin3, pin4)​
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);​

void setup() {​
[Link](9600);​
[Link]("Stepper Motor Control Initialized.");​

// Set the motor speed in RPM (Revolutions Per Minute)​
[Link](15); // A low speed is typically safer for these
motors​
}​

void loop() {​
// --- PHASE 1: Rotate Clockwise (CW) 1/4 Revolution ---​
int stepsCW = stepsPerRevolution / 4; // 512 steps​
[Link]("Moving CW by ");​
[Link](stepsCW);​
[Link](" steps (90 degrees)...");​

[Link](stepsCW); // Positive value moves CW​
delay(2000); // Wait 2 seconds​

// --- PHASE 2: Rotate Counter-Clockwise (CCW) 1/2 Revolution ---​
int stepsCCW = stepsPerRevolution / 2; // 1024 steps​
[Link]("Moving CCW by ");​
[Link](stepsCCW);​
[Link](" steps (180 degrees)...");​

[Link](-stepsCCW); // Negative value moves CCW​
delay(2000); // Wait 2 seconds​
}​
Conclusion
The practical successfully interfaced and controlled a stepper motor, achieving precise angular
movement. By using the ULN2003 driver and the Arduino Stepper Library, the complex task
of sequencing the motor coils was simplified. The program demonstrated the core advantage of
a stepper motor: the ability to control movement not just by duration (like a DC motor), but by a
specific, quantifiable number of steps, allowing for repeatable and accurate positioning control
necessary for precision applications in IoT automation.
📐 Practical 7: Interface & Program Servo Motor
Aim
To interface a Standard Servo Motor (e.g., SG90) with an Arduino UNO board and program it
to rotate to specific angular positions (0^\circ, 90^\circ, and 180^\circ) and then sweep
continuously within a defined range.

Theory
A Servo Motor is an actuator that provides rotational position control within a limited range,
typically 0^\circ to 180^\circ. Unlike DC motors, which spin continuously, and Stepper motors,
which require constant stepping, a Servo motor maintains a specific angle when commanded,
making it ideal for positioning tasks.
1.​ Three Wires: Servo motors typically have three wires:
○​ \text{GND} (Black/Brown)
○​ \text{VCC} (Red, usually 5\text{V})
○​ Signal (Orange/Yellow/White)
2.​ Control Signal (PWM): The Servo is controlled by a specific type of Pulse Width
Modulation (PWM) signal sent to the signal wire. The pulse width (the length of the
\text{HIGH} signal) determines the commanded angular position:
○​ A narrow pulse (e.g., 500\text{ }\mu\text{s} or 1\text{ ms}) commands the 0^\circ
position.
○​ A wide pulse (e.g., 2500\text{ }\mu\text{s} or 2\text{ ms}) commands the 180^\circ
position.
○​ A mid-range pulse (e.g., 1500\text{ }\mu\text{s} or 1.5\text{ ms}) commands the
90^\circ position.
3.​ Arduino \text{Servo} Library: The Arduino \text{Servo} library is essential as it
simplifies this complex timing process. Instead of manually calculating pulse widths, you
simply use the \text{[Link]}(\text{angle}) function, where angle is a value from 0 to
180.

Components Required
●​ Arduino UNO Board
●​ SG90 or similar Standard Servo Motor
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ Servo \text{GND} (Brown/Black) to Arduino \text{GND}.
○​ Servo \text{VCC} (Red) to Arduino 5\text{V} (For small servos like \text{SG90},
5\text{V} from the Arduino is usually sufficient. Larger servos require a separate
power supply).
●​ Control Signal:
○​ Servo \text{Signal} (Orange/Yellow) to Arduino Digital Pin 9 (or any digital pin).
\

Code (Arduino C++)


This code uses the \text{Servo} library to command the motor to specific positions and then
execute a sweep pattern.
#include <Servo.h>​

// Create a Servo object​
Servo myServo; ​

const int SERVO_PIN = 9; // Digital pin for the servo signal​

void setup() {​
[Link](9600);​
[Link]("Servo Motor Control Initialized.");​

// Attaches the servo object to the pin​
[Link](SERVO_PIN); ​
}​

void loop() {​
// --- PHASE 1: Command Specific Positions ---​

// Go to 0 degrees​
[Link](0);​
[Link]("Position: 0 degrees");​
delay(1000); ​

// Go to 90 degrees​
[Link](90);​
[Link]("Position: 90 degrees");​
delay(1000); ​

// Go to 180 degrees​
[Link](180);​
[Link]("Position: 180 degrees");​
delay(1000); ​

// --- PHASE 2: Continuous Sweep from 0 to 180 ---​
[Link]("Starting continuous sweep...");​
int pos = 0;​

// Sweep from 0 to 180 degrees​
for (pos = 0; pos <= 180; pos += 1) { ​
[Link](pos); // Move to the current position​
delay(15); // Delay for speed control​
}​

// Sweep from 180 to 0 degrees​
for (pos = 180; pos >= 0; pos -= 1) { ​
[Link](pos); // Move to the current position​
delay(15); ​
}​
}​

Conclusion
The practical successfully interfaced and controlled the Servo motor using the Arduino's
\text{Servo} library. The use of \text{[Link]}(\text{angle}) simplified the underlying PWM
signal generation, allowing for direct control over the motor's angular position. The code
demonstrated both discrete positioning (moving to 0^\circ, 90^\circ, and 180^\circ) and
continuous, controlled motion (the sweep pattern). This highlights the Servo motor's
capability for precise, limited-range actuation, making it a critical component for IoT applications
requiring specific physical movements or alignments.
🔆 Practical 8: Interface & Program Light Sensor
(LDR) with IoT Board (Arduino)
Aim
To interface a Light Dependent Resistor (LDR) with an Arduino UNO board and program it to
read the ambient light intensity and print the corresponding analog value and a scaled,
human-readable measurement to the Serial Monitor.

Theory
An LDR (Photoresistor) is a passive sensor whose resistance changes based on the intensity
of light falling on its surface.
1.​ Operation: In bright light, the resistance is low (a few hundred ohms). In darkness, the
resistance is very high (several megaohms).
2.​ Voltage Divider: Since the Arduino's analog pins measure voltage, not resistance, the
LDR must be part of a voltage divider circuit. This circuit consists of the LDR and a
fixed-value series resistor (e.g., 10 \text{ k}\Omega). The voltage at the midpoint
between the two resistors is fed to the Arduino's analog pin.
○​ As light increases, LDR resistance decreases, causing the voltage at the analog pin
to increase.
○​ As light decreases, LDR resistance increases, causing the voltage at the analog pin
to decrease.
3.​ Analog Read: The Arduino's built-in Analog-to-Digital Converter (ADC) converts the
analog voltage (0V to 5V) into a digital value ranging from 0 (darkest) to 1023
(brightest).

Components Required
●​ Arduino UNO Board
●​ Light Dependent Resistor (LDR)
●​ 10 \text{ k}\Omega Resistor (Fixed, for voltage divider)
●​ Breadboard and connecting wires

Circuit Diagram (Conceptual)


●​ Voltage Divider Setup:
○​ 5\text{V} pin to one side of the LDR.
○​ The other side of the LDR connects to the fixed 10 \text{ k}\Omega resistor.
○​ The fixed 10 \text{ k}\Omega resistor connects from the LDR to \text{GND}.
○​ The midpoint (junction between the LDR and the 10 \text{ k}\Omega resistor)
connects to Analog Pin A0.
\

Code (Arduino C++)


// Define the analog pin connected to the LDR voltage divider​
const int LDR_PIN = A0; ​

void setup() {​
// Initialize serial communication for outputting data​
[Link](9600);​
[Link]("LDR Sensor Interface Initialized.");​
}​

void loop() {​
// 1. Read the raw analog value (0 to 1023)​
int rawValue = analogRead(LDR_PIN);​

// 2. Scale the value to a percentage for easier interpretation​
// (0% = Dark, 100% = Bright)​
// The map function can be used: map(value, fromLow, fromHigh,
toLow, toHigh)​
// Since 0 is usually dim and 1023 is bright, we map 0-1023 to
0-100.​
int percentage = map(rawValue, 0, 1023, 0, 100); ​

// 3. Determine a simple human-readable status​
String lightStatus;​
if (percentage < 10) {​
lightStatus = "Very Dark";​
} else if (percentage < 40) {​
lightStatus = "Dim Light";​
} else if (percentage < 75) {​
lightStatus = "Moderate Light";​
} else {​
lightStatus = "Bright Light";​
}​

// 4. Print the results​
[Link]("Raw Reading: ");​
[Link](rawValue);​
[Link](" | Light %: ");​
[Link](percentage);​
[Link]("% | Status: ");​
[Link](lightStatus);​

delay(500); // Read the sensor every half second​
}​

Conclusion
The practical successfully interfaced the LDR with the Arduino by implementing a voltage
divider circuit to convert the LDR's resistance change into a measurable voltage. The
analogRead() function was used to capture this analog voltage and convert it into a digital value
(0 to 1023). The code demonstrated how to not only read raw sensor data but also process
and scale it into a more meaningful percentage and descriptive status, which is essential before
transmitting data in a real-world IoT application.
🌡️ Practical 9: Interface & Program Temperature
Sensor (LM35) with IoT Board (Arduino)
Aim
To interface the LM35 Precision Centigrade Temperature Sensor with an Arduino UNO
board and program it to read the analog voltage output, convert this reading into a temperature
in Degrees Celsius (\mathbf{^\circ C}), and display the result on the Serial Monitor.

Theory
The LM35 is a linear analog temperature sensor that provides an output voltage directly
proportional to the temperature in Celsius. It is commonly preferred over thermistors because it
does not require complex linearization or a voltage divider circuit.
1.​ Linearity: The LM35 outputs 10\text{ mV} for every 1^\circ \text{C} change.
○​ At 0^\circ \text{C}, the output is 0\text{V}.
○​ At 25^\circ \text{C} (Room Temperature), the output is 250\text{ mV} (0.25\text{V}).
2.​ Arduino ADC: The Arduino's 10-bit Analog-to-Digital Converter (ADC) reads voltages
from 0\text{V} to 5\text{V} and translates them into a digital value from 0 to 1023.
3.​ Conversion Formula: To get the temperature in ^\circ \text{C}, we must perform two
steps:
○​ Step 1: Convert ADC Reading to Voltage (mV): (Where 5000 is the 5\text{V}
reference expressed in \text{mV})
○​ Step 2: Convert Voltage to Temperature (\mathbf{^\circ C}): (Since the LM35
outputs 10\text{ mV} per ^\circ \text{C})

Components Required
●​ Arduino UNO Board
●​ LM35 Temperature Sensor
●​ Connecting wires

Circuit Diagram (Conceptual)


The LM35 has three pins:
1.​ Pin 1 (Left): Power (\text{VCC}), connected to Arduino 5\text{V}.
2.​ Pin 2 (Middle): Output (\text{Vout}), connected to Analog Pin A0.
3.​ Pin 3 (Right): Ground (\text{GND}), connected to Arduino \text{GND}.
\

Code (Arduino C++)


// Define the analog pin connected to the LM35 output​
const int LM35_PIN = A0; ​

void setup() {​
// Initialize serial communication for outputting data​
[Link](9600);​
[Link]("LM35 Temperature Sensor Initialized.");​
}​

void loop() {​
// 1. Read the raw analog value (0 to 1023)​
int rawADC = analogRead(LM35_PIN);​

// 2. Convert the raw ADC value to voltage in millivolts (mV)​
// ADC_Value / 1024 * 5000 mV (5V reference)​
float voltage_mV = (rawADC / 1024.0) * 5000.0;​

// 3. Convert the voltage (mV) to temperature in Celsius (°C)​
// Since LM35 output is 10mV per degree Celsius.​
float temperature_C = voltage_mV / 10.0;​

// 4. Optionally, convert Celsius to Fahrenheit​
float temperature_F = (temperature_C * 9.0 / 5.0) + 32.0;​

// 5. Print the results​
[Link]("Raw ADC: ");​
[Link](rawADC);​
[Link](" | Voltage: ");​
[Link](voltage_mV);​
[Link](" mV | Temp: ");​
[Link](temperature_C);​
[Link](" C / ");​
[Link](temperature_F);​
[Link](" F");​

delay(1000); // Read the sensor once every second​
}​

Conclusion
The practical successfully interfaced the LM35 temperature sensor and demonstrated the
conversion of its analog output into precise, human-readable temperature units. The core of the
exercise involved:
1.​ Using the LM35's linear voltage property (no complex voltage divider needed).
2.​ Accurately using the Arduino ADC resolution (1024 steps across 5000\text{ mV}) to
calculate the measured voltage.
3.​ Applying the factor of 10\text{ mV} per \mathbf{^\circ C} to derive the final temperature
reading.
This process is fundamental for any IoT application focused on environmental monitoring and
provides a reliable method for quantitative data acquisition.
🔥 Practical 10: Interface & Program Gas Sensor
(MQ-2) with IoT Board (Arduino)
Aim
To interface an MQ-2 Gas Sensor (sensitive to Methane, Butane, LPG, Smoke, etc.) with an
Arduino UNO board and program it to read both the sensor's analog gas concentration level
and provide a simple digital alert when a dangerous threshold is reached.

Theory
The MQ-2 Gas Sensor is a Metal Oxide Semiconductor (MOS) type sensor used for detecting
combustible gases and smoke.
1.​ Operation: The sensor has a sensing material whose resistance decreases when it
comes into contact with the target gases. This is due to a chemical reaction that releases
electrons.
2.​ Output: The MQ-2 module typically provides two outputs:
○​ Analog Output (A0): Provides a continuous voltage proportional to the gas
concentration (used for quantitative measurement).
○​ Digital Output (D0): Provides a \text{HIGH} or \text{LOW} signal when the gas
concentration crosses a pre-set threshold (adjustable via a potentiometer on the
module, used for quick alerts).
3.​ Arduino Interface: We will use both outputs:
○​ Analog Reading (A0): Connected to an Arduino Analog Pin to read the raw
concentration level (0-1023).
○​ Digital Reading (D0): Connected to an Arduino Digital Pin to trigger an immediate
action (like turning on an alarm LED).

Components Required
●​ Arduino UNO Board
●​ MQ-2 Gas Sensor Module (must have both \text{A0} and \text{D0} pins)
●​ LED (for digital alarm indicator)
●​ 220\text{ }\Omega Resistor (for LED)
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ MQ-2 \text{VCC} to Arduino 5\text{V}.
○​ MQ-2 \text{GND} to Arduino \text{GND}.
●​ Sensor Inputs:
○​ MQ-2 \text{A0} (Analog Out) to Arduino Analog Pin A0.
○​ MQ-2 \text{D0} (Digital Out) to Arduino Digital Pin 2.
●​ Alarm Output:
○​ LED \text{Anode} (Long leg) to Arduino Digital Pin 13 (via 220\text{ }\Omega
resistor).
○​ LED \text{Cathode} (Short leg) to Arduino \text{GND}.
\

Code (Arduino C++)


// Define the pins used​
const int GAS_ANALOG_PIN = A0; // Analog output of the sensor​
const int GAS_DIGITAL_PIN = 2; // Digital output of the sensor (D0)​
const int ALARM_LED_PIN = 13; // Built-in LED or external LED​

// Define a safe threshold (example value for alarm if D0 is not used)​
// Note: This is a raw ADC value and needs calibration in a real
scenario.​
const int CONC_THRESHOLD = 300; ​

void setup() {​
[Link](9600);​

// Set the pins modes​
pinMode(GAS_DIGITAL_PIN, INPUT);​
pinMode(ALARM_LED_PIN, OUTPUT);​

// Start with alarm off​
digitalWrite(ALARM_LED_PIN, LOW);​

[Link]("MQ-2 Gas Sensor Initialized. Monitoring...");​
}​

void loop() {​
// 1. Read the raw analog gas concentration (0-1023)​
int analogConcentration = analogRead(GAS_ANALOG_PIN);​

// 2. Read the digital alarm status from D0​
int digitalAlarmState = digitalRead(GAS_DIGITAL_PIN);​

// 3. Implement custom alarm logic based on the analog reading​
if (analogConcentration > CONC_THRESHOLD) {​
// If concentration is high, turn the LED on (High Alert)​
digitalWrite(ALARM_LED_PIN, HIGH);​
[Link]("!!! HIGH GAS ALERT (Analog) !!! -> ");​
} else {​
// Turn the LED off (Safe)​
digitalWrite(ALARM_LED_PIN, LOW);​
}​

// 4. Print all data​
[Link]("Raw Analog: ");​
[Link](analogConcentration);​

[Link](" | Digital D0 Status: ");​
// Note: D0 is usually LOW for alarm​
[Link](digitalAlarmState == LOW ? "ALARM" : "SAFE"); ​

[Link](""); // Newline​

delay(500); // Read the sensor twice per second​
}​

Conclusion
The practical successfully interfaced the MQ-2 gas sensor and demonstrated a dual-mode
monitoring system.
1.​ Quantitative Monitoring: The Analog output (\text{A0}) provided a raw concentration
level (0-1023), allowing for fine-grained monitoring and the implementation of a custom
alarm threshold in the code.
2.​ Binary Safety Alert: The Digital output (\text{D0}) provided a quick, binary
\text{ALARM}/\text{SAFE} status based on the module's pre-set sensitivity, which was
used to control an indicator LED.
This dual approach is valuable in IoT safety systems, providing both an immediate hardware
alert and the raw data necessary for logging and analysis.
🔥 Practical 11: Interface & Programming Fire Sensor
with IoT Board (Arduino)
Aim
To interface an Infrared Flame Sensor with an Arduino UNO board and program a simple
alarm system that provides a digital alert (e.g., turning on an LED and printing a message)
immediately upon detecting the specific infrared (IR) light signature of a flame.

Theory
The Infrared Flame Sensor is designed to detect the presence of fire.
1.​ Operation: Flames emit a specific wavelength of infrared light (typically around 760
\text{ nm} to 1100 \text{ nm}) that is distinct from normal ambient light. The sensor module
uses an IR phototransistor to detect this specific spectrum.
2.​ Output: Most flame sensor modules provide two outputs (similar to the MQ-2 gas
sensor):
○​ Digital Output (D0): This is the most crucial output for fire detection. It is set to
\text{LOW} (or \text{HIGH}, depending on the module) when the detected IR
intensity crosses a pre-set threshold (adjustable via a potentiometer on the
module). This is used for a quick, binary fire/no-fire alert.
○​ Analog Output (A0): Provides a voltage proportional to the IR intensity (used for
distance or intensity measurement, but often less critical than D0).
3.​ Alarm System: The practical focuses on reading the \text{D0} pin. When the state
changes (indicating fire), the Arduino triggers an actuator, such as an LED or buzzer, to
serve as the local alarm.

Components Required
●​ Arduino UNO Board
●​ Infrared Flame Sensor Module (with D0 and A0 pins)
●​ LED (for alarm indicator)
●​ Piezo Buzzer (optional, for a louder alarm)
●​ 220\text{ }\Omega Resistor (for LED)
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ Flame Sensor \text{VCC} to Arduino 5\text{V}.
○​ Flame Sensor \text{GND} to Arduino \text{GND}.
●​ Sensor Input:
○​ Flame Sensor \text{D0} (Digital Out) to Arduino Digital Pin 2.
●​ Alarm Output:
○​ LED \text{Anode} (Long leg) to Arduino Digital Pin 13 (via 220\text{ }\Omega
resistor).
○​ LED \text{Cathode} (Short leg) to Arduino \text{GND}.
\

Code (Arduino C++)


This code monitors the digital output pin and triggers an alarm LED when a flame is detected.
// Define the pins used​
const int FLAME_SENSOR_PIN = 2; // Digital pin connected to D0 of the
sensor​
const int ALARM_LED_PIN = 13; // Built-in LED or external alarm LED​

// Variable to hold the current status​
int flameStatus = HIGH; // Assume initial state is HIGH (no flame) for
many modules​

void setup() {​
[Link](9600);​

// Set the pin modes​
pinMode(FLAME_SENSOR_PIN, INPUT);​
pinMode(ALARM_LED_PIN, OUTPUT);​

// Ensure the LED is off initially​
digitalWrite(ALARM_LED_PIN, LOW);​

[Link]("IR Flame Sensor Initialized. Awaiting Fire
Signal...");​
// Note: Test by exposing sensor to a lighter/match and adjust
module POT.​
}​

void loop() {​
// 1. Read the digital status of the flame sensor (D0)​
flameStatus = digitalRead(FLAME_SENSOR_PIN);​

// 2. Check the status (Many modules output LOW when fire is
detected)​
if (flameStatus == LOW) {​
// FIRE DETECTED: Activate the alarm and notify​
digitalWrite(ALARM_LED_PIN, HIGH);​
[Link]("!!! FIRE DETECTED !!! - ALARM ON");​
} else {​
// No fire detected: Keep the alarm off​
digitalWrite(ALARM_LED_PIN, LOW);​
[Link]("Status: SAFE");​
}​

// To prevent rapid flooding of the serial monitor​
delay(500); ​
}​

Conclusion
The practical successfully interfaced the Infrared Flame Sensor and implemented a
rapid-response digital alarm system. By monitoring the sensor's Digital Output (\mathbf{D0}),
the Arduino was able to establish a binary state (fire or no fire). The code utilized simple
\text{digitalRead} and \text{digitalWrite} functions to trigger an immediate visual alarm (LED),
demonstrating a fundamental principle of safety-critical IoT systems: swift detection and
actuation based on digital inputs.
📏 Practical 12: Interface & Programming Ultrasonic
Sensor with IoT Board (Arduino)
Aim
To interface the HC-SR04 Ultrasonic Sensor with an Arduino UNO board and program it to
measure the distance to the nearest object in centimeters and output the measurement to the
Serial Monitor.

Theory
The HC-SR04 measures distance using the principle of sonar (Sound Navigation and Ranging).
1.​ Operation: The sensor has two transducers: a transmitter (Trigger pin) and a receiver
(Echo pin).
○​ The Arduino sends a short (\mathbf{10\text{ }\mu\text{s}}) \text{HIGH} pulse to the
Trigger pin.
○​ The sensor emits an 8\text{-cycle} burst of 40\text{ kHz} ultrasonic sound
waves.
○​ The sound wave travels, hits an object, and bounces back.
○​ The sensor's Echo pin goes \text{HIGH} when the sound is emitted and returns
\text{LOW} when the reflected wave is received.
2.​ Distance Calculation: The Arduino measures the duration of the \text{HIGH} pulse on
the Echo pin, which is the time elapsed between sound transmission and reception.
○​ Formula for Distance:
○​ Speed of Sound in Air: Approximately 343\text{ m/s} or 0.0343\text{
cm}/\mu\text{s}.
○​ Simplified Formula (in cm): Since the time is for a round trip (divided by 2) and
the Arduino measures time in \text{microseconds}, the final formula is: (Where 58 is
derived from 1,000,000 \text{ } \mu\text{s}/\text{second} / (343 \text{ m/s} \times 100
\text{ cm/m}) / 2 \approx 58.12)

Components Required
●​ Arduino UNO Board
●​ HC-SR04 Ultrasonic Sensor
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ HC-SR04 \text{VCC} to Arduino 5\text{V}.
○​ HC-SR04 \text{GND} to Arduino \text{GND}.
●​ Control Pins:
○​ HC-SR04 \text{Trig} (Trigger) to Arduino Digital Pin 9.
○​ HC-SR04 \text{Echo} (Echo) to Arduino Digital Pin 10.
\

Code (Arduino C++)


// Define the control pins​
const int trigPin = 9; ​
const int echoPin = 10; ​

// Variables for measurement​
long duration; // To store the time duration of the sound travel​
float distanceCm; // To store the final distance in centimeters​

void setup() {​
[Link](9600);​

// Set the pin modes​
pinMode(trigPin, OUTPUT); // Trig pin is output​
pinMode(echoPin, INPUT); // Echo pin is input​

[Link]("HC-SR04 Ultrasonic Sensor Initialized.
Measuring...");​
}​

void loop() {​
// 1. Clear the trigPin (ensure LOW for a clean start)​
digitalWrite(trigPin, LOW);​
delayMicroseconds(2);​

// 2. Set the trigPin HIGH for 10 microseconds (pulse to start sound
wave)​
digitalWrite(trigPin, HIGH);​
delayMicroseconds(10);​
digitalWrite(trigPin, LOW);​

// 3. Read the echoPin, returns the time (in microseconds) the sound
took to travel​
duration = pulseIn(echoPin, HIGH);​

// 4. Calculate the distance (cm) using the simplified formula:​
// Duration / 58 = Distance in cm​
distanceCm = duration / 58.0;​

// 5. Print the results​
[Link]("Distance: ");​
// Ensure the measurement is within the sensor's practical range
(e.g., 2cm to 400cm)​
if (distanceCm < 2 || distanceCm > 400) {​
[Link]("Out of Range");​
} else {​
[Link](distanceCm);​
[Link](" cm");​
}​

delay(500); // Wait half a second before the next measurement​
}​

Conclusion
The practical successfully interfaced the HC-SR04 Ultrasonic Sensor by correctly configuring
the Trigger pin as an output and the Echo pin as an input. The core functionality was achieved
by using the pulseIn() function to accurately measure the time-of-flight of the sound wave. By
applying the specific conversion factor (\mathbf{58}) to the measured duration, the distance to
the object was reliably calculated in centimeters. This demonstrates the use of time-based
measurement principles for proximity sensing, a key function in autonomous and monitoring IoT
systems.
🌱 Practical 13: Interfacing & Programming Moisture
Sensor with IoT Board (Arduino)
Aim
To interface an Analog Soil Moisture Sensor with an Arduino UNO board and program it to
measure the moisture content of the soil and output a processed, human-readable moisture
percentage to the Serial Monitor.

Theory
A Soil Moisture Sensor (capacitive or resistive) measures the water content of the soil. We will
focus on the resistive type for this practical, as it is the most common module with dual
analog/digital outputs.
1.​ Operation: The sensor probes act as electrodes. When placed in soil:
○​ Dry Soil: Has high electrical resistance.
○​ Wet Soil: Has low electrical resistance (due to water and dissolved salts).
2.​ Output & Voltage Divider: The sensor module converts this resistance change into a
voltage that is fed to the Arduino's analog pin.
○​ Dry Soil (High Resistance): Results in a low analog output voltage (ADC value
close to 1023 in some modules, or 0 in others, depending on the internal wiring).
For simplicity, we assume low voltage = wet and high voltage = dry for mapping
purposes, which is common.
3.​ Mapping: The raw 0-1023 ADC reading needs to be mapped to a meaningful range
(e.g., 0-100\%). Since the raw ADC reading is typically inversely proportional to the
moisture, the mapping often involves reversing the range.

Components Required
●​ Arduino UNO Board
●​ Analog Soil Moisture Sensor Module (e.g., \text{FC-28} or similar)
●​ Connecting wires
●​ Small cup of dry soil and water (for testing)

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ Sensor \text{VCC} to Arduino 5\text{V}.
○​ Sensor \text{GND} to Arduino \text{GND}.
●​ Sensor Input:
○​ Sensor \text{A0} (Analog Out) to Arduino Analog Pin A0.
\

Code (Arduino C++)


This code reads the analog value and re-maps it to an estimated moisture percentage,
assuming that a high ADC value (near 1023) means the sensor is detecting mostly air (dry) and
a low ADC value (near 0) means it's fully saturated (wet).
// Define the analog pin connected to the sensor​
const int MOISTURE_PIN = A0; ​

// Define calibration values (These must be tested for your specific
sensor/soil)​
// DRY_AIR_VALUE: The reading when sensor is completely dry (e.g.,
600-900)​
// WET_WATER_VALUE: The reading when sensor is submerged in water
(e.g., 200-400)​
const int DRY_AIR_VALUE = 650; ​
const int WET_WATER_VALUE = 350;​

void setup() {​
[Link](9600);​
[Link]("Soil Moisture Sensor Initialized. Insert into
soil.");​
}​

void loop() {​
// 1. Read the raw analog value (0 to 1023)​
int rawValue = analogRead(MOISTURE_PIN);​

// 2. Map the raw value to a percentage (0% to 100%)​
// Since high rawValue means DRY (0%) and low rawValue means WET
(100%), ​
// we map the range inversely: [WET_WATER_VALUE, DRY_AIR_VALUE] ->
[100, 0]​
int moisturePercentage = map(rawValue, WET_WATER_VALUE,
DRY_AIR_VALUE, 100, 0);​

// 3. Constrain the percentage to stay within 0% and 100%​
moisturePercentage = constrain(moisturePercentage, 0, 100);​

// 4. Determine a simple status​
String moistureStatus;​
if (moisturePercentage < 30) {​
moistureStatus = "Critical! Needs Water.";​
} else if (moisturePercentage < 70) {​
moistureStatus = "Adequate Moisture.";​
} else {​
moistureStatus = "Saturated.";​
}​

// 5. Print the results​
[Link]("Raw ADC: ");​
[Link](rawValue);​
[Link](" | Moisture %: ");​
[Link](moisturePercentage);​
[Link]("% | Status: ");​
[Link](moistureStatus);​

delay(1000); // Read the sensor once per second​
}​

Conclusion
The practical successfully demonstrated the interface of an analog soil moisture sensor. The
core challenge was overcome by calibrating the sensor by defining boundary values
(DRY_AIR_VALUE and WET_WATER_VALUE) and then using the \text{map()} function to
re-scale the inverse analog voltage reading into a positive, linear moisture percentage. This
allows the Arduino to provide meaningful, actionable data, forming the basis of an automated
irrigation system in an IoT environment.
🚶 Practical 14: Interfacing & Programming PIR
Sensor with IoT Board (Arduino)
Aim
To interface a Passive Infrared (PIR) Motion Sensor with an Arduino UNO board and
program it to act as a security trigger, activating a digital output (LED) and notifying the user
via the Serial Monitor whenever motion is detected.

Theory
The PIR Sensor is a reliable, low-power sensor designed to detect movement based on
changes in infrared radiation (heat) emitted by objects (like humans or animals) in its field of
view.
1.​ Operation: The sensor has a Fresnel lens that focuses IR energy onto a pyroelectric
sensor. When a warm body moves, the pattern of IR radiation changes rapidly, triggering
the sensor.
2.​ Output: The PIR sensor is a digital device. Its signal pin provides:
○​ \mathbf{\text{LOW}} (0V): No motion detected.
○​ \mathbf{\text{HIGH}} (3.3V/5V): Motion detected.
3.​ Adjustments: Most PIR modules have two potentiometers: one to adjust the sensitivity
(detection range) and one to adjust the delay time (how long the output stays \text{HIGH}
after motion stops).
4.​ Application: In IoT, PIR sensors are fundamental for smart lighting, security alarms, and
occupancy tracking.

Components Required
●​ Arduino UNO Board
●​ HC-SR501 or similar PIR Motion Sensor Module (with three pins: VCC, GND, OUT)
●​ LED (for alarm indicator)
●​ 220\text{ }\Omega Resistor (for LED)
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ PIR \text{VCC} to Arduino 5\text{V}.
○​ PIR \text{GND} to Arduino \text{GND}.
●​ Sensor Input:
○​ PIR \text{OUT} (Signal Pin) to Arduino Digital Pin 2.
●​ Alarm Output:
○​ LED \text{Anode} (Long leg) to Arduino Digital Pin 13 (via 220\text{ }\Omega
resistor).
○​ LED \text{Cathode} (Short leg) to Arduino \text{GND}.
\

Code (Arduino C++)


This code monitors the digital output pin of the PIR and uses edge detection to prevent
repetitive messages while the motion is continuous.
// Define the pins used​
const int PIR_INPUT_PIN = 2; // Digital pin connected to the PIR OUT
pin​
const int ALARM_LED_PIN = 13; // Alarm LED pin​

// Variables for state tracking​
int pirState = LOW; // Current state of the PIR pin​
int lastPirState = LOW; // Previous state of the PIR pin (for edge
detection)​

void setup() {​
[Link](9600);​

// Set the pin modes​
pinMode(PIR_INPUT_PIN, INPUT);​
pinMode(ALARM_LED_PIN, OUTPUT);​

// Ensure the LED is off initially​
digitalWrite(ALARM_LED_PIN, LOW);​

[Link]("PIR Sensor Initialized. Waiting for motion...");​
}​

void loop() {​
// 1. Read the current state of the PIR sensor​
pirState = digitalRead(PIR_INPUT_PIN);​

// 2. Check for the rising edge (transition from LOW to HIGH)​
if (pirState == HIGH && lastPirState == LOW) {​
// Motion just started!​
digitalWrite(ALARM_LED_PIN, HIGH);​
[Link](">>> MOTION DETECTED! <<<");​
[Link]("Security system engaged.");​

} ​
// 3. Check for the falling edge (transition from HIGH to LOW)​
else if (pirState == LOW && lastPirState == HIGH) {​
// Motion just stopped!​
digitalWrite(ALARM_LED_PIN, LOW);​
[Link]("Motion stopped.");​

}​

// 4. Update the last state for the next loop iteration​
lastPirState = pirState;​

delay(50); // Small delay for loop stability​
}​

Conclusion
The practical successfully interfaced the PIR sensor, utilizing its digital output for reliable
motion detection. By employing edge detection logic (lastPirState), the Arduino was able to
accurately distinguish between the start of motion, continuous motion, and the end of motion.
This allowed for clean, non-repetitive messages on the Serial Monitor and effective control of
the alarm LED, proving the PIR sensor's fundamental role in event-driven security and
automation aspects of IoT.
🚶 Practical 14: Interfacing & Programming PIR
Sensor with IoT Board (Arduino)
Aim
To interface a Passive Infrared (PIR) Motion Sensor with an Arduino UNO board and
program it to act as a security trigger, activating a digital output (LED) and notifying the user
via the Serial Monitor whenever motion is detected.

Theory
The PIR Sensor is a reliable, low-power sensor designed to detect movement based on
changes in infrared radiation (heat) emitted by objects (like humans or animals) in its field of
view.
1.​ Operation: The sensor has a Fresnel lens that focuses IR energy onto a pyroelectric
sensor. When a warm body moves, the pattern of IR radiation changes rapidly, triggering
the sensor.
2.​ Output: The PIR sensor is a digital device. Its signal pin provides:
○​ \mathbf{\text{LOW}} (0V): No motion detected.
○​ \mathbf{\text{HIGH}} (3.3V/5V): Motion detected.
3.​ Adjustments: Most PIR modules have two potentiometers: one to adjust the sensitivity
(detection range) and one to adjust the delay time (how long the output stays \text{HIGH}
after motion stops).
4.​ Application: In IoT, PIR sensors are fundamental for smart lighting, security alarms, and
occupancy tracking.

Components Required
●​ Arduino UNO Board
●​ HC-SR501 or similar PIR Motion Sensor Module (with three pins: VCC, GND, OUT)
●​ LED (for alarm indicator)
●​ 220\text{ }\Omega Resistor (for LED)
●​ Connecting wires

Circuit Diagram (Conceptual)


●​ Power & Ground:
○​ PIR \text{VCC} to Arduino 5\text{V}.
○​ PIR \text{GND} to Arduino \text{GND}.
●​ Sensor Input:
○​ PIR \text{OUT} (Signal Pin) to Arduino Digital Pin 2.
●​ Alarm Output:
○​ LED \text{Anode} (Long leg) to Arduino Digital Pin 13 (via 220\text{ }\Omega
resistor).
○​ LED \text{Cathode} (Short leg) to Arduino \text{GND}.
\

Code (Arduino C++)


This code monitors the digital output pin of the PIR and uses edge detection to prevent
repetitive messages while the motion is continuous.
// Define the pins used​
const int PIR_INPUT_PIN = 2; // Digital pin connected to the PIR OUT
pin​
const int ALARM_LED_PIN = 13; // Alarm LED pin​

// Variables for state tracking​
int pirState = LOW; // Current state of the PIR pin​
int lastPirState = LOW; // Previous state of the PIR pin (for edge
detection)​

void setup() {​
[Link](9600);​

// Set the pin modes​
pinMode(PIR_INPUT_PIN, INPUT);​
pinMode(ALARM_LED_PIN, OUTPUT);​

// Ensure the LED is off initially​
digitalWrite(ALARM_LED_PIN, LOW);​

[Link]("PIR Sensor Initialized. Waiting for motion...");​
}​

void loop() {​
// 1. Read the current state of the PIR sensor​
pirState = digitalRead(PIR_INPUT_PIN);​

// 2. Check for the rising edge (transition from LOW to HIGH)​
if (pirState == HIGH && lastPirState == LOW) {​
// Motion just started!​
digitalWrite(ALARM_LED_PIN, HIGH);​
[Link](">>> MOTION DETECTED! <<<");​
[Link]("Security system engaged.");​

} ​
// 3. Check for the falling edge (transition from HIGH to LOW)​
else if (pirState == LOW && lastPirState == HIGH) {​
// Motion just stopped!​
digitalWrite(ALARM_LED_PIN, LOW);​
[Link]("Motion stopped.");​

}​

// 4. Update the last state for the next loop iteration​
lastPirState = pirState;​

delay(50); // Small delay for loop stability​
}​

Conclusion
The practical successfully interfaced the PIR sensor, utilizing its digital output for reliable
motion detection. By employing edge detection logic (lastPirState), the Arduino was able to
accurately distinguish between the start of motion, continuous motion, and the end of motion.
This allowed for clean, non-repetitive messages on the Serial Monitor and effective control of
the alarm LED, proving the PIR sensor's fundamental role in event-driven security and
automation aspects of IoT.

You might also like