0% found this document useful (0 votes)
20 views55 pages

Arduino Guide for IT Projects

guide to a student of Bachelor in IT to use Arduino UNO in the final project

Uploaded by

Ontop Scenes
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)
20 views55 pages

Arduino Guide for IT Projects

guide to a student of Bachelor in IT to use Arduino UNO in the final project

Uploaded by

Ontop Scenes
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

Arduino Learning Guide for IT Final Year Project

Table of Contents
1. Introduction

2. Prerequisites & Your Advantages

3. Hardware Requirements

4. Software Setup

5. Learning Path (12-Week Plan)

6. Arduino Basics

7. Connecting Arduino to Databases

8. Networking with Arduino

9. Project Ideas for IT Students

10. Sample Project: IoT Environmental Monitor

11. Resources & References

Introduction
Arduino is an open-source electronics platform based on easy-to-use hardware and software. For IT students, it
bridges the gap between software development and physical computing, enabling you to create Internet of
Things (IoT) projects that combine sensors, databases, networking, and web technologies.

Why Arduino for IT Projects?


Integrates with databases (MySQL, MongoDB)

Supports networking protocols (HTTP, MQTT, TCP/IP)

Compatible with web technologies

Large community and extensive documentation

Real-world applications in IoT, automation, and monitoring systems

Prerequisites & Your Advantages


What You Already Know:
Basic Programming: Arduino uses C/C++ syntax, similar to Java or C
Networking: Understanding of client-server, HTTP, APIs will help with IoT projects

MySQL Database: Perfect for storing sensor data and creating analytics

What You'll Learn:


Microcontroller programming

Electronic circuits (basic)

Sensor interfacing

Real-time data collection

Embedded systems concepts

Hardware Requirements
Essential Starter Kit (~$40-60)

1. Arduino UNO R3 - Main microcontroller board

2. USB Cable (Type A to B) - For programming and power

3. Breadboard - For prototyping circuits without soldering

4. Jumper Wires - Male-to-male, male-to-female, female-to-female

5. LEDs (assorted colors) - For output indication

6. Resistors (220Ω, 1kΩ, 10kΩ) - For current limiting

7. Push Buttons - For input

8. Potentiometer - For analog input practice

Sensors for Your Project (Choose based on project idea)


DHT11/DHT22 - Temperature and humidity sensor ($3-5)

HC-SR04 - Ultrasonic distance sensor ($2-3)

PIR Sensor - Motion detection ($2-3)

MQ-Series - Gas sensors (MQ-2, MQ-135) ($3-5)

LDR - Light dependent resistor ($1)

RFID RC522 - RFID reader module ($5-8)

Soil Moisture Sensor - For agriculture projects ($2-3)

For Internet Connectivity


ESP8266 (NodeMCU) - WiFi-enabled board, Arduino-compatible ($5-8)
Alternative to UNO for projects requiring WiFi

ESP32 - WiFi + Bluetooth, more powerful ($8-12)

Ethernet Shield - For wired internet on Arduino UNO ($10-15)

Optional but Useful

LCD Display (16x2) - Display data locally

Relay Module - Control high-voltage devices

Buzzer - Audio alerts

SD Card Module - Local data logging

Where to Buy
Amazon, AliExpress, or local electronics stores

Arduino official store

SparkFun, Adafruit (educational resources included)

Software Setup
1. Arduino IDE
Download & Install:

Visit: [Link]

Available for Windows, Mac, Linux

Free and open-source

First Setup:

1. Install Arduino IDE


2. Connect Arduino UNO via USB
3. Tools → Board → Arduino UNO
4. Tools → Port → Select your Arduino port (COM3, COM4, etc.)
5. File → Examples → [Link] → Blink
6. Click Upload (→) button
7. LED on board should blink!

2. Arduino Web Editor (Cloud Alternative)

Online IDE: [Link]

No installation needed
Requires account creation

Good for trying out code quickly

3. Tinkercad Circuits (Simulator)


URL: [Link]

Free online Arduino simulator

Practice without physical hardware

Great for learning and testing circuits

4. Database Setup (MySQL)


Install XAMPP or WAMP:

Includes Apache, MySQL, PHP

Use phpMyAdmin for database management

Create databases to store sensor data

5. Additional Tools
Fritzing - Circuit diagram design (optional)

PuTTY or Serial Monitor - For debugging

Postman - Test API endpoints

VS Code - Alternative editor with Arduino extension

Learning Path (12-Week Plan)


Weeks 1-2: Arduino Fundamentals
Goals: Understand Arduino basics, digital I/O, analog input

Day 1-3: Getting Started

Set up Arduino IDE

Understand Arduino board components

Upload "Blink" sketch

Modify blink timing

Day 4-7: Digital I/O

Control multiple LEDs


Read button input

Use if-statements for control

Build a simple traffic light

Day 8-14: Analog Input

Read potentiometer values

Use Serial Monitor for debugging

Map() function for value conversion

Build LED brightness controller

Practice Projects:

1. Button-controlled LED

2. Traffic light sequence

3. Night light (LED + LDR)

4. Simple alarm system (buzzer + button)

Weeks 3-4: Sensors & Advanced Programming


Goals: Interface sensors, use libraries, data processing

Week 3: Temperature & Humidity

Install DHT library

Read DHT11/DHT22 sensor

Display data on Serial Monitor

Calculate average readings

Week 4: Distance & Motion

HC-SR04 ultrasonic sensor

PIR motion sensor

Implement triggers and alerts

Multi-sensor integration

Practice Projects:

1. Temperature monitoring system


2. Distance measuring device

3. Motion-activated LED

4. Multi-sensor dashboard (Serial Monitor)

Key Concepts:

cpp

// Library usage
#include <DHT.h>

// Sensor initialization
DHT dht(PIN, DHT11);

// Reading data
float temp = [Link]();
float humidity = [Link]();

// Data validation
if (isnan(temp) || isnan(humidity)) {
[Link]("Sensor read failed!");
}

Weeks 5-6: Internet Connectivity


Goals: Connect Arduino to internet, send/receive data

Week 5: ESP8266/ESP32 Setup

Install ESP board in Arduino IDE

Connect to WiFi network

Make HTTP requests

Understand IP addressing

Week 6: Web Communication

Send data to web server (POST requests)

Receive commands from web (GET requests)

Parse JSON data

Introduction to APIs

Practice Projects:
1. WiFi scanner

2. Send sensor data to ThingSpeak

3. Control LED via web browser

4. Weather station with API integration

Sample Code: WiFi Connection

cpp

#include <ESP8266WiFi.h>

const char* ssid = "YOUR_WIFI_SSID";


const char* password = "YOUR_PASSWORD";

void setup() {
[Link](115200);
[Link](ssid, password);

while ([Link]() != WL_CONNECTED) {


delay(500);
[Link](".");
}

[Link]("WiFi Connected!");
[Link]([Link]());
}

Weeks 7-8: Database Integration


Goals: Store Arduino data in MySQL, retrieve and display

Week 7: Server-Side Setup

Set up XAMPP/WAMP

Create MySQL database

Write PHP scripts for data insertion

Understand RESTful API basics

Week 8: Arduino to Database

Send HTTP POST from Arduino

Insert sensor data into MySQL


Error handling and reconnection

Data timestamping

Database Structure Example:

sql

CREATE DATABASE arduino_project;

USE arduino_project;

CREATE TABLE sensor_data (


id INT AUTO_INCREMENT PRIMARY KEY,
temperature FLOAT,
humidity FLOAT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

PHP Script (insert_data.php):

php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "arduino_project";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$temperature = $_POST['temperature'];
$humidity = $_POST['humidity'];

$sql = "INSERT INTO sensor_data (temperature, humidity)


VALUES ('$temperature', '$humidity')";

if ($conn->query($sql) === TRUE) {


echo "Data inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Arduino Code:

cpp
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* serverName = "[Link]

void sendData(float temp, float hum) {


if([Link]() == WL_CONNECTED) {
HTTPClient http;
WiFiClient client;

[Link](client, serverName);
[Link]("Content-Type", "application/x-www-form-urlencoded");

String httpRequestData = "temperature=" + String(temp) +


"&humidity=" + String(hum);

int httpResponseCode = [Link](httpRequestData);

if (httpResponseCode > 0) {
[Link]("Data sent successfully");
} else {
[Link]("Error sending data");
}

[Link]();
}
}

Weeks 9-10: Web Dashboard Development


Goals: Create web interface to visualize Arduino data

Week 9: Frontend Development

HTML/CSS for dashboard layout

JavaScript for dynamic updates

[Link] or Google Charts for visualization

Real-time data display using AJAX

Week 10: Backend & Integration

PHP scripts to fetch data from MySQL

JSON API creation


Implement data filtering (date range, sensor type)

User authentication (optional)

Sample Dashboard ([Link]):

html
<!DOCTYPE html>
<html>
<head>
<title>Arduino Dashboard</title>
<script src="[Link]
<style>
body { font-family: Arial; padding: 20px; }
.card {
background: #f4f4f4;
padding: 20px;
margin: 10px;
border-radius: 5px;
}
#tempChart { max-width: 800px; margin: 20px auto; }
</style>
</head>
<body>
<h1>Environmental Monitoring Dashboard</h1>

<div class="card">
<h2>Current Readings</h2>
<p>Temperature: <span id="currentTemp">--</span> °C</p>
<p>Humidity: <span id="currentHum">--</span> %</p>
<p>Last Update: <span id="lastUpdate">--</span></p>
</div>

<canvas id="tempChart"></canvas>

<script>
// Fetch latest data
function fetchData() {
fetch('get_data.php')
.then(response => [Link]())
.then(data => {
[Link]('currentTemp').textContent =
[Link];
[Link]('currentHum').textContent =
[Link];
[Link]('lastUpdate').textContent =
[Link];
} );
}

// Update every 5 seconds


setInterval(fetchData, 5000);
fetchData();
</script>
</body>
</html>

Weeks 11-12: Final Project Development


Goals: Build complete system, testing, documentation

Week 11: Implementation

Assemble complete hardware

Integrate all software components

Implement error handling

Test all features

Week 12: Polish & Documentation

Create circuit diagrams

Write user manual

Prepare presentation

Create demo video

Arduino Basics
Arduino Code Structure

cpp
// Variable declarations (global)
int ledPin = 13;

// Setup runs once at startup


void setup() {
pinMode(ledPin, OUTPUT); // Set pin as output
[Link](9600); // Start serial communication
}

// Loop runs repeatedly


void loop() {
digitalWrite(ledPin, HIGH); // Turn LED on
delay(1000); // Wait 1 second
digitalWrite(ledPin, LOW); // Turn LED off
delay(1000); // Wait 1 second
}

Essential Functions
Digital I/O:

cpp

pinMode(pin, MODE); // Set pin mode: INPUT, OUTPUT, INPUT_PULLUP


digitalWrite(pin, VALUE); // Write: HIGH or LOW
int value = digitalRead(pin); // Read: HIGH or LOW

Analog I/O:

cpp

int value = analogRead(pin); // Read 0-1023 (10-bit ADC)


analogWrite(pin, value); // PWM output 0-255

Timing:

cpp

delay(milliseconds); // Pause execution


delayMicroseconds(microseconds);
unsigned long time = millis(); // Time since startup (ms)
unsigned long time = micros(); // Time since startup (µs)

Serial Communication:

cpp
[Link](9600); // Start serial at 9600 baud
[Link]("Hello"); // Print without newline
[Link]("World"); // Print with newline
[Link](); // Check for incoming data
char c = [Link](); // Read one byte

Pin Configuration
Arduino UNO Pins:

Digital Pins: 0-13 (0-1 used for Serial)

PWM Pins: 3, 5, 6, 9, 10, 11 (marked with ~)

Analog Input: A0-A5

Power: 5V, 3.3V, GND

Special: AREF, RESET

Database Integration
Complete Flow: Arduino → Database → Web
1. Arduino Side:

cpp
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>

#define DHTPIN D4
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);


const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* serverName = "[Link]

void setup() {
[Link](115200);
[Link]();

[Link](ssid, password);
while ([Link]() != WL_CONNECTED) {
delay(500);
[Link](".");
}
[Link]("\nConnected to WiFi");
}

void loop() {
float temp = [Link]();
float humidity = [Link]();

if (!isnan(temp) && !isnan(humidity)) {


sendToDatabase(temp, humidity);
}

delay(60000); // Send data every minute


}

void sendToDatabase(float temp, float hum) {


if([Link]() == WL_CONNECTED) {
WiFiClient client;
HTTPClient http;

[Link](client, serverName);
[Link]("Content-Type", "application/x-www-form-urlencoded");

String postData = "temperature=" + String(temp, 2) +


"&humidity=" + String(hum, 2);
int httpCode = [Link](postData);

if (httpCode > 0) {
String response = [Link]();
[Link]("Response: " + response);
} else {
[Link]("Error: " + [Link](httpCode));
}

[Link]();
}
}

2. Database Schema:

sql

CREATE DATABASE IF NOT EXISTS arduino_iot;


USE arduino_iot;

CREATE TABLE sensor_readings (


id INT AUTO_INCREMENT PRIMARY KEY,
device_id VARCHAR(50) DEFAULT 'device_001',
temperature DECIMAL(5,2),
humidity DECIMAL(5,2),
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_timestamp (timestamp),
INDEX idx_device (device_id)
);

-- Create view for latest readings


CREATE VIEW latest_readings AS
SELECT * FROM sensor_readings
ORDER BY timestamp DESC
LIMIT 100;

3. PHP API ([Link]):

php
<?php
header('Content-Type: application/json');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "arduino_iot";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


$temperature = floatval($_POST['temperature']);
$humidity = floatval($_POST['humidity']);

// Validate data
if ($temperature < -50 || $temperature > 100 ||
$humidity < 0 || $humidity > 100) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid sensor values']);
exit();
}

$stmt = $conn->prepare("INSERT INTO sensor_readings (temperature, humidity) VALUES (?, ?)");


$stmt->bind_param("dd", $temperature, $humidity);

if ($stmt->execute()) {
echo json_encode([
'status' => 'success',
'message' => 'Data inserted',
'id' => $stmt->insert_id
]);
} else {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Insert failed']);
}

$stmt->close();
} else {
http_response_code(405);
echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
}

$conn->close();
?>

4. Retrieve Data API (get_data.php):

php
<?php
header('Content-Type: application/json');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "arduino_iot";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die(json_encode(['error' => 'Connection failed']));
}

// Get last N records or time range


$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 50;
$hours = isset($_GET['hours']) ? intval($_GET['hours']) : 24;

$sql = "SELECT temperature, humidity,


DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i:%s') as timestamp
FROM sensor_readings
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL ? HOUR)
ORDER BY timestamp DESC
LIMIT ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $hours, $limit);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while($row = $result->fetch_assoc()) {
$data[] = $row;
}

echo json_encode($data);

$stmt->close();
$conn->close();
?>

Networking
MQTT Protocol (Alternative to HTTP)
MQTT is ideal for IoT projects with many devices or real-time requirements.

Setup Mosquitto Broker (Windows):

1. Download from [Link]


2. Install and start service
3. Default port: 1883

Arduino MQTT Client:

cpp
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* mqtt_server = "[Link]";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
[Link](115200);
setup_wifi();
[Link](mqtt_server, 1883);
[Link](callback);
}

void setup_wifi() {
[Link]("SSID", "PASSWORD");
while ([Link]() != WL_CONNECTED) {
delay(500);
}
}

void callback(char* topic, byte* payload, unsigned int length) {


[Link]("Message arrived [");
[Link](topic);
[Link]("] ");

for (int i = 0; i < length; i++) {


[Link]((char)payload[i]);
}
[Link]();
}

void reconnect() {
while (![Link]()) {
if ([Link]("ArduinoClient")) {
[Link]("home/commands");
} else {
delay(5000);
}
}
}

void loop() {
if (![Link]()) {
reconnect();
}
[Link]();

// Publish sensor data


float temp = readTemperature();
char msg[50];
snprintf(msg, 50, "%.2f", temp);
[Link]("home/temperature", msg);

delay(10000);
}

Project Ideas for IT Students


1. Smart Environmental Monitoring System ⭐ Recommended
Description: Monitor temperature, humidity, air quality in real-time with web dashboard.

Hardware:

ESP8266/ESP32

DHT22 sensor

MQ-135 air quality sensor

Optional: LCD display

Features:

Real-time data logging to MySQL

Historical data visualization (charts)

Email/SMS alerts for threshold violations

Mobile-responsive web dashboard

Export data to CSV/Excel

IT Skills Used: Database design, web development, API creation, data visualization

2. IoT-Based Smart Attendance System


Description: RFID-based attendance with automated reports and notifications.

Hardware:
Arduino UNO/ESP8266

RFID RC522 reader

RFID cards/tags

Buzzer for feedback

Features:

Student database (ID, name, photo)

Real-time attendance marking

Generate attendance reports

Late arrival tracking

Admin web panel

Parent notification system

IT Skills Used: Database management, authentication, reporting, email integration

3. Smart Home Automation System


Description: Control home appliances via web/mobile interface.

Hardware:

ESP8266

Relay modules (4-channel)

Temperature sensor

Motion sensor

Features:

Remote control of appliances

Scheduled automation (turn on/off at specific times)

Energy consumption monitoring

Security notifications (motion detection)

Voice control integration (optional)

IT Skills Used: IoT protocols, real-time communication, scheduling, security


4. Smart Agriculture/Irrigation System

Description: Automated plant watering based on soil moisture.

Hardware:

Arduino UNO/ESP8266

Soil moisture sensor

Water pump/solenoid valve

DHT22 sensor

Relay module

Features:

Automatic watering based on moisture level

Weather data integration

Water usage tracking

Crop health monitoring

Remote manual override

Analytics dashboard

IT Skills Used: Automation logic, external API integration, data analytics

5. Smart Parking System


Description: Real-time parking slot availability with web interface.

Hardware:

ESP8266

HC-SR04 ultrasonic sensors (per slot)

LEDs for indication

Features:

Real-time slot availability

Mobile app showing free slots

Parking duration tracking

Automated billing
Historical occupancy data

Reservation system (advanced)

IT Skills Used: Real-time systems, geolocation, payment integration, mobile development

6. Patient Health Monitoring System


Description: Remote patient monitoring with vital signs.

Hardware:

ESP32

Pulse oximeter sensor (MAX30100)

Temperature sensor

Optional: ECG sensor

Features:

Real-time vital signs display

Historical health data

Emergency alert system

Doctor/caregiver web portal

PDF report generation

Medication reminders

IT Skills Used: Healthcare data handling, real-time alerts, reporting, security compliance

7. Smart Energy Meter


Description: Monitor electricity consumption with cost calculation.

Hardware:

ESP8266

Current sensor (ACS712)

Voltage sensor

Features:

Real-time power consumption


Cost calculation

Daily/monthly usage reports

Appliance-wise breakdown

Compare with previous periods

Bill prediction

IT Skills Used: Data analytics, reporting, financial calculations

8. Warehouse Inventory Management


Description: Automated inventory tracking with RFID.

Hardware:

Arduino UNO/ESP8266

RFID reader

RFID tags on products

LED/LCD display

Features:

Auto-detect when items enter/leave

Real-time inventory count

Low stock alerts

Product database

Search and reports

Barcode scanner integration (optional)

IT Skills Used: Inventory management, database optimization, reporting

Sample Project: IoT Environmental Monitor


Complete Implementation Guide
Project Overview: Build a complete environmental monitoring system that measures temperature, humidity,
and air quality, stores data in MySQL, and displays it on a web dashboard.

Hardware Setup
Components:
ESP8266 (NodeMCU)

DHT22 sensor

MQ-135 gas sensor

Breadboard and jumpers

Power supply

Circuit Connections:

DHT22:
- VCC → 3.3V
- GND → GND
- DATA → D4 (GPIO2)

MQ-135:
- VCC → 5V (via VIN)
- GND → GND
- AOUT → A0

Complete Arduino Code

cpp
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <DHT.h>

// WiFi credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// Server details
const char* serverName = "[Link]

// Sensor pins
#define DHTPIN D4
#define DHTTYPE DHT22
#define MQ135PIN A0

DHT dht(DHTPIN, DHTTYPE);

// Timing
unsigned long lastTime = 0;
unsigned long timerDelay = 60000; // Send data every 60 seconds

void setup() {
[Link](115200);

// Initialize sensors
[Link]();
pinMode(MQ135PIN, INPUT);

// Connect to WiFi
[Link]("Connecting to WiFi...");
[Link](ssid, password);

while ([Link]() != WL_CONNECTED) {


delay(500);
[Link](".");
}

[Link]("");
[Link]("WiFi connected");
[Link]("IP Address: ");
[Link]([Link]());
}

void loop() {
// Send data at intervals
if ((millis() - lastTime) > timerDelay) {

// Check WiFi connection


if([Link]() == WL_CONNECTED) {

// Read sensors
float temperature = [Link]();
float humidity = [Link]();
int airQuality = analogRead(MQ135PIN);

// Validate readings
if (isnan(temperature) || isnan(humidity)) {
[Link]("Failed to read from DHT sensor!");
return;
}

// Display readings
[Link]("--- Sensor Readings ---");
[Link]("Temperature: ");
[Link](temperature);
[Link](" °C");
[Link]("Humidity: ");
[Link](humidity);
[Link](" %");
[Link]("Air Quality: ");
[Link](airQuality);

// Send to database
sendDataToServer(temperature, humidity, airQuality);

} else {
[Link]("WiFi Disconnected");
[Link]();
}

lastTime = millis();
}
}

void sendDataToServer(float temp, float hum, int airQ) {


WiFiClient client;
HTTPClient http;

// Specify destination
[Link](client, serverName);
[Link]("Content-Type", "application/x-www-form-urlencoded");
// Prepare POST data
String httpRequestData = "temperature=" + String(temp, 2) +
"&humidity=" + String(hum, 2) +
"&air_quality=" + String(airQ);

[Link]("Sending data to server...");

// Send POST request


int httpResponseCode = [Link](httpRequestData);

if (httpResponseCode > 0) {
[Link]("HTTP Response code: ");
[Link](httpResponseCode);
String response = [Link]();
[Link](response);
} else {
[Link]("Error code: ");
[Link](httpResponseCode);
[Link]([Link](httpResponseCode));
}

[Link]();
}

Database Setup

sql
-- Create database
CREATE DATABASE IF NOT EXISTS environmental_monitor;
USE environmental_monitor;

-- Sensor data table


CREATE TABLE sensor_data (
id INT AUTO_INCREMENT PRIMARY KEY,
temperature DECIMAL(5,2) NOT NULL,
humidity DECIMAL(5,2) NOT NULL,
air_quality INT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_timestamp (timestamp)
);

-- Alerts table (for threshold violations)


CREATE TABLE alerts (
id INT AUTO_INCREMENT PRIMARY KEY,
alert_type VARCHAR(50),
sensor_value DECIMAL(10,2),
threshold_value DECIMAL(10,2),
message TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Device info table (for multiple devices)


CREATE TABLE devices (
device_id VARCHAR(50) PRIMARY KEY,
device_name VARCHAR(100),
location VARCHAR(100),
last_seen DATETIME,
status ENUM('online', 'offline') DEFAULT 'offline'
);

PHP Backend ([Link])

php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "environmental_monitor";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
http_response_code(500);
echo json_encode([
'status' => 'error',
'message' => 'Database connection failed'
]);
exit();
}

// Process POST request


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

// Get and validate data


$temperature = isset($_POST['temperature']) ? floatval($_POST['temperature']) : null;
$humidity = isset($_POST['humidity']) ? floatval($_POST['humidity']) : null;
$air_quality = isset($_POST['air_quality']) ? intval($_POST['air_quality']) : null;

// Validation
if ($temperature === null || $humidity === null || $air_quality === null) {
http_response_code(400);
echo json_encode([
'status' => 'error',
'message' => 'Missing required parameters'
]);
exit();
}

// Validate ranges
if ($temperature < -50 || $temperature > 100) {
http_response_code(400);
echo json_encode([
'status' => 'error',
'message' => 'Temperature out of valid range'
]);
exit();
}

if ($humidity < 0 || $humidity > 100) {


http_response_code(400);
echo json_encode([
'status' => 'error',
'message' => 'Humidity out of valid range'
]);
exit();
}

// Prepare and execute insert


$stmt = $conn->prepare("INSERT INTO sensor_data (temperature, humidity, air_quality) VALUES (?, ?, ?)");
$stmt->bind_param("ddi", $temperature, $humidity, $air_quality);

if ($stmt->execute()) {

// Check for alerts


checkAlerts($conn, $temperature, $humidity, $air_quality);

echo json_encode([
'status' => 'success',
'message' => 'Data inserted successfully',
'id' => $stmt->insert_id,
'timestamp' => date('Y-m-d H:i:s')
]);
} else {
http_response_code(500);
echo json_encode([
'status' => 'error',
'message' => 'Failed to insert data'
]);
}

$stmt->close();

} else {
http_response_code(405);
echo json_encode([
'status' => 'error',
'message' => 'Method not allowed. Use POST.'
]);
}
$conn->close();

// Function to check and create alerts


function checkAlerts($conn, $temp, $hum, $airQ) {
// Define thresholds
$temp_high = 35;
$temp_low = 10;
$hum_high = 80;
$hum_low = 20;
$airQ_high = 600;

// Check temperature
if ($temp > $temp_high) {
insertAlert($conn, 'High Temperature', $temp, $temp_high,
"Temperature exceeded safe limit: {$temp}°C");
} elseif ($temp < $temp_low) {
insertAlert($conn, 'Low Temperature', $temp, $temp_low,
"Temperature below safe limit: {$temp}°C");
}

// Check humidity
if ($hum > $hum_high) {
insertAlert($conn, 'High Humidity', $hum, $hum_high,
"Humidity exceeded safe limit: {$hum}%");
} elseif ($hum < $hum_low) {
insertAlert($conn, 'Low Humidity', $hum, $hum_low,
"Humidity below safe limit: {$hum}%");
}

// Check air quality


if ($airQ > $airQ_high) {
insertAlert($conn, 'Poor Air Quality', $airQ, $airQ_high,
"Air quality poor: {$airQ}");
}
}

function insertAlert($conn, $type, $value, $threshold, $message) {


$stmt = $conn->prepare("INSERT INTO alerts (alert_type, sensor_value, threshold_value, message) VALUES (?, ?, ?, ?)");
$stmt->bind_param("sdds", $type, $value, $threshold, $message);
$stmt->execute();
$stmt->close();
}
?>
Get Data API (get_data.php)

php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "environmental_monitor";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die(json_encode(['error' => 'Connection failed']));
}

// Get parameters
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 100;
$hours = isset($_GET['hours']) ? intval($_GET['hours']) : 24;

// Fetch data
$sql = "SELECT
id,
temperature,
humidity,
air_quality,
DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i:%s') as timestamp
FROM sensor_data
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL ? HOUR)
ORDER BY timestamp DESC
LIMIT ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $hours, $limit);
$stmt->execute();
$result = $stmt->get_result();

$data = [];
while($row = $result->fetch_assoc()) {
$data[] = $row;
}

// Get statistics
$stats_sql = "SELECT
AVG(temperature) as avg_temp,
MIN(temperature) as min_temp,
MAX(temperature) as max_temp,
AVG(humidity) as avg_humidity,
AVG(air_quality) as avg_air_quality,
COUNT(*) as total_readings
FROM sensor_data
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL ? HOUR)";

$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param("i", $hours);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$stats = $stats_result->fetch_assoc();

// Return combined response


echo json_encode([
'status' => 'success',
'data' => $data,
'statistics' => $stats,
'count' => count($data)
]);

$stmt->close();
$stats_stmt->close();
$conn->close();
?>

Get Latest Reading API (get_latest.php)

php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "environmental_monitor";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die(json_encode(['error' => 'Connection failed']));
}

$sql = "SELECT
temperature,
humidity,
air_quality,
DATE_FORMAT(timestamp, '%Y-%m-%d %H:%i:%s') as timestamp
FROM sensor_data
ORDER BY timestamp DESC
LIMIT 1";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
$data = $result->fetch_assoc();
echo json_encode([
'status' => 'success',
'data' => $data
]);
} else {
echo json_encode([
'status' => 'error',
'message' => 'No data available'
]);
}

$conn->close();
?>

Web Dashboard ([Link])

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Environmental Monitoring Dashboard</title>
<script src="[Link]
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}

.container {
max-width: 1400px;
margin: 0 auto;
}

h1 {
text-align: center;
color: white;
margin-bottom: 30px;
font-size: 2.5em;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}

.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 30px;
}

.stat-card {
background: white;
border-radius: 15px;
padding: 25px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
transition: transform 0.3s;
}

.stat-card:hover {
transform: translateY(-5px);
}

.stat-card h3 {
color: #667eea;
font-size: 1em;
margin-bottom: 10px;
text-transform: uppercase;
letter-spacing: 1px;
}

.stat-value {
font-size: 2.5em;
font-weight: bold;
color: #333;
}

.stat-unit {
font-size: 1em;
color: #999;
margin-left: 5px;
}

.last-update {
color: #666;
font-size: 0.85em;
margin-top: 10px;
}

.chart-container {
background: white;
border-radius: 15px;
padding: 30px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
margin-bottom: 20px;
}

.chart-container h2 {
color: #667eea;
margin-bottom: 20px;
}

.status-indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 8px;
animation: pulse 2s infinite;
}

.status-online {
background: #4CAF50;
}

.status-offline {
background: #f44336;
}

@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}

.controls {
background: white;
border-radius: 15px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.controls select {
padding: 10px;
border-radius: 5px;
border: 2px solid #667eea;
font-size: 1em;
margin-right: 10px;
}

.alert-banner {
background: #ff9800;
color: white;
padding: 15px;
border-radius: 10px;
margin-bottom: 20px;
display: none;
}

.[Link] {
display: block;
}

@media (max-width: 768px) {


.stats-grid {
grid-template-columns: 1fr;
}

h1 {
font-size: 1.8em;
}
}
</style>
</head>
<body>
<div class="container">
<h1> 🌡️ Environmental Monitoring Dashboard</h1>
<div class="alert-banner" id="alertBanner">
⚠️<span id="alertMessage"></span>
</div>

<!-- Current Readings -->


<div class="stats-grid">
<div class="stat-card">
<h3> 🌡️ Temperature</h3>
<div class="stat-value">
<span id="currentTemp">--</span>
<span class="stat-unit">°C</span>
</div>
<div class="last-update">
<span class="status-indicator status-online" id="statusIndicator"></span>
<span id="lastUpdate">Waiting for data...</span>
</div>
</div>

<div class="stat-card">
<h3> 💧 Humidity</h3>
<div class="stat-value">
<span id="currentHumidity">--</span>
<span class="stat-unit">%</span>
</div>
<div class="last-update">
Average: <span id="avgHumidity">--</span>%
</div>
</div>
<div class="stat-card">
<h3> 🌫️ Air Quality</h3>
<div class="stat-value">
<span id="currentAirQuality">--</span>
<span class="stat-unit"></span>
</div>
<div class="last-update">
Status: <span id="airQualityStatus">Good</span>
</div>
</div>

<div class="stat-card">
<h3> 📊 Statistics</h3>
<div class="stat-value" style="font-size: 1.5em;">
<span id="totalReadings">--</span>
<span class="stat-unit">readings</span>
</div>
<div class="last-update">
Last 24 hours
</div>
</div>
</div>

<!-- Controls -->


<div class="controls">
<label for="timeRange">Time Range:</label>
<select id="timeRange" onchange="updateCharts()">
<option value="1">Last Hour</option>
<option value="6">Last 6 Hours</option>
<option value="12">Last 12 Hours</option>
<option value="24" selected>Last 24 Hours</option>
<option value="168">Last Week</option>
</select>

<button onclick="refreshData()" style="padding: 10px 20px; background: #667eea; color: white; border: none; border
🔄 Refresh
</button>
</div>

<!-- Temperature Chart -->


<div class="chart-container">
<h2>Temperature Over Time</h2>
<canvas id="temperatureChart"></canvas>
</div>

<!-- Humidity Chart -->


<div class="chart-container">
<h2>Humidity Over Time</h2>
<canvas id="humidityChart"></canvas>
</div>

<!-- Air Quality Chart -->


<div class="chart-container">
<h2>Air Quality Index</h2>
<canvas id="airQualityChart"></canvas>
</div>
</div>

<script>
let tempChart, humidityChart, airQualityChart;
let updateInterval;

// Initialize charts
function initCharts() {
const tempCtx = [Link]('temperatureChart').getContext('2d');
tempChart = new Chart(tempCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Temperature (°C)',
data: [],
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgba(255, 99, 132, 0.1)',
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
plugins: {
legend: { display: true }
},
scales: {
y: {
beginAtZero: false
}
}
}
} );

const humCtx = [Link]('humidityChart').getContext('2d');


humidityChart = new Chart(humCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Humidity (%)',
data: [],
borderColor: 'rgb(54, 162, 235)',
backgroundColor: 'rgba(54, 162, 235, 0.1)',
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true,
max: 100
}
}
}
} );

const airCtx = [Link]('airQualityChart').getContext('2d');


airQualityChart = new Chart(airCtx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Air Quality Index',
data: [],
borderColor: 'rgb(75, 192, 192)',
backgroundColor: 'rgba(75, 192, 192, 0.1)',
tension: 0.4,
fill: true
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
} );
}
// Fetch latest reading
function fetchLatestData() {
fetch('get_latest.php')
.then(response => [Link]())
.then(result => {
if ([Link] === 'success') {
const data = [Link];

[Link]('currentTemp').textContent =
parseFloat([Link]).toFixed(1);
[Link]('currentHumidity').textContent =
parseFloat([Link]).toFixed(1);
[Link]('currentAirQuality').textContent =
data.air_quality;
[Link]('lastUpdate').textContent =
'Updated: ' + [Link];

// Update air quality status


updateAirQualityStatus(data.air_quality);

// Check for alerts


checkAlerts([Link], [Link], data.air_quality);

// Update status indicator


[Link]('statusIndicator').className =
'status-indicator status-online';
}
})
.catch(error => {
[Link]('Error:', error);
[Link]('statusIndicator').className =
'status-indicator status-offline';
} );
}

// Fetch historical data


function fetchHistoricalData(hours = 24) {
fetch(`get_data.php?hours=${hours}&limit=100`)
.then(response => [Link]())
.then(result => {
if ([Link] === 'success') {
const data = [Link](); // Oldest first
const stats = [Link];

// Update statistics
[Link]('avgHumidity').textContent =
parseFloat(stats.avg_humidity).toFixed(1);
[Link]('totalReadings').textContent =
stats.total_readings;

// Update charts
updateChartData(tempChart, data, 'temperature');
updateChartData(humidityChart, data, 'humidity');
updateChartData(airQualityChart, data, 'air_quality');
}
})
.catch(error => [Link]('Error:', error));
}

// Update chart data


function updateChartData(chart, data, field) {
[Link] = [Link](item => {
const date = new Date([Link]);
return [Link]('en-US', {
hour: '2-digit',
minute: '2-digit'
} );
} );
[Link][0].data = [Link](item => parseFloat(item[field]));
[Link]();
}

// Update air quality status


function updateAirQualityStatus(value) {
const statusElement = [Link]('airQualityStatus');
if (value < 300) {
[Link] = 'Good';
[Link] = '#4CAF50';
} else if (value < 600) {
[Link] = 'Moderate';
[Link] = '#ff9800';
} else {
[Link] = 'Poor';
[Link] = '#f44336';
}
}

// Check for alerts


function checkAlerts(temp, humidity, airQuality) {
const alerts = [];

if (temp > 35) [Link](`High temperature: ${temp}°C`);


if (temp < 10) [Link](`Low temperature: ${temp}°C`);
if (humidity > 80) [Link](`High humidity: ${humidity}%`);
if (humidity < 20) [Link](`Low humidity: ${humidity}%`);
if (airQuality > 600) [Link]('Poor air quality detected');

const alertBanner = [Link]('alertBanner');


const alertMessage = [Link]('alertMessage');

if ([Link] > 0) {
[Link] = [Link](' | ');
[Link]('show');
} else {
[Link]('show');
}
}

// Update charts based on time range


function updateCharts() {
const hours = [Link]('timeRange').value;
fetchHistoricalData(hours);
}

// Refresh data manually


function refreshData() {
fetchLatestData();
updateCharts();
}

// Initialize on page load


[Link] = function() {
initCharts();
fetchLatestData();
fetchHistoricalData(24);

// Auto-update every 10 seconds


updateInterval = setInterval(() => {
fetchLatestData();
updateCharts();
}, 10000);
};
</script>
</body>
</html>
Resources & References
Official Documentation
Arduino Official Website: [Link]

Arduino Language Reference: [Link]

Arduino IDE Download: [Link]

ESP8266 Core: [Link]

ESP32 Core: [Link]

Learning Platforms
Arduino Project Hub: [Link]

Tinkercad Circuits: [Link]

Instructables Arduino: [Link]

[Link]: [Link]

YouTube Channels
Paul McWhorter: Comprehensive Arduino tutorials

GreatScott!: Electronics and Arduino projects

Programming Electronics Academy: Beginner-friendly

DroneBot Workshop: Advanced IoT projects

Electronoobs: Practical project tutorials

Component Datasheets
DHT22 Sensor: [Link]

HC-SR04 Ultrasonic: [Link]

MQ-135 Gas Sensor: [Link]


135/resources/[Link]

RFID RC522: [Link]

Libraries
DHT Sensor Library: By Adafruit

PubSubClient: MQTT for Arduino

ArduinoJson: JSON parsing

WiFiManager: Easy WiFi configuration


TimeLib: Time and date functions

Forums & Communities


Arduino Forum: [Link]

Reddit r/arduino: [Link]

Stack Overflow: Tag: [arduino]

Discord Communities: Arduino, ESP32/ESP8266

Tools
Fritzing: Circuit design ([Link]

EasyEDA: PCB design ([Link]

PlatformIO: Advanced IDE ([Link]

Serial Port Monitor: For debugging

Online Stores (Component Suppliers)


Arduino Official Store: [Link]

SparkFun: [Link]

Adafruit: [Link]

AliExpress: Budget components

Amazon: Quick delivery

DigiKey: Professional components

Mouser Electronics: Wide selection

Books (Recommended)
1. "Arduino Cookbook" by Michael Margolis
Comprehensive reference with 200+ recipes

2. "Programming Arduino: Getting Started with Sketches" by Simon Monk


Perfect for beginners

3. "Arduino Project Handbook" by Mark Geddes


25 practical projects

4. "Internet of Things with ESP8266" by Marco Schwartz


IoT-focused projects

Project Inspiration

Arduino Project Hub: Thousands of documented projects


[Link]: Community projects with code

GitHub: Search for "arduino projects"

YouTube: Search "Arduino + [your interest]"

Tips for Success


1. Start Simple

Don't jump to complex projects immediately

Master basics: LED, button, sensor reading

Build confidence before adding networking

2. Documentation is Key
Comment your code thoroughly

Keep a project journal

Take photos of circuit connections

Document errors and solutions

3. Testing Strategy
Test components individually first

Use Serial Monitor for debugging

Verify connections with multimeter

Test power supply stability

4. Common Mistakes to Avoid


Wrong voltage: Check if component needs 3.3V or 5V

Loose connections: Use quality jumper wires

Power issues: Don't power too many devices from Arduino

Pin conflicts: Don't use pins 0 & 1 if using Serial Monitor

Delay() overuse: Use millis() for non-blocking code

5. Troubleshooting Checklist

□ Is Arduino powered on?


□ Is correct board selected in IDE?
□ Is correct COM port selected?
□ Are all connections secure?
□ Is code uploaded successfully?
□ Are sensor readings within expected range?
□ Is Serial Monitor baud rate correct?
□ Are libraries installed?

6. Final Year Project Tips


Start early: Give yourself at least 3 months

Document everything: Keep weekly progress logs

Create milestones: Break project into phases

Test incrementally: Don't wait till end to test

Backup code: Use GitHub for version control

Prepare demo: Have working prototype ready

Create presentation: Explain technical and practical aspects

7. Presentation Points to Cover


Problem statement and motivation

System architecture diagram

Hardware components and circuit

Software flow and algorithms

Database design

Web interface demonstration

Results and testing

Future enhancements

Challenges faced and solutions

Weekly Milestone Checklist


Week 1-2: ☐ Foundation
Arduino IDE installed and working
First program uploaded (Blink)
Understand digital I/O
Read sensor data

Week 3-4: ☐ Sensors


DHT sensor reading temperature/humidity
Additional sensors tested
Data displayed on Serial Monitor
Basic data validation

Week 5-6: ☐ Connectivity


WiFi connection successful
HTTP request working
Data sent to web server
Error handling implemented

Week 7-8: ☐ Database


MySQL database created
PHP API working
Data successfully stored
Data retrieval tested

Week 9-10: ☐ Web Interface


Dashboard HTML created
Real-time data display working
Charts implemented
Responsive design

Week 11: ☐ Integration


All components connected
End-to-end testing complete
Alerts/notifications working
Bug fixes completed

Week 12: ☐ Documentation


Code commented
Circuit diagram created
User manual written
Presentation prepared
Demo ready

Conclusion
This guide provides a complete roadmap for learning Arduino and developing an impressive final year IT
project. Remember:
Be patient: Learning hardware takes time

Experiment: Try different sensors and combinations

Join communities: Ask questions when stuck

Document: Keep track of your progress

Have fun: Enjoy building something tangible!

Your IT background in programming, networking, and databases gives you a strong foundation. Arduino simply
adds the physical computing layer, allowing you to create real-world solutions.

Good luck with your final year project! 🚀

Last Updated: December 2025 Document Version: 1.0

You might also like