Skill Oriented Program: Shaik Akram
Skill Oriented Program: Shaik Akram
SHAIK AKRAM
(21JR1A05H2)
Under Supervision of
CERTIFICATE
This is to certify that the Skill-oriented titled “AI & IoT” is a bonafide work of SHAIK AKRAM
(21JR1A05H2), who carried out the work under my supervision and submitted in partial fulfillment
of the requirements for the award of credits in 3-2 of BACHELOR OF TECHNOLOGY in
COMPUTER SCIENCE and ENGINEERING during the academic year 2023-2024.
EXTERNAL EXAMINER
DECLARATION
I hereby inform that this SOC Report entitled “AI & IoT” has been Carried out and
submitted in partial fulfilment for the award to the degree of Bachelor of Technology in
COMPUTER SCIENCE AND ENGINEERING under the guidance of Mrs M.V.Sheela
Devi,the work embodied in this work is original and has not been submitted in part or full for the
award of credits in 3-2 B.Tech in CSE in the Academic year: 2023-2024
SHAIK AKRAM
(21JR1A05H2)
TABLE OF CONTENTS
1 Introduction to AI 1-4
5 Activity-3: 30-36
11 Activity-8: Write a program for IR Sensor and satisfy the condition. 56-58
16 Activity-13: Write a program for DHT level and read humidity and 71-73
temperature values.
17 Activity-14: Write a program to Rotate servomotor 0 to 90 degrees. 74-75
18 Activity-15: Write a program for ultra sonic sensor and print the 76-78
distance
19 Activity-16: Create an activity how to connect wifi with Node 79-81
26 Introduction 104-107
28 Conclusion 112
29 Certificate 113
COURSE OBJECTIVES:
• Automating tasks wherever possible to speed up processes and reduce human error.
• Making sure that code changes are continuously integrated and delivered, so that new
features can be released faster.
COURSE OUTCOMES:
At the end ofthis course, students will be able to:
CO1: Apply basic design principles to present ideas, information, products, and services on websites
and able to apply basic programming principles to the construction of websites effectively manage
website projects using available resources.
CO3: Use employability skills including fundamental skills, management skills, and teamwork
skills.
CO-PO Mapping
CO-PSO Mapping
C32.1 3
C32.2 2
C32.3 3
C32.4 2
Introduction to AI:
Artificial Intelligence (AI) refers to the development of computer systems that can perform tasks
that typically require human intelligence. These tasks include learning, reasoning, problem-
solving, perception, natural language understanding, and even speech recognition. AI systems
aim to mimic or simulate human cognitive functions, enabling machines to perform complex
tasks autonomously.
The ethical implications of AI, including issues related to bias, transparency, and job
displacement, are also important considerations. As AI continues to advance, ongoing
discussions and regulations aim to address these concerns and ensure responsible development
and use of this powerful technology.
Applications of AI:
1. Healthcare:
Diagnostics: AI is used for medical image analysis, helping in the early detection of diseases
through techniques like computer-aided diagnosis (CAD).
Drug Discovery:Accelerating the process of identifying potential drug candidates and
optimizing drug development pipelines.
Personalized Medicine: Tailoring treatment plans based on individual patient data.
2. Finance:
Algorithmic Trading: AI algorithms analyze market data to make trading decisions,
optimizing investment strategies.
Fraud Detection: Identifying unusual patterns and anomalies in financial transactions to detect
fraudulent activities.
Credit Scoring: AI assesses creditworthiness by analyzing various factors and historical data.
3. Education:
Adaptive Learning: Customizing educational content and experiences based on individual
student performance and needs.
Automated Grading: AI systems can assess and grade assignments, quizzes, and exams.
Intelligent Tutoring Systems: Providing personalized assistance to students in real-time.
4. Retail:
Recommendation Systems: AI algorithms analyze customer preferences and behaviors to
recommend products or services.
Inventory Management: Predicting demand and optimizing inventory levels to reduce costs
and prevent stockouts.
Chatbots and Virtual Assistants: Enhancing customer service through automated chat support.
5. Autonomous Vehicles:
Self-Driving Cars: AI is crucial for perceiving the environment, making decisions, and
navigating without human intervention.
Traffic Management: AI helps optimize traffic flow, reduce congestion, and improve
transportation systems.
7. Cybersecurity:
Anomaly Detection: Identifying unusual patterns or behaviors that may indicate a security
threat.
Malware Detection: AI analyzes patterns and signatures to detect and prevent malware attacks.
Authentication Systems:Enhancing security through biometric recognition and behavioral
analysis.
8. Manufacturing:
Predictive Maintenance: AI analyzes data from sensors to predict when equipment or
machinery needs maintenance, reducing downtime.
Quality Control: Computer vision systems inspect and ensure the quality of products on the
production line.
Supply Chain Optimization: AI optimizes the supply chain by predicting demand, managing
inventory, and improving logistics.
9. Entertainment:
Content Recommendation: AI suggests movies, music, or content based on user preferences.
Gaming: AI is used to create intelligent and adaptive non-player characters (NPCs) in video
games.
Content Creation: AI-generated art, music, and writing.
10. Agriculture:
Precision Farming: AI analyzes data from sensors, satellites, and drones to optimize crop
management.
Crop Monitoring: Using computer vision to monitor the health and growth of crops.
Predictive Analytics: AI helps predict crop yields, disease outbreaks, and optimal planting
times.
These applications showcase the diverse and transformative impact of AI across various
sectors, continually evolving as technology advances.
History:
1950s-1960s: Early concepts and foundations of ML were laid down, with pioneers like Alan
Turing and the development of the perceptron algorithm by Frank Rosenblatt.
1970s-1980s: The field faced challenges and skepticism, leading to the "AI winter." However,
notable developments, such as the introduction of decision trees, occurred during this period.
1990s-2000s: ML experienced a revival with advancements in algorithms, computing power,
and the availability of large datasets. Support Vector Machines and ensemble methods gained
popularity.
2010s-Present: Deep learning, a subset of ML, gained prominence, achieving breakthroughs in
image and speech recognition, natural language processing, and other domains.
Feature Selection: Identify relevant features that contribute to predicting the output.
Model Selection: Choose an appropriate algorithm based on the nature of the problem
(classification or regression).
Model Training: Feed the training data into the chosen model, allowing it to adjust its
parameters to minimize the difference between predicted and actual outputs.
Model Evaluation: Assess the model's performance on a separate testing dataset to ensure it
generalizes well to new, unseen data.
Prediction: Use the trained model to make predictions on new, unseen data.
2.Unsupervised Learning:
Unsupervised learning is a type of machine learning where the model is provided with input
data without explicit output labels. The goal is for the model to discover patterns, structures, or
relationships within the data. Unsupervised learning is particularly useful when the dataset
lacks labeled examples, and the objective is to explore the inherent structure within the data.
There are two main types of unsupervised learning: clustering and dimensionality reduction.
1. Clustering:
Clustering involves grouping similar data points together based on their inherent
characteristics. The algorithm aims to identify natural groupings within the data without prior
knowledge of the class labels.
Examples:
Customer segmentation based on purchasing behavior.
Grouping news articles into topics.
2. Dimensionality Reduction:
Dimensionality reduction involves reducing the number of features or variables in the dataset
while preserving its essential characteristics. This can help in visualizing and understanding
complex relationships within high-dimensional data.
Examples:
Principal Component Analysis (PCA) for feature reduction.
t-Distributed Stochastic Neighbor Embedding (t-SNE) for visualizing high-dimensional data in
two or three dimensions.
3. Reinforcement Learning:
Reinforcement Learning (RL) is a type of machine learning where an agent learns to make
decisions by interacting with an environment. The agent receives feedback in the form of
rewards or penalties, allowing it to learn optimal strategies over time. There are several types
of reinforcement learning approaches, and the fundamental concepts include states, actions,
rewards, and policies.
Data Preprocessing:
Data preprocessing is a crucial step in machine learning that involves transforming raw data
into a clean, organized format that is suitable for analysis and modeling. The main objectives of
data preprocessing are to improve the quality of data, enhance the performance of machine
learning models, and ensure that the data is suitable for the chosen algorithm. Here are the
steps involved in data preprocessing and reasons why it's necessary:
1. Data Cleaning:
Handle Missing Values: Many datasets contain missing values, which can cause errors during
analysis or modeling. Imputation techniques such as mean, median, or mode substitution, or
more sophisticated methods like interpolation, can be used to fill in missing values.
Noise Reduction: Outliers, errors, or noise in the data can adversely affect model performance.
Techniques like smoothing, binning, or outlier detection/removal can help reduce noise.
Consistency Checks: Ensure consistency in data formats, units, and values. For example,
converting categorical variables into a consistent format or checking for data integrity issues.
2. Data Transformation:
Normalization/Standardization: Scaling numerical features to a similar scale can improve the
performance of certain algorithms, particularly those based on distance measures like K-
nearest neighbors (KNN) or gradient descent optimization techniques.
Encoding Categorical Variables: Converting categorical variables into numerical
representations that can be easily processed by machine learning algorithms. This can involve
techniques like one-hot encoding, label encoding, or target encoding.
3. Data Reduction:
Dimensionality Reduction: When dealing with high-dimensional data, reducing the number of
features can help reduce computational complexity, alleviate the curse of dimensionality, and
improve model generalization. Techniques like principal component analysis (PCA), feature
selection, or feature extraction can be used for this purpose.
4. Data Discretization:
Binning: Grouping continuous values into discrete intervals. This can simplify the data and
improve the robustness of the model, especially for decision tree-based algorithms or
association rule mining.
Bucketing: Similar to binning, but for categorical variables. Grouping infrequent categories
into a single category or grouping similar categories together can help reduce complexity and
noise in the data.
5. Data Integration:
Combining Data Sources: When working with multiple datasets, integrating them into a single
cohesive dataset can provide a more comprehensive view of the problem domain and improve
model performance.
6. Data Normalization:
Scaling: Scaling numerical features to a similar range can help prevent certain features from
dominating others in algorithms that are sensitive to feature magnitudes, such as gradient
descent-based optimization algorithms.
7. Data Splitting:
Train-Test Split: Splitting the dataset into training and testing subsets allows for the evaluation
of model performance on unseen data, helping to assess the generalization ability of the model.
10
Activity-1
Create a Data For Countries Using Data Preprocessing Steps
importing libraies
import numpy a s np
import pandas as pd
data.columns
Index(['Country', 'Age', 'Salary', 'Purchased'], dtype='object')
data.head()
data.tail()
11
data.head(8)
data.Country
0 France
1 Spain
2 Germany
3 Spain
4 Germany
5 France
6 Spain
7 France
8 Germany
9 France
12
8 50.0
9 37.0
Name: Age, dtype: float64
data.Salary
0 72000.0
1 48000.0
2 54000.0
3 61000.0
4 NaN
5 58000.0
6 52000.0
7 79000.0
8 83000.0
9 67000.0
13
data.iloc[0:4]
data.iloc[1:4]
Country Age Salary Purchased
1 Spain 27.0 48000.0 Yes
2 Germany 30.0 54000.0 No
3 Spain 38.0 61000.0 No
data.iloc[:4,:1]
Country
0 France
1 Spain
2 Germany
3 Spain
data.iloc[2:4,:1]
Country
2 Germany
3 Spain
data.iloc[:7,:3]
14
data.iloc[:7,2]
0 72000.0
1 48000.0
2 54000.0
3 61000.0
4 NaN
5 58000.0
6 52000.0
15
type(y)
pandas.core.series.Series
x.values
Output:
array([['France', 44.0, 72000.0],
['Spain', 27.0, 48000.0],
['Germany', 30.0, 54000.0],
['Spain', 38.0, 61000.0],
['Germany', 40.0, nan],
['France', 35.0, 58000.0],
['Spain', nan, 52000.0],
['France', 48.0, 79000.0],
['Germany', 50.0, 83000.0],
['France', 37.0, 67000.0]], dtype=object)
16
17
18
Activity-2
Create EDA For Given Data.
import numpy as np
import pandas as pd
data=pd.read_csv('train.csv')
data
Passenger
Id Survi Pclass Name Sex Age Sibsp Parch Ticket
ved
Braund,
0 1 0 3 Mr.Owen Male 22.0 1 0 A/5
Harris 21171
Currings,
Mrs.John
1 2 1 1 Bradle Female 38.0 1 0 PC
(Fiorence 17599
Briggs
Th…)
Heikkinen,
2 3 1 3 Miss. female 26.0 0 0 STON/02
Laina 3101282
Futrella,
Mrs.Jacques
3 4 1 1 Health female 35.0 1 0 113803
(Lily May
Peel)
data.head()
Passenger
Id Survived Pclass Name Sex Age Sibsp Parch Ticket F
Braund,
0 1 0 3 Mr.Owen Male 22.0 1 0 A/5 7.2
Harris 21171
Currings,
Mrs.John
1 2 1 1 Bradle Female 38.0 1 0 PC 71.2
(Fiorence 17599
Briggs
Th…)
19
data.tail()
Passenger
Id Survived Pclass Name Sex Age Sibsp Parch Ticket Fare
Montvila,
886 887 0 2 Rev. Male 27.0 1 0 211536 13.00
Juoza
S
Graham, 1
887 888 1 1 Miss. Female 19.0 0 112053 30.00
Margare
T
Edith
Data.head(1)
Passenger
Id Survived Pclass Name Sex Age Sibsp Parch Ticket Fare
Braund,
Data.tail(1):
Passenger
Id Survived Pclass Name Sex Age Sibsp Parch Ticket Fare
Dooley
Mean
mean=data.Age.mean()
mean
Output:
29.69911764705882
Median
median=data.Fare.median()
median
20
Output:
14.4542
Mode:
mode=data.Sex.mode()
mode
Output:
0 male
Name: Sex, dtype: object
Count
count=data.Ticket.count()
count
Output:
891
max=data.Age.max()
max
Output:
80.0
min=data.Age.min( )
min
Output:
0.42
data.describe ( ):
Passenger
Id Survived Pclass Age SibSp Age Parch Fare
Count 891.000000 891.000000 891.000000 714.000000 891.000000 891.000000 891.000 891.000000
21
Bar chart
import plotly.express as px
dataset=px.data.iris()
fig=px.bar (dataset, x='species',y='petal_width')
fig.show()
Histogram
22
import plotly.express as px
dataset=px.data.iris()
fig=px.histogram(dataset,x='sepal_length',y='petal_length')
fig.show()
Scatterplot:
import plotly.express as px
dataset=px.data.iris()
fig=px.scatter(dataset,x='species',y='petal_width')
fig.show()
Bubbleplot:
import plotly.express as px
dataset=px.data.iris()
fig=px.scatter(dataset,x='species',y='petal_width',size='petal_length',color='species')
fig.show()
23
Classification Algorithms:
Classification algorithms are a fundamental component of machine learning and are used to
categorize data points into predefined classes or categories based on their features. These
algorithms learn from labeled training data and then predict the class labels for new, unseen
data points. Here are some commonly used classification algorithms:
Logistic Regression:
Logistic Regression is a statistical method used for binary classification tasks, meaning it
predicts the probability that an instance belongs to a particular class. Despite its name, logistic
regression is used for classification rather than regression.
Here's how logistic regression works:
1. Sigmoid Function: Logistic regression uses the sigmoid (logistic) function to model the
probability that a given input belongs to a certain class. The sigmoid function takes any real-
valued number and maps it to a value between 0 and 1, which represents the probability.
\[ \sigma(z) = \frac{1}{1 + e^{-z}} \]
where \( z \) is the linear combination of the input features and their corresponding weights.
2. Decision Boundary: Logistic regression learns a decision boundary that separates the classes
in the feature space. For binary classification, this decision boundary is a hyperplane.
3. Training: Logistic regressionis trained using a method called maximum likelihood
estimation. The model parameters (weights) are adjusted iteratively to maximize the likelihood
of the observed data given the model.
4. Cost Function: The cost function used in logistic regression is the logarithmic loss (or cross-
entropy loss), which measures the difference between the predicted probabilities and the actual
class labels.
\[ J(\theta) = -\frac{1}{m} \sum_{i=1}^{m} \left( y^{(i)} \log(h_{\theta}(x^{(i)})) + (1 -
y^{(i)}) \log(1 - h_{\theta}(x^{(i)})) \right) \]
24
where \( h_{\theta}(x) \) is the sigmoid function, \( x^{(i)} \) are the input features of the \( i
\)th instance, \( y^{(i)} \) is the corresponding actual class label (0 or 1), and \( \theta \) are the
model parameters.
5. Regularization: Regularization techniques such as L1 regularization (Lasso) or L2
regularization (Ridge) can be applied to logistic regression to prevent overfitting by penalizing
large parameter values.
Decision Trees:
Decision Trees are a popular and intuitive machine learning algorithm used for both
classification and regression tasks. In the context of classification, decision trees partition the
feature space into regions, with each region corresponding to a particular class label. Here's
how decision trees work:
Tree Structure: A decision tree is a hierarchical structure consisting of nodes and branches.
Each internal node represents a decision based on the value of a feature, and each leaf node
represents a class label.
Feature Selection: At each internal node, the decision tree algorithm selects the feature that
best splits the data into subsets that are as pure as possible in terms of class labels. The purity
of a subset is typically measured using metrics like Gini impurity or entropy.
Recursive Partitioning: The process of selecting features and splitting the data into subsets is
performed recursively until certain stopping criteria are met. These criteria may include
reaching a maximum tree depth, having a minimum number of samples in each leaf node, or no
further improvement in purity.
Classification: Once the decision tree is constructed, class labels for new instances are
determined by traversing the tree from the root node to a leaf node based on the feature values
of the instance.
Interpretability: One of the key advantages of decision trees is their interpretability. The
decision rules learned by the tree can be easily understood and visualized, making them
valuable for explaining the model's predictions to stakeholders.
25
Handling Categorical and Numerical Features: Decision trees can handle both categorical
and numerical features. For categorical features, the tree considers each possible value as a
separate branch. For numerical features, the tree selects a threshold to split the data into two
subsets.
Pruning: Decision trees are prone to overfitting, especially when the tree becomes too complex.
Pruning techniques can be applied to simplify the tree by removing nodes that do not
significantly improve its predictive performance on a validation dataset.
Ensemble Methods: Decision trees can be combined into ensemble methods such as Random
Forests and Gradient Boosted Trees to improve performance and reduce overfitting.
Random Forest:
Random Forest is an ensemble learning method based on decision trees. It builds multiple
decision trees during training and combines their predictions to improve accuracy and reduce
overfitting. Here's how Random Forest works:
Bootstrapped Sampling: Random Forest creates multiple bootstrap samples (random samples
with replacement) from the original dataset. Each bootstrap sample is used to train a decision
tree.
Random Feature Selection: At each node of the decision tree, Random Forest considers only a
random subset of features (often the square root of the total number of features). This helps in
decorrelating the trees and reducing overfitting.
Decision Tree Training: For each bootstrap sample, a decision tree is grown using a process
similar to the standard decision tree algorithm (e.g., CART). However, since only a subset of
features is considered at each node, the trees are typically less deep.
Voting or Averaging: For classification tasks, each decision tree in the Random Forest
ensemble predicts the class label of a new instance. The final prediction is determined by
majority voting among the predictions of all trees. For regression tasks, the final prediction is
often the average of predictions from all trees.
26
Bagging: Random Forest uses a technique called bagging (Bootstrap Aggregating) to combine
predictions from multiple models trained on different subsets of the data. This reduces variance
and helps improve generalization performance.
Parallelization: Training each decision tree in a Random Forest can be done independently,
allowing for efficient parallelization across multiple processors or threads.
Out-of-Bag Error: Since each tree in the Random Forest is trained on a bootstrap sample,
some data points are left out (out-of-bag samples). These out-of-bag samples can be used to
estimate the model's performance without the need for a separate validation set.
Feature Importance: Random Forest can provide a measure of feature importance based on
how much each feature contributes to reducing impurity across all trees in the ensemble. This
can be useful for feature selection and understanding the underlying data patterns.
Support Vector Machines (SVM): SVM is a powerful classification algorithm that finds the
hyperplane that best separates the classes in the feature space. It works particularly well in
high-dimensional spaces.
K-Nearest Neighbors (KNN):
K-Nearest Neighbors (KNN) is a simple and intuitive machine learning algorithm used for both
classification and regression tasks. In this explanation, I'll focus on its application for
classification:
Basic Idea: The fundamental idea behind KNN is to predict the class of a data point by looking
at the majority class among its K nearest neighbors in the feature space. It assumes that similar
instances tend to belong to the same class.
Parameter K: The value of K is a hyperparameter that needs to be specified before applying the
algorithm. It determines the number of nearest neighbors to consider when making predictions.
A larger K means smoother decision boundaries but may also lead to more noise in the
predictions, while a smaller K can capture finer details but may be more sensitive to outliers.
27
Distance Metric: KNN relies on a distance metric to measure the similarity between data points
in the feature space. The most commonly used distance metrics are Euclidean distance,
Manhattan distance, and Minkowski distance. The choice of distance metric depends on the
nature of the data and the underlying problem.
Decision Rule: Once the K nearest neighbors of a data point are identified based on the chosen
distance metric, the majority class among these neighbors is assigned to the data point. In the
case of ties, a simple voting mechanism or weighted voting can be used to break the tie.
Classification Boundary: The decision boundary in KNN is non-linear and can adapt to the
shape of the data. It is defined by the regions where the majority class among the K nearest
neighbors changes.
Scalability: One of the drawbacks of KNN is its computational complexity during prediction, as
it requires computing distances between the query point and all training points. This can make
KNN less suitable for large datasets with high dimensionality.
Normalization: It's important to normalize or standardize the feature values before applying
KNN, especially if the features have different scales. Failure to do so can lead to features with
larger scales dominating the distance calculations.
Curse of Dimensionality: KNN performance can degrade as the number of dimensions
(features) increases, a phenomenon known as the curse of dimensionality. In high-dimensional
spaces, the notion of distance becomes less meaningful, and the data points may appear
equidistant from each other.
28
29
Activity-3
import numpy as np
import pandas as pd
data=pd.read_csv('crop.csv')
x=data.iloc[:,:7].values
x
array([[ 90. , 42. , 43. , ..., 82.00274423,
6.50298529, 202.9355362 ],
[ 85. , 58. , 41. , ..., 80.31964408,
7.03809636, 226.6555374 ],
[ 60. , 55. , 44. , ..., 82.3207629 ,
7.84020714, 263.9642476 ],
...,
[118. , 33. , 30. , ..., 67.22512329,
6.36260785, 173.3228386 ],
[117. , 32. , 34. , ..., 52.12739421,
6.75879255, 127.1752928 ],
30
31
32
33
34
35
36
37
Architecture of IoT:
The architecture of IoT typically consists of the following layers:
1. PerceptionLayer: This layer includes sensors, actuators, and other devices that collect data
from the physical environment.
2. Network Layer: Data collected by devices are transmitted through various communication
protocols like Wi-Fi, Bluetooth, Zigbee, or cellular networks to the next layer.
3. Middleware Layer: This layer processes and manages the data received from the network
layer. It may include gateways, protocol converters, and data storage solutions.
4. ApplicationLayer: Here, the processed data is utilized by applications and services to
provide value-added functionalities such as analytics, visualization, automation, and decision-
making.
Advantages of IoT:
1. Efficiency: IoT enables automation and optimization of processes, leading to increased
operational efficiency and reduced resource consumption.
2.Improved Decision Making: Real-time data collection and analysis from IoT devices
empower businesses and individuals to make informed decisions promptly.
3.Cost Savings: IoT facilitates predictive maintenance, asset tracking, and energy management,
resulting in cost reductions through optimized resource utilization and reduced downtime.
4.Enhanced Safety and Security: IoT enables remote monitoring of assets, infrastructure, and
environments, enhancing safety measures and enabling timely responses to security threats.
38
5.Convenience: IoT devices offer convenience through remote access and control of various
devices and systems, making daily tasks easier and more manageable.
6.Innovation: IoT fosters innovation by enabling the development of new products, services,
and business models that leverage connected devices and data-driven insights.
Boards in IOT:
In IoT (Internet of Things) development, various hardware platforms or development boards are
used to prototype, build, and deploy IoT solutions. These boards provide the necessary
computing power, connectivity options, and peripheral interfaces to interface with sensors,
actuators, and other components. Here are some commonly used IoT development boards:
Arduino Boards:
Arduino Uno: A popular choice for beginners and prototyping due to its simplicity and
versatility.
The Arduino Uno has a variety of pins that serve different purposes. Here's a breakdown of the
pins on an Arduino Uno:
1. Digital Pins (0-13):
These pins can be configured as digital input or output. Pin 0 (RX) and Pin 1 (TX) are also used
for serial communication with the computer.
Pins 3, 5, 6, 9, 10, and 11 support Pulse Width Modulation (PWM) for analog-like output.
2.Analog Pins (A0-A5):
These pins can be used as analog inputs to read voltage levels. They can also function as
digital inputs or outputs (14-19) when using digital functions.
3.Power Pins:
5V: Provides a regulated 5V output used to power external components.
3.3V: Provides a regulated 3.3V output used to power external components.
Vin: The voltage supplied to the board when it's using an external power source (e.g., a
battery).
GND (Ground): Ground pins used as the reference voltage for digital and analog circuits.
4. Other Pins:
RESET: This pin is used to reset the microcontroller.
AREF: Analog Reference voltage pin. Used to set an external reference voltage (0-5V) for
analog input pins.
ICSP Header: In-Circuit Serial Programming header used for programming the
microcontroller using an external programmer.
39
Crystal Oscillator Pins: Two pins (XTAL1 and XTAL2) for connecting an external crystal
oscillator for clocking the microcontroller.
These pins provide various functionalities and can be utilized to interface with a wide range of
sensors, actuators, displays, and other electronic components. Understanding the capabilities
and limitations of each pin is essential when designing and building Arduino projects.
Arduino Nano: A compact version of the Uno, suitable for projects with space constraints.
The Arduino Nano is a compact microcontroller board based on the ATmega328P
microcontroller, similar to the Arduino Uno but in a smaller form factor. It features a variety of
digital and analog pins that can be used for interfacing with sensors, actuators, and other
electronic components. Here's an overview of the pins on an Arduino Nano:
Digital Pins (D2 - D13):
These pins can be configured as digital input or output. Pin 13 also has an onboard LED
connected to it, similar to the Arduino Uno.
Analog Pins (A0 - A7):
These pins can be used as analog inputs to read voltage levels. They can also function as digital
inputs or outputs (D14 - D21) when using digital functions.
Power Pins:
5V: Provides a regulated 5V output used to power external components.
3.3V: Provides a regulated 3.3V output used to power external components.
Vin: The voltage supplied to the board when it's using an external power source (e.g., a
battery).
GND (Ground): Ground pins used as the reference voltage for digital and analog circuits.
40
Other Pins:
RESET: This pin is used to reset the microcontroller.
TX (Transmit) and RX (Receive): Pins for serial communication with other devices.
A6 and A7: Analog input-only pins without digital functions.
USB Interface:
The Nano can be powered and programmed via a USB interface, similar to the Uno.
Crystal Oscillator Pins:
Two pins (XTAL1 and XTAL2) for connecting an external crystal oscillator for clocking the
microcontroller.
Arduino Mega: Offers more GPIO pins and memory compared to Uno, suitable for larger
projects.
Arduino MKR Series: Designed specifically for IoT applications with built-in connectivity
options like Wi-Fi, GSM, and LoRa.
Raspberry Pi:
Raspberry Pi 3/4: Although primarily known as a single-board computer, Raspberry Pi is
widely used in IoT projects due to its processing power, connectivity options (Wi-Fi, Bluetooth),
and GPIO pins for interfacing with sensors and actuators. It can run various operating systems,
including Linux-based distributions.
GPIO Pins:
Raspberry Pi models typically have a set of GPIO pins, which are numbered and can be used
for digital input/output operations.
The number and layout of GPIO pins may vary depending on the specific Raspberry Pi model.
For example, the Raspberry Pi 4 Model B has 40 GPIO pins, while earlier models may have
fewer pins.
These pins can be controlled using software to read digital inputs (e.g., button presses) or to
output digital signals (e.g., controlling LEDs or relays).
Power Pins:
3.3V: Provides a regulated 3.3V power output for external components.
5V: Provides a regulated 5V power output for external components.
GND (Ground): Ground pins used as the reference voltage for digital and analog circuits.
Other Pins:
5V and 3.3V Pins: These pins provide a direct 5V or 3.3V power output, respectively.
I2C Pins (SDA, SCL): These pins are used for I2C (Inter-Integrated Circuit) communication
with external devices.
41
UART Pins (RX, TX): These pins are used for serial communication (UART) with external
devices.
SPI Pins (MOSI, MISO, SCLK, CE0, CE1): These pins are used for SPI (Serial Peripheral
Interface) communication with external devices.
PWM Pins: Some GPIO pins support Pulse Width Modulation (PWM), which can be used for
analog-like output (e.g., controlling the brightness of LEDs).
ID_SD and ID_SC Pins: Reserved for use with the Raspberry Pi HAT (Hardware Attached on
Top) identification EEPROM.
Other Interfaces:
Camera Connector: A dedicated connector for attaching the Raspberry Pi Camera Module.
Display Connector: A dedicated connector for attaching displays using the DSI (Display Serial
Interface) standard.
CSI (Camera Serial Interface) Connector: A dedicated connector for attaching displays using
the CSI standard.
42
Analog Pins:
NodeMCU boards also feature analog input pins, which can be used to read analog voltage
levels from sensors or other analog devices.
Analog pins are labeled A0 to A5 and can also function as digital GPIO pins when needed.
Power Pins:
3V3 (3.3V): Provides a regulated 3.3V power output for external components.
GND (Ground): Ground pins used as the reference voltage for digital and analog circuits.
Vin: The voltage supplied to the board when it's using an external power source (e.g., a
battery).
5V: Provides a regulated 5V power output for external components.
USB Interface:
NodeMCU boards can be powered and programmed via a USB interface, similar to Arduino
boards.
They typically feature a micro USB port for connecting to a computer for programming and
serial communication.
Reset Button:
A reset button is usually present on NodeMCU boards, which can be pressed to reset the board
or restart the program execution.
Flash Button:
Some NodeMCU boards feature a flash button, which is used for putting the board into
firmware flashing mode when uploading new firmware or programs.
LEDs:
NodeMCU boards often include built-in LEDs that indicate power status, Wi-Fi connectivity,
and other system states.
43
ESP32 Dev Kit: An upgraded version of the ESP8266, the ESP32 offers more GPIO pins, dual-
core processing, Bluetooth, and Wi-Fi connectivity.
GPIO Pins:
The ESP32 features a large number of General Purpose Input/Output (GPIO) pins, which can
be configured as digital inputs or outputs.
The specific number and configuration of GPIO pins may vary depending on the ESP32
development board variant. For example, the ESP32 DevKit has numerous GPIO pins labeled
GPIO0 to GPIO39.
Analog Pins:
The ESP32 also includes several analog input pins, which can be used to read analog voltage
levels from sensors or other analog devices.
Analog pins are typically labeled A0 to A19, although not all pins may be available on every
ESP32 development board variant.
Power Pins:
3V3 (3.3V): Provides a regulated 3.3V power output for external components.
GND (Ground): Ground pins used as the reference voltage for digital and analog circuits.
Vin: The voltage supplied to the board when it's using an external power source (e.g., a
battery).
5V: Provides a regulated 5V power output for external components.
USB Interface:
ESP32 development boards can be powered and programmed via a USB interface, similar to
other microcontroller development boards.
They typically feature a micro USB port for connecting to a computer for programming and
serial communication.
Reset Button:
A reset button is usually present on ESP32 development boards, which can be pressed to reset
the board or restart the program execution.
Flash Button:
Some ESP32 development boards feature a flash button, which is used for putting the board into
firmware flashing mode when uploading new firmware or programs.
LEDs:
ESP32 development boards often include built-in LEDs that indicate power status, Wi-Fi
connectivity, and other system states.
Sensors in IOT:
44
Temperature Sensors:
Thermistor: Changes resistance with temperature.
Temperature ICs: Integrated circuits designed specifically for temperature sensing (e.g., LM35,
DS18B20).
Infrared Temperature Sensors: Measures temperature remotely using infrared radiation.
Humidity Sensors:
Capacitive Humidity Sensors: Measures humidity by changes in capacitance.
Resistive Humidity Sensors: Measures humidity by changes in resistance.
Gravimetric Humidity Sensors: Measures humidity by changes in mass.
Pressure Sensors:
Piezoelectric Pressure Sensors: Generates an electrical charge proportional to applied
pressure.
Capacitive Pressure Sensors: Measures pressure-induced changes in capacitance.
Strain Gauge Pressure Sensors: Measures pressure-induced strain in a material.
Proximity Sensors:
Inductive Proximity Sensors: Detects metallic objects without physical contact.
Capacitive Proximity Sensors: Detects non-metallic objects based on capacitance changes.
Ultrasonic Proximity Sensors: Uses ultrasonic waves to detect objects' proximity.
Motion Sensors:
Passive Infrared (PIR) Sensors: Detects motion based on changes in infrared radiation.
Microwave Sensors: Detects motion based on microwave reflection.
Ultrasonic Sensors: Measures distance by emitting ultrasonic waves and calculating the time it
takes for them to return.
Light Sensors:
Photodiodes: Converts light into current.
Phototransistors: Amplifies current produced by incident light.
Photoresistors (LDRs): Changes resistance based on incident light intensity.
Gas Sensors:
Carbon Monoxide (CO) Sensors: Detects the presence of carbon monoxide gas.
Methane (CH4) Sensors: Detects the presence of methane gas.
Air Quality Sensors: Measures various air pollutants such as CO2, VOCs, etc.
45
Level Sensors:
Float Sensors: Detects liquid levels by floating on the surface.
Capacitive Level Sensors: Measures liquid levels based on changes in capacitance.
Ultrasonic Level Sensors: Measures liquid levels using ultrasonic waves.
Acceleration Sensors:
Accelerometers: Measures acceleration forces in various directions.
Gyroscopes: Measures orientation and rotational speed.
Inertial Measurement Units (IMUs): Combines accelerometers and gyroscopes for
comprehensive motion sensing.
Biometric Sensors:
Fingerprint Sensors: Authenticates users based on fingerprint patterns.
Iris Scanners: Authenticates users based on iris patterns.
Heart Rate Monitors: Measures heart rate and other cardiovascular parameters.
Environmental Sensors:
Air Quality Sensors: Measures pollutants, humidity, and temperature in the environment.
Weather Sensors: Measures various weather parameters such as temperature, humidity,
pressure, and rainfall.
46
Activity-4
Make led on at pin 13.
To turn on an LED connected to pin 13 on an Arduino Uno, you will need the following
components:
Arduino Uno board
LED (Light Emitting Diode)
Resistor (usually around 220 ohms)
Breadboard
Jumper wires
Here's how to connect the components:
Connect the longer leg (anode) of the LED to pin 13 of the Arduino Uno.
Connect the shorter leg (cathode) of the LED to one leg of the resistor.
Connect the other leg of the resistor to the ground (GND) pin of the Arduino Uno.
Optionally, you can use a breadboard to make the connections more organized.
Ensure that the LED and resistor are properly connected without any loose connections.
Once the components are connected, you can use the following Arduino sketch to turn on the
LED:
arduino
Copy code
void setup() {
// Set pin 13 as an output
pinMode(13, OUTPUT);
}
void loop() {
// Turn on the LED
digitalWrite(13, HIGH);
// Add a delay to keep the LED on for some time
delay(1000); // 1000 milliseconds = 1 second
}
47
This code will set pin 13 as an output in the setup() function. In the loop() function, it will turn
on the LED connected to pin 13 by setting the pin to HIGH using digitalWrite(). Then, it will
add a delay of 1000 milliseconds (1 second) using delay() to keep the LED on for one second.
You can adjust the delay time to change how long the LED stays on.
Source Code:
int led=13;
void setup(){
pinMode(led,OUTPUT);
}
void loop(){
digitalWrite(led,1);
}
Output:
48
Activity-5
Toogle built in LED at pin13.
To toggle the built-in LED connected to pin 13 on an Arduino Uno, you don't need any
additional components besides the Arduino Uno itself, as the board comes with an LED already
connected to pin 13. Here's an explanation of how it works:
Arduino Uno Board: The Arduino Uno is a microcontroller board that comes with a built-in
LED connected to pin 13. Pin 13 is also marked on the board.
LED (Light Emitting Diode): The built-in LED on the Arduino Uno board is a light-emitting
diode that lights up when a voltage is applied to it. LEDs have polarity, meaning they have a
positive (anode) and negative (cathode) terminal. The longer leg of the LED is the positive
(anode) terminal, while the shorter leg is the negative (cathode) terminal.
Microcontroller: The microcontroller on the Arduino Uno board controls the operation of the
LED and other functions of the board. It executes the code uploaded to the board and generates
signals to control the LED.
Here's the Arduino sketch to toggle the built-in LED on pin 13:
void setup() {
// Set pin 13 as an output
pinMode(13, OUTPUT);
}
void loop() {
// Toggle the built-in LED on pin 13
digitalWrite(13, !digitalRead(13));
// Add a delay to control the blinking speed
delay(1000); // 1000 milliseconds = 1 second
}
49
delay(1000) adds a delay of 1000 milliseconds (1 second) between each toggle to control the
blinking speed of the LED.
With this code, the built-in LED on pin 13 will continuously toggle on and off at a 1-second
interval, creating a blinking effect.
Source Code:
int led=13;
void setup(){
pinMode(led,OUTPUT);
}
void loop(){
digitalWrite(led,1);
delay(5000);
digitalWrite(led,0);
delay(5000);
}
Output:
50
Activity-6
Print Your Team members names on serial motion.
To print team members' names on the serial monitor when motion is detected, you will need an
Arduino board, a motion sensor (e.g., PIR sensor), and some jumper wires. Here's how you can
set it up:
Components:
Arduino board (e.g., Arduino Uno)
Motion sensor (e.g., PIR sensor)
Jumper wires
Connections:
Connect the VCC pin of the motion sensor to the 5V pin on the Arduino.
Connect the GND pin of the motion sensor to the GND pin on the Arduino.
Connect the OUT pin of the motion sensor to a digital pin on the Arduino (e.g., pin 2).
Connect the Arduino to your computer via USB cable for serial communication.
Arduino Sketch:
const int motionPin = 2; // Pin connected to the OUT pin of the motion sensor
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(motionPin, INPUT); // Set motionPin as input
}
void loop() {
int motionState = digitalRead(motionPin); // Read motion sensor state
if (motionState == HIGH) { // If motion is detected
Serial.println("Motion detected!");
Serial.println("Team Members:");
Serial.println("- John Doe");
Serial.println("- Jane Smith");
Serial.println("- Bob Johnson");
Serial.println(); // Empty line for clarity
delay(1000); // Delay to prevent multiple detections in quick succession
51
}
}
Explanation:
The sketch sets up a motion sensor connected to pin 2. When motion is detected (the sensor
output goes HIGH), it prints a message to the serial monitor along with the names of team
members.
The delay(1000) function is used to prevent multiple detections in quick succession, providing a
debounce effect.
Make sure to adjust the pin numbers and baud rate in the sketch according to your specific
setup. Also, replace "John Doe", "Jane Smith", and "Bob Johnson" with the names of your team
members.
Source Code:
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println("Jyothi");
Serial.println("Likitha");
Serial.println("Varshini");
Serial.println("Muskaan");
Serial.println("Srujana");
}
Output:
52
Activity-7
Make LED on & off Based up on input
To control an LED based on an input signal, such as a button press, you'll need an Arduino
board, an LED, a resistor to limit the current through the LED, a pushbutton or switch, and
some jumper wires. Here's how you can set it up:
Components:
Arduino board (e.g., Arduino Uno)
LED (any color)
Resistor (around 220 ohms is typical)
Pushbutton or switch
Breadboard
Jumper wire
Connections:
Connect one leg of the pushbutton or switch to a digital pin on the Arduino (e.g., pin 2).
Connect the other leg of the pushbutton or switch to the ground (GND) pin on the Arduino.
Connect the anode (longer leg) of the LED to a current-limiting resistor (220 ohms), and
connect the other end of the resistor to a digital pin on the Arduino (e.g., pin 13).
Connect the cathode (shorter leg) of the LED to the ground (GND) pin on the Arduino.
Optionally, you can use a breadboard to make the connections more organized.
53
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
}
Explanation:
The sketch sets up a pushbutton connected to pin 2 and an LED connected to pin 13.
The pushbutton is configured with the internal pull-up resistor using pinMode(buttonPin,
INPUT_PULLUP). When the button is not pressed, the input pin will read HIGH due to the
pull-up resistor. When the button is pressed, the input pin will read LOW.
In the loop() function, it continuously reads the state of the pushbutton using
digitalRead(buttonPin). If the button is pressed (buttonState is LOW), it turns on the LED by
setting the ledPin to HIGH. Otherwise, it turns off the LED by setting the ledPin to LOW.
This setup allows you to control the LED's state by pressing and releasing the pushbutton.
When the button is pressed, the LED turns on, and when it's released, the LED turns off.
Source Code:
nt led=13;
void setup(){
pinMode(led,OUTPUT);
Serial.begin(9600);
}
void loop(){
while(Serial.available()){
String s=Serial.readString();
if (s=="on"){
digitalWrite(led,1);
}
else if (s=="off"){
digitalWrite(led,0);
}
}
Output:
54
On Off
55
Activity-8
Write a program for IR Sensor and satisfy the Condition.
To create a program for an IR (Infrared) sensor that satisfies a condition, let's design a simple
example where an LED turns on when the IR sensor detects an object within its range. For this
project, you'll need the following components:
Components:
Arduino board (e.g., Arduino Uno)
IR sensor module (e.g., TCRT5000)
LED
Resistor (around 220 ohms)
Breadboard
Jumper wires
Connections:
Connect the VCC pin of the IR sensor to the 5V pin on the Arduino.
Connect the GND pin of the IR sensor to the GND pin on the Arduino.
Connect the OUT pin of the IR sensor to a digital pin on the Arduino (e.g., pin 2).
Connect the anode (longer leg) of the LED to a current-limiting resistor (220 ohms), and
connect the other end of the resistor to a digital pin on the Arduino (e.g., pin 13).
Connect the cathode (shorter leg) of the LED to the GND pin on the Arduino.
Optionally, you can use a breadboard to make the connections more organized.
const int irSensorPin = 2; // Pin connected to the IR sensor
const int ledPin = 13; // Pin connected to the LED
void setup() {
pinMode(irSensorPin, INPUT); // Set irSensorPin as input
pinMode(ledPin, OUTPUT); // Set ledPin as output
}
void loop() {
int irSensorState = digitalRead(irSensorPin); // Read the state of the IR sensor
56
57
Output:
58
Activity-9
Write a program for Gas Sensor and satisfy the Condition.
To create a program for a gas sensor that satisfies a condition, let's design a simple example
where an LED turns on when the gas sensor detects a certain level of gas concentration. For
this project, you'll need the following components:
Components:
Arduino board (e.g., Arduino Uno)
Gas sensor module (e.g., MQ-2)
LED
Resistor (around 220 ohms)
Breadboard
Jumper wires
Connections:
Connect the VCC pin of the gas sensor to the 5V pin on the Arduino.
Connect the GND pin of the gas sensor to the GND pin on the Arduino.
Connect the OUT pin of the gas sensor to an analog pin on the Arduino (e.g., A0).
Connect the anode (longer leg) of the LED to a current-limiting resistor (220 ohms), and
connect the other end of the resistor to a digital pin on the Arduino (e.g., pin 13).
Connect the cathode (shorter leg) of the LED to the GND pin on the Arduino.
Optionally, you can use a breadboard to make the connections more organized.
59
60
Serial.println("gas detected");
}
else{
Serial.println("gas not detected");
}
}
Output:
61
Activity-10
Write a program for LDR Sensor and satisfy the Condition.
To create a program for an LDR (Light Dependent Resistor) sensor that satisfies a condition,
let's design a simple example where an LED turns on when the light level detected by the LDR
sensor falls below a certain threshold. For this project, you'll need the following components:
Components:
Arduino board (e.g., Arduino Uno)
LDR sensor module
Resistor (around 10k ohms)
LED
Resistor (around 220 ohms)
Breadboard
Jumper wires
Connections:
Connect one leg of the LDR sensor to the 5V pin on the Arduino.
Connect the other leg of the LDR sensor to one leg of a resistor (10k ohms).
Connect the other leg of the resistor to the A0 pin on the Arduino.
Connect the anode (longer leg) of the LED to a current-limiting resistor (220 ohms), and
connect the other end of the resistor to a digital pin on the Arduino (e.g., pin 13).
Connect the cathode (shorter leg) of the LED to the GND pin on the Arduino.
Optionally, you can use a breadboard to make the connections more organized.
const int ldrPin = A0; // Pin connected to the LDR sensor
const int ledPin = 13; // Pin connected to the LED
void setup() {
pinMode(ldrPin, INPUT); // Set ldrPin as input
pinMode(ledPin, OUTPUT); // Set ledPin as output
}
void loop() {
int ldrValue = analogRead(ldrPin); // Read the value from the LDR sensor
62
if (ldrValue < 300) { // If light level is below a threshold (adjust threshold as needed)
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
delay(1000); // Delay for stability
}
Explanation:
The sketch sets up an LDR sensor connected to analog pin A0 and an LED connected to pin 13.
The LDR sensor's OUT pin is connected to analog pin A0 and is configured as an input.
In the loop() function, it continuously reads the value from the LDR sensor using
analogRead(ldrPin). The value represents the light level detected by the LDR sensor.
If the light level falls below a certain threshold (in this example, 300), it turns on the LED by
setting the ledPin to HIGH. Otherwise, it turns off the LED by setting the ledPin to LOW.
Adjust the threshold value according to the sensitivity of your LDR sensor and the desired level
of detection.
This setup allows you to control the LED based on the light level detected by the LDR sensor.
When the light level falls below the threshold, the LED turns on, and when it rises above the
threshold, the LED turns off.
Source Code:
int ldr=3;
void setup(){
pinMode(ldr,INPUT);
Serial.begin(9600);
}
void loop(){
int g=digitalRead(ldr);
Serial.println(g);
if(g==0){
Serial.println("light detected");
}
else {
63
Serial.println("darkness detected");
}
}
OutPut:
64
Activity-11
Write a program for Alcohol Sensor and satisfy the Condition.
To create a program for an alcohol sensor that satisfies a condition, let's design a simple
example where an LED turns on when the alcohol sensor detects a certain level of alcohol
vapor. For this project, you'll need the following components:
Components:
Arduino board (e.g., Arduino Uno)
Alcohol sensor module (e.g., MQ-3)
LED
Resistor (around 220 ohms)
Breadboard
Jumper wires
Connections:
Connect the VCC pin of the alcohol sensor to the 5V pin on the Arduino.
Connect the GND pin of the alcohol sensor to the GND pin on the Arduino.
Connect the OUT pin of the alcohol sensor to an analog pin on the Arduino (e.g., A0).
Connect the anode (longer leg) of the LED to a current-limiting resistor (220 ohms), and
connect the other end of the resistor to a digital pin on the Arduino (e.g., pin 13).
Connect the cathode (shorter leg) of the LED to the GND pin on the Arduino.
Optionally, you can use a breadboard to make the connections more organized.
const int alcoholSensorPin = A0; // Pin connected to the alcohol sensor
const int ledPin = 13; // Pin connected to the LED
void setup() {
pinMode(alcoholSensorPin, INPUT); // Set alcoholSensorPin as input
pinMode(ledPin, OUTPUT); // Set ledPin as output
}
void loop() {
int alcoholSensorValue = analogRead(alcoholSensorPin); // Read the value from the alcohol
sensor
65
66
if(g>threshold){
Serial.println("Alcohol Detected");
}
else{
Serial.println("Alcohol not Detected");
}
Output:
67
Activity-12
Write a program for Soil Moisture Sensor.
Make sure you have selected the correct board (NodeMCU) and port in the Arduino IDE before
uploading the code.
Components required:
NodeMCU (ESP8266)
Soil moisture sensor
LED
Resistor (220 ohms - for LED)
Jumper wires
Connections:
Connect the soil moisture sensor to the analog pin A0 of NodeMCU.
Connect the LED to digital pin D1 of NodeMCU via a resistor.
Connect the ground (GND) of NodeMCU to the ground (GND) of the soil moisture sensor and
LED.
Connect the 3.3V or 5V pin of NodeMCU to the VCC pin of the soil moisture sensor and the
anode (longer leg) of the LED.
This code continuously reads the soil moisture level and prints it to the serial monitor. It then
checks the moisture level and turns on the LED if the soil is dry, otherwise, it turns off the LED.
Adjust the threshold value (500 in this case) according to your sensor and soil conditions
Here's a simple program that reads the soil moisture level and controls an LED based on the
moisture level:
// Define the pin connections
#define SOIL_MOISTURE_PIN A0 // Analog pin for soil moisture sensor
#define LED_PIN D1 // Digital pin for LED
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(SOIL_MOISTURE_PIN, INPUT); // Set soil moisture pin as input
pinMode(LED_PIN, OUTPUT); // Set LED pin as output
}
void loop() {
68
69
}
}
Output:
Detected
Not Detected
70
Activity-13
Write a program for DHT level and read humidity and temperature values.
To create a program for reading humidity and temperature values using a DHT sensor, you'll
need an Arduino board, a DHT sensor (such as DHT11 or DHT22), and some jumper wires for
connections. Here's a step-by-step guide including the program, components, and connections:
Components:
Arduino board (e.g., Arduino Uno)
DHT sensor (DHT11, DHT22, etc.)
Jumper wires
Connections:
Connect the DHT sensor to the Arduino board as follows:
DHT sensor VCC pin to Arduino 5V pin
DHT sensor GND pin to Arduino GND pin
DHT sensor data pin to a digital pin on the Arduino (for example, pin 2)
Program (Arduino sketch):
#include <DHT.h>
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11 sensor type
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000); // Wait for 2 seconds between measurements
float humidity = dht.readHumidity(); // Read humidity value
float temperatureC = dht.readTemperature(); // Read temperature in Celsius
//float temperatureF = dht.readTemperature(true); // Read temperature in Fahrenheit
// Check if any reads failed and exit early (to try again)
71
if (isnan(humidity) || isnan(temperatureC)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print humidity and temperature values to serial monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
//Serial.print("Temperature: ");
//Serial.print(temperatureF);
//Serial.println(" °F");
}
Instructions:
Connect the DHT sensor to the Arduino board as described above.
Open the Arduino IDE on your computer.
Copy the provided Arduino sketch into the Arduino IDE.
Upload the sketch to your Arduino board.
Open the serial monitor in the Arduino IDE to view the humidity and temperature readings.
This program initializes communication with the DHT sensor, reads humidity and temperature
values, and prints them to the serial monitor every 2 seconds. You can adjust the delay time or
add further functionality as per your requirements.
SourceCode:
#include<DHT.h>
DHT dht(D1,DHT11);
void setup(){
Serial.begin(9600);
dht.begin();
}
72
void loop(){
float h=dht.readHumidity();
float t=dht.readTemperature();
if(isnan(h)||isnan(t)){
return;
}
Serial.println("Humidity=");
Serial.println(h);
Serial.println("temperature=");
Serial.println(t);
}
Output:
73
Activity-14
Write a program to Rotate servo motor 0 to 90 degrees.
To rotate a servo motor from 0 to 90 degrees using an Arduino, you'll need an Arduino board, a
servo motor, and some jumper wires for connections. Here's a step-by-step guide including the
program, components, and connections:
Components:
Arduino board (e.g., Arduino Uno)
Servo motor
Jumper wires
Connections:
Connect the servo motor to the Arduino board as follows:
Servo motor signal wire (usually orange or yellow) to digital pin 9 on the Arduino
Servo motor power wire (usually red) to the Arduino 5V pin
Servo motor ground wire (usually brown or black) to any GND pin on the Arduino
Program (Arduino sketch):
#include <Servo.h>
Servo servoMotor; // Create a servo object to control the servo motor
void setup() {
servoMotor.attach(9); // Attach the servo to digital pin 9
}
void loop() {
for (int angle = 0; angle <= 90; angle += 1) { // Rotate servo from 0 to 90 degrees
servoMotor.write(angle); // Set servo position
delay(15); // Delay to allow the servo to reach the position
}
}
Instructions:
Connect the servo motor to the Arduino board as described above.
Open the Arduino IDE on your computer.
Copy the provided Arduino sketch into the Arduino IDE.
74
75
Activity-15
Write a program for ultra sonic sensor and print the distance
To create a program for an ultrasonic sensor to measure distance and print the result using an
Arduino board, you'll need an Arduino board, an ultrasonic sensor (such as the HC-SR04), and
some jumper wires for connections. Here's a step-by-step guide including the program,
components, and connections:
Components:
Arduino board (e.g., Arduino Uno)
Ultrasonic sensor (e.g., HC-SR04)
Jumper wires
Connections:
Connect the ultrasonic sensor to the Arduino board as follows:
Ultrasonic sensor VCC pin to Arduino 5V pin
Ultrasonic sensor GND pin to Arduino GND pin
Ultrasonic sensor TRIG pin to digital pin 2 on the Arduino
Ultrasonic sensor ECHO pin to digital pin 3 on the Arduino
Program (Arduino sketch):
#define TRIG_PIN 2 // Digital pin connected to the TRIG pin of the ultrasonic sensor
#define ECHO_PIN 3 // Digital pin connected to the ECHO pin of the ultrasonic sensor
void setup() {
Serial.begin(9600); // Initialize serial communication for printing distance
pinMode(TRIG_PIN, OUTPUT); // Set TRIG_PIN as an output
pinMode(ECHO_PIN, INPUT); // Set ECHO_PIN as an input
}
void loop() {
digitalWrite(TRIG_PIN, LOW); // Set TRIG_PIN low for 2 microseconds to ensure stability
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); // Send a 10 microsecond pulse to the TRIG_PIN
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
76
77
digitalWrite(trig,1);
delayMicroseconds(10);
digitalWrite(trig,0);
float duration=pulseIn(echo,1);
duration=duration/2;
float distance=(0.034)*duration;
Serial.println(distance);
}
Output:
78
Activity-16
Create an activity how to connect wifi with Node MCU.
To connect a NodeMCU to Wi-Fi, you don't need any additional components beyond the
NodeMCU itself. NodeMCU boards come with built-in Wi-Fi capabilities, allowing you to
connect them directly to your wireless network. Here's a step-by-step guide:
Components:
NodeMCU board (or any ESP8266-based development board)
Steps:
1. Connect NodeMCU to Computer:
Use a USB cable to connect your NodeMCU board to your computer.
2. Install ESP8266 Board in Arduino IDE:
Open Arduino IDE.
Go to "File" > "Preferences".
In the "Additional Board Manager URLs" field, add this URL:
http://arduino.esp8266.com/stable/package_esp8266com_index.json.
Click "OK" to close the preferences window.
Go to "Tools" > "Board" > "Boards Manager..."
Type "esp8266" in the search box and install the "esp8266" board package.
3. Select the Correct Board and Port:
Go to "Tools" > "Board" and select "NodeMCU 1.0 (ESP-12E Module)".
Go to "Tools" > "Port" and select the COM port to which your NodeMCU is connected.
4. Write the Wi-Fi Connection Sketch:
Open a new sketch in Arduino IDE.
#include <ESP8266WiFi.h>
const char* ssid = "YourWiFiSSID"; // Your Wi-Fi network SSID
const char* password = "YourWiFiPassword"; // Your Wi-Fi network password
void setup() {
Serial.begin(115200);
delay(10);
// Connect to Wi-Fi
79
Serial.println();
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, password);
80
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED){
Serial.print(".");
delay(1500);
}
Serial.println("wifi connected");
}
void loop(){
}
Output:
81
Activity-17
How to create think speak account.
ThingSpeak is an IoT platform that allows you to collect, analyze, and visualize data from IoT
devices. Here are the steps:
Step 1: Visit ThingSpeak Website
82
Step 4: Verify EmailCheck your email inbox for a verification email from ThingSpeak. Click on
the verification link in the email to verify your account.
Step 5: Login
Once your account is verified, return to the ThingSpeak website and log in with your
credentials.
Step 6: Complete Signup Process
After logging in, you may be prompted to provide additional information, such as your name
and country. Fill out the required fields and click on the "Complete Sign Up" button.
Step 8: Dashboard
You will be directed to your ThingSpeak Dashboard, where you can create and manage
channels, visualize data, and perform other IoT-related tasks.
83
That's it! You have successfully created a ThingSpeak account. You can now start using
ThingSpeak to collect and analyze data from your IoT devices
84
Activity-18
Create an activity toUpload ultra sonic sensor data to thing speak IOT cloud.
To upload ultrasonic sensor data to ThingSpeak IoT cloud, you'll need a device such as an
Arduino or a NodeMCU board, an ultrasonic sensor, and an active internet connection. Here's
a general outline of the steps involved:
Set up ThingSpeak Channel:
Log in to your ThingSpeak account.
Create a new channel by navigating to "Channels" > "My Channels" and clicking on "New
Channel".
Define fields for your ultrasonic sensor data (e.g., distance in centimeters).
Save your channel, and note down your Channel ID and Write API Key.
Connect Ultrasonic Sensor to Arduino/NodeMCU:
Connect the VCC pin of the ultrasonic sensor to the 5V pin of your Arduino/NodeMCU.
Connect the GND pin of the ultrasonic sensor to the GND pin of your Arduino/NodeMCU.
Connect the TRIG pin of the ultrasonic sensor to a digital pin (e.g., D2) of your
Arduino/NodeMCU.
Connect the ECHO pin of the ultrasonic sensor to another digital pin (e.g., D3) of your
Arduino/NodeMCU.
Write Arduino/NodeMCU Sketch:
Write a sketch in the Arduino IDE that reads the distance from the ultrasonic sensor and sends
it to ThingSpeak.
Use the ThingSpeak library or make HTTP requests to the ThingSpeak API to update the
channel with the sensor data.
Here's a basic example sketch for Arduino using the ThingSpeak library:
#include <ESP8266WiFi.h>
#include <ThingSpeak.h>
const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";
const char* apiKey = "YourAPIKey";
const int trigPin = D2;
const int echoPin = D3;
WiFiClient client;
85
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
WiFi.begin(ssid, password);
ThingSpeak.begin(client);
}
void loop() {
long duration, distance_cm;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance_cm = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.println(distance_cm);
ThingSpeak.setField(1, distance_cm);
ThingSpeak.writeFields(YOUR_CHANNEL_ID, apiKey);
delay(5000); // Wait for 5 seconds before sending next data point
}
Replace "YourWiFiSSID", "YourWiFiPassword", "YourAPIKey", and "YOUR_CHANNEL_ID"
with your actual Wi-Fi credentials, ThingSpeak API key, and ThingSpeak channel ID,
respectively.
Upload Sketch to Arduino/NodeMCU:
Connect your Arduino/NodeMCU board to your computer via USB.
Open the Arduino IDE, select the correct board and port, and upload the sketch to your board.
Monitor Data on ThingSpeak:
86
After uploading the sketch, open your ThingSpeak channel and navigate to "Charts" to visualize
the data being sent by your device.
That's it! Your ultrasonic sensor data should now be uploaded to ThingSpeak IoT cloud at
regular intervals. Adjust the delay in the sketch according to your desired data update
frequency.
Source Code:
#include<ESP8266WiFi.h>
#include<ThingSpeak.h>
char*ssid="Muskaan";
char*password="musk@@n$h@fi";
WiFiClient client;
int channel=2427750;
char* apikey="XQXGTWN1T1YODR0N";
int trig=D0;
int echo=D2;
void setup(){
pinMode(trig,OUTPUT);
pinMode(echo, INPUT);
Serial.begin(9600);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while(WiFi.status()!=WL_CONNECTED){
Serial.print(".");
delay(500);
}
Serial.println("wifi connected");
ThingSpeak.begin(client);
}
void loop(){
digitalWrite(trig,0);
delayMicroseconds(2);
87
digitalWrite(trig,1);
delayMicroseconds(10);
digitalWrite(trig,0);
float duration=pulseIn(echo,1);
duration=duration/2;
float distance=(0.034)*duration;
Serial.println(distance);
ThingSpeak.setField(1,distance);
int status=ThingSpeak.writeFields(channel,apikey);
if(status>20){
Serial.println("data stored");
}
else {
Serial.println("data failure");
}
}
Output:
88
89
Activity-19
Create an Activity how to See uploaded data in mobile app.
To view the data uploaded to ThingSpeak on a mobile app, you can use the official ThingSpeak
app available for both iOS and Android devices. Here's how to do it:
For iOS:
Download the ThingSpeak App:
Open the App Store on your iOS device.
Search for "ThingSpeak" and download the official ThingSpeak app developed by MathWorks.
Log in to Your ThingSpeak Account:
Open the ThingSpeak app on your iOS device.
Log in to your ThingSpeak account using your username and password.
View Your Channels:
Once logged in, you will see a list of your channels.
Tap on the channel that you want to view.
View Data:
In the channel details view, you can see the data plotted on charts.
You can customize the time range and view the data in different chart types.
For Android:
Download the ThingSpeak App:
Open the Google Play Store on your Android device.
Search for "ThingSpeak" and download the official ThingSpeak app developed by MathWorks.
Log in to Your ThingSpeak Account:
Open the ThingSpeak app on your Android device.
Log in to your ThingSpeak account using your username and password.
View Your Channels:
Once logged in, you will see a list of your channels.
Tap on the channel that you want to view.
View Data:
In the channel details view, you can see the data plotted on charts.
90
You can customize the time range and view the data in different chart types.
By following these steps, you can easily view the data uploaded to ThingSpeak on your mobile
device using the official ThingSpeak app. You can monitor your IoT devices and visualize data
from anywhere with an internet connection.
Output:
91
Activity-20
Create an application for Activating virtual lap on &off using Http request .
To activate and deactivate a virtual lamp using HTTP requests with ThingSpeak, you can utilize
the ThingSpeak React app feature to trigger actions based on data updates. Here's a step-by-
step guide:
Set Up ThingSpeak Channel:
Log in to your ThingSpeak account.
Create a new channel by navigating to "Channels" > "My Channels" and clicking on "New
Channel".
Define fields for your virtual lamp state (e.g., lamp_state with values 0 for off and 1 for on).
Save your channel, and note down your Channel ID and Write API Key.
Create a React App on ThingSpeak:
In your ThingSpeak account, navigate to "Apps" > "React".
Click on "New React" to create a new React app.
Configure your React app to trigger actions based on changes to your lamp_state field:
Select your ThingSpeak channel and field (lamp_state).
Define a React with the following conditions:
If lamp_state = 1 (on), trigger an action to turn on the virtual lamp.
If lamp_state = 0 (off), trigger an action to turn off the virtual
lamp.Save your React app.
Send HTTP Requests to Update lamp_state:
Use any HTTP client (e.g., curl, Postman, browser) to send HTTP requests to update the
lamp_state field on your ThingSpeak channel.
You'll need to make a HTTP GET or POST request to the ThingSpeak API endpoint with your
Channel ID and Write API Key, along with the new lamp_state value.
Example using curl:
bash
Copy code
# Turn on the virtual lamp (set lamp_state to 1)
curl -X POST 'https://api.thingspeak.com/update' \
-d 'api_key=YOUR_API_KEY' \
92
-d 'field1=1'
# Turn off the virtual lamp (set lamp_state to 0)
curl -X POST 'https://api.thingspeak.com/update' \
-d 'api_key=YOUR_API_KEY' \
-d 'field1=0'
Replace YOUR_API_KEY with your ThingSpeak Write API Key.
Configure Actions (Optional):
Depending on your setup, you can configure the actions triggered by the React app to control
your virtual lamp. This could involve integrating with external devices (e.g., smart bulbs) or
services (e.g., home automation platforms).
With this setup, you can use HTTP requests to update the lamp_state field on your ThingSpeak
channel, and the React app will trigger actions based on changes to this field, effectively
turning your virtual lamp on or off.
Output:
ON
93
Activity-21
Create an application to turn on and turn off the light using Alexa.
To create and deploy this Alexa skill, you'll need to follow these steps:
Configure the Alexa skill: Go to the Alexa Developer Console
(developer.amazon.com/alexa/console/ask) and create a new skill.
Configure the skill's invocation name, intents, and endpoint (select AWS Lambda and choose
the Lambda function you created).
94
Set up an AWS Lambda function: Create a new AWS Lambda function using the Node.js
runtime. Copy and paste the code above into the Lambda function code editor.
Source Code:
# -*- coding: utf-8 -*-
# This sample demonstrates handling intents from an Alexa skill using the Alexa Skills Kit SDK
for Python.
# Please visit https://alexa.design/cookbook for additional examples on implementing slots,
dialog management,
# session persistence, api calls, and more.
# This sample is built using the handler classes approach in skill builder.
import logging
import ask_sdk_core.utils as ask_utils
import urllib3
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.dispatch_components import AbstractExceptionHandler
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response
logger = logging.getLogger( name )
logger.setLevel(logging.INFO)
class BulbOnIntentHandler(AbstractRequestHandler):
95
http.request('GET','https://api.thingspeak.com/update?api_key=Q2Q9O9TYZOFC359R&field1
=0')
speak_output = "bulb is switch off"
return (
handler_input.response_builder
96
.speak(speak_output)
.set_should_end_session(False)
# .ask("add a reprompt if you want to keep the session open for the user to respond")
.response
)
class LaunchRequestHandler(AbstractRequestHandler):
"""Handler for Skill Launch."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("LaunchRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Welcome, you can say Hello or Help. Which would you like to try?"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class HelloWorldIntentHandler(AbstractRequestHandler):
"""Handler for Hello World Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("HelloWorldIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Hello World!"
return (
handler_input.response_builder
.speak(speak_output)
97
# .ask("add a reprompt if you want to keep the session open for the user to respond")
.response
)
class HelpIntentHandler(AbstractRequestHandler):
"""Handler for Help Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("AMAZON.HelpIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "You can say hello to me! How can I help?"
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
class CancelOrStopIntentHandler(AbstractRequestHandler):
"""Single handler for Cancel and Stop Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return (ask_utils.is_intent_name("AMAZON.CancelIntent")(handler_input) or
ask_utils.is_intent_name("AMAZON.StopIntent")(handler_input))
98
.response
)
class FallbackIntentHandler(AbstractRequestHandler):
"""Single handler for Fallback Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("AMAZON.FallbackIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
logger.info("In FallbackIntentHandler")
speech = "Hmm, I'm not sure. You can say Hello or Help. What would you like to do?"
reprompt = "I didn't catch that. What can I help you with?"
return handler_input.response_builder.speak(speech).ask(reprompt).response
class SessionEndedRequestHandler(AbstractRequestHandler):
"""Handler for Session End."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_request_type("SessionEndedRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
# Any cleanup logic goes here.
return handler_input.response_builder.response
class IntentReflectorHandler(AbstractRequestHandler):
"""The intent reflector is used for interaction model testing and debugging.
It will simply repeat the intent the user said. You can create custom handlers
for your intents by defining them above, then also adding them to the request
handler chain below.
"""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
99
return ask_utils.is_request_type("IntentRequest")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
intent_name = ask_utils.get_intent_name(handler_input)
speak_output = "You just triggered " + intent_name + "."
return (
handler_input.response_builder
.speak(speak_output)
# .ask("add a reprompt if you want to keep the session open for the user to respond")
.response
)
class CatchAllExceptionHandler(AbstractExceptionHandler):
"""Generic error handling to capture any syntax or routing errors. If you receive an error
stating the request handler chain is not found, you have not implemented a handler for
the intent being invoked or included it in the skill builder below.
"""
def can_handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> bool
return True
def handle(self, handler_input, exception):
# type: (HandlerInput, Exception) -> Response
logger.error(exception, exc_info=True)
speak_output = "Sorry, I had trouble doing what you asked. Please try again."
return (
handler_input.response_builder
.speak(speak_output)
.ask(speak_output)
.response
)
100
# The SkillBuilder object acts as the entry point for your skill, routing all request and response
# payloads to the handlers above. Make sure any new handlers or interceptors you've
# defined are included below. The order matters - they're processed top to bottom.
sb = SkillBuilder()
sb.add_request_handler(LaunchRequestHandler())
sb.add_request_handler(HelloWorldIntentHandler())
sb.add_request_handler(HelpIntentHandler())
sb.add_request_handler(BulbOnIntentHandler())
sb.add_request_handler(BulbOffIntentHandler())
sb.add_request_handler(SessionEndedRequestHandler())
sb.add_request_handler(IntentReflectorHandler()) # make sure IntentReflectorHandler is last
so it doesn't override your custom intent handlers
sb.add_exception_handler(CatchAllExceptionHandler())
lambda_handler = sb.lambda_handler()
Test the skill: Use the Test tab in the Alexa Developer Console to test your skill with sample
utterances.
Publish the skill (optional): Once you're satisfied with your skill, you can submit it for
certification and publish it to the Alexa Skills Store.
After completing these steps, you should be able to interact with your Alexa skill by saying
"Alexa, open [your skill's invocation name]" and then saying "hello" to trigger the HelloIntent.
Alexa will respond with "Hello! Nice to meet you!".
Output:
101
ON:
OFF:
102
Hackaton Project :
Abstract:
The increasing pollution of water bodies worldwide poses a significant threat to the environment and human
health. One major contributor to this pollution is garbage, including plastics, debris, and other waste materials,
which accumulate in lakes, rivers, and oceans. Traditional methods of garbage collection and cleaning are often
inefficient, labor-intensive, and costly.To address this issue, we present ChatWater, a novel approach to cleaning
garbage from water bodies using smart technology. ChatWater employs a combination of robotics, artificial
intelligence (AI), and remote sensing to detect, collect, and manage garbage effectively.The system consists of
autonomous surface vehicles equipped with sensors and cameras, capable of identifying and classifying various
types of garbage in real-time. These vehicles communicate with a central control system powered by AI
algorithms, which analyze data from the sensors to optimize garbage collection routes and strategies.
Additionally, ChatWater utilizes machine learning models to continuously improve its garbage detection and
classification capabilities, adapting to different environments and types of debris over time. The system can also
be integrated with existing water management infrastructure, providing a seamless solution for municipalities,
environmental agencies, and other stakeholders.By combining cutting-edge technology with environmental
stewardship, ChatWater offers a scalable and sustainable solution to the growing problem of water pollution.
Through ongoing research, development, and collaboration, we aim to make our water bodies cleaner and
healthier for future generations. The system consists of autonomous surface vehicles equipped with sensors and
cameras, capable of identifying and classifying various types of garbage in real-time. These vehicles
communicate with a central control system powered by AI algorithms, which analyze data from the sensors to
optimize garbage collection routes and strategiesintelligence (AI), and remote sensing to detect, collect, and
manage garbage effectively.The system consists of autonomous surface vehicles equipped with sensors and
cameras, capable of identifying and classifying various types of garbage in real-time. These vehicles
communicate with a central control system powered by AI algorithms, which analyze data from the sensors to
optimize garbage collection routes and strategies.
Introduction:
Water pollution caused by garbage and waste materials has become a pressing global concern, adversely
affecting ecosystems, biodiversity, and human health. In rivers, lakes, and oceans, accumulating debris, including
plastics, metals, and other pollutants, poses significant challenges for environmental conservation and sustainable
development. Traditional methods of garbage collection and cleaning are often inadequate, inefficient, and
costly, necessitating innovative solutions to address this critical issue.
In response to this challenge, our project introduces a novel approach to water garbage cleaning: the ChatWater
system. Leveraging advancements in robotics, artificial intelligence (AI), and remote sensing technologies,
ChatWater aims to revolutionize the way we detect, collect, and manage garbage in water bodies. By combining
smart technology with environmental stewardship, ChatWater offers a scalable, efficient, and sustainable
solution to combat water pollution.
This introduction sets the stage for discussing the urgent need for effective water garbage cleaning solutions and
highlights the potential of the ChatWater system to address this global challenge. Through a multidisciplinary
approach that integrates engineering, environmental science, and computer science, we aim to contribute to the
preservation and restoration of our water ecosystems for the benefit of present and future generations.
Architectural Diagram:
Iot Sensors:
For a project that integrates AI and IoT technologies into a virtual driving simulator to teach and
enhance driving skills, a variety of IoT sensors and devices are necessary to accurately capture real-
time data about the user’s interactions and environment. Here are some essential IoT sensors and
devices that would typically be required:
1. Camera Sensors: High-resolution cameras are mounted on the surface vehicles or drones to capture
images and videos of the water surface. These cameras provide visual data that is essential for
identifying and classifying different types of garbage, such as plastics, debris, and organic materials.
2. LiDAR (Light Detection and Ranging): LiDAR sensors use laser pulses to measure distances and
create detailed 3D maps of the surrounding environment. In water garbage cleaner projects, LiDAR
sensors are used to accurately detect the location and depth of submerged garbage and obstacles,
enabling the navigation of autonomous vehicles.
3. Sonar Sensors: Sonar sensors emit sound waves that travel through water and bounce off objects,
providing information about their distance and size. Sonar sensors are useful for detecting submerged
garbage, underwater obstacles, and the contours of the water body's bottom.
4. Infrared (IR) Sensors: IR sensors detect infrared radiation emitted by objects, allowing them to
differentiate between various materials based on their thermal properties. IR sensors can help identify
organic materials, such as floating vegetation, algae, and oil slicks, amidst the garbage.
5. GPS (Global Positioning System): GPS sensors provide accurate location data, enabling precise
navigation and mapping of garbage accumulation areas in water bodies. GPS data is essential for
optimizing garbage collection routes and coordinating multiple autonomous vehicles.
6. Water Quality Sensors: Water quality sensors measure parameters such as pH, dissolved oxygen,
turbidity, and conductivity to assess the environmental health of the water body. Monitoring water
quality helps identify pollution sources and prioritize cleanup efforts.
Role of AioT:
The Internet of Things (IoT) plays a crucial role in enhancing the functionality, efficiency, and effectiveness of
water garbage cleaner projects like ChatWater. Here are some key roles of IoT in such projects:
1. Sensor Integration: IoT enables the integration of various sensors, including cameras, LiDAR, sonar, GPS,
and water quality sensors, into autonomous surface vehicles (ASVs) and other equipment used in the project.
These sensors collect real-time data on garbage accumulation, water quality, environmental conditions, and
vessel operations, providing valuable insights for decision-making and optimization.
2. Data Collection and Monitoring: IoT facilitates the collection, transmission, and storage of large volumes
of sensor data from distributed devices deployed in water bodies. Data on garbage concentration, types of debris,
water quality parameters, and vessel movements are continuously monitored and analyzed to identify patterns,
trends, and anomalies, enabling proactive management of garbage cleaning operations.
3. Remote Control and Monitoring: IoT enables remote control and monitoring of ASVs and other
equipment from a centralized control station or through cloud-based platforms. Operators can remotely command
ASVs to start or stop garbage collection, adjust navigation routes, and respond to changing environmental
conditions in real-time, optimizing operational efficiency and safety.
4. Predictive Maintenance: IoT-enabled sensors can monitor the health and performance of ASVs and
onboard equipment, detecting potential issues or malfunctions before they escalate into costly downtime or
failures. Predictive maintenance algorithms analyze sensor data to identify maintenance needs, schedule repairs,
and prevent unexpected breakdowns, ensuring continuous operation of the garbage cleaning system.
5. Integration with Environmental Monitoring Systems: IoT enables seamless integration with existing
environmental monitoring systems, such as weather stations, water quality monitoring networks, and pollution
tracking platforms. By sharing data and insights across different systems, stakeholders can gain a comprehensive
understanding of water pollution dynamics, facilitate coordinated response efforts, and support evidence-based
decision-making.
6. Enhanced Communication and Collaboration: IoT facilitates communication and collaboration among
stakeholders involved in water garbage cleaner projects, including government agencies, environmental
organizations, research institutions, and local communities. Real-time data sharing, communication channels, and
collaboration platforms enable stakeholders to exchange information, coordinate actions, and mobilize resources
more effectively to address water pollution challenges.
Overall, IoT serves as a foundational technology for water garbage cleaner projects, enabling seamless
connectivity, real-time data insights, predictive analytics, and collaborative decision-making to combat water
pollution and promote environmental sustainability.
Source code:
Arduino IDE:
int counter = 0;
int currentStateCLK;
int previousStateCLK;
int bs1 = 2;
int bs2 = 7;
int bs3 = 8;
int bs4 = 12;
void setup() {
pinMode(bs3, INPUT_PULLUP);
pinMode(bs4, INPUT_PULLUP);
void loop() {
// If the previous and the current state of the inputCLK are different, then a pulse has occurred
if (currentStateCLK != previousStateCLK) {
} else {
// Encoder is rotating clockwise
counter ++;
encdir ="CW";
Serial.println("Moving forward");
}
Serial.print("Direction: ");
Serial.print(encdir);
Serial.print(" -- Value: ");
Serial.println(counter);
}
// Update previousStateCLK with the current state
previousStateCLK = currentStateCLK;
if (digitalRead(bs2) == LOW)
Serial.println("Turned Right");
if (digitalRead(bs3) == LOW)
Serial.println("Front brake applied");
if (digitalRead(bs4) == LOW)
Serial.println("Back brake applied");
}
Python code:
import serial
import pyautogui
import time
while True:
if ser.in_waiting:
line = ser.readline().decode('utf-8').rstrip()
print(line)
The provided Arduino code snippet is designed to manage inputs from a rotary encoder and four bump
switches, outputting related changes to the Serial Monitor for debugging or interface purposes. Here's
a detailed breakdown of the various parts and functionalities of the code:
- > `inputCLK` and `inputDT`: These are the digital pin numbers on the Arduino to which the two
output pins of the rotary encoder are connected. These pins will detect the rotational direction of the
encoder.
- > `counter`: This integer variable is used to keep track of the rotary encoder's position.
- > `currentStateCLK` and `previousStateCLK`: These variables store the current and previous states
of the `inputCLK` pin, respectively, to determine rotation direction.
- > `bs1`, `bs2`, `bs3`, `bs4`: These are the digital pin numbers connected to four bump switches. The
script checks the state of these switches to detect presses.
- > `encdir`: A String variable used to indicate the direction of the encoder's rotation ("CW" for
clockwise, "CCW" for counterclockwise).
Setup Function:
- > The `pinMode` functions set `inputCLK` and `inputDT` as inputs to read the state of the rotary
encoder.
- > The bump switch pins (`bs1`, `bs2`, `bs3`, `bs4`) are also set as inputs but with pull-up resistors
enabled (`INPUT_PULLUP`). This configuration means the default state of these pins is HIGH, and
they go LOW when the switch is pressed.
- > Initializes the Serial connection at a baud rate of 9600 to enable communication over USB to a
computer for debugging.
- > The initial state of `inputCLK` is read and stored in `previousStateCLK`.
Loop Function:
- > At the beginning of each loop iteration, `currentStateCLK` is updated with the current state of the
`inputCLK` pin.
- > It checks if there has been a change in the state of `inputCLK` since the last loop iteration:
- > If a change is detected (indicative of rotary encoder movement), it then checks the state of
`inputDT`.
- > If `inputDT` is different from `currentStateCLK`, it implies counterclockwise rotation,
decrements the `counter`, and sets `encdir` to "CCW".
- > If `inputDT` is the same as `currentStateCLK`, it implies clockwise rotation, increments the
`counter`, and sets `encdir` to "CW".
- > Outputs the direction and current value of `counter` to the Serial Monitor.
- > Updates `previousStateCLK` with the current state for comparison in the next loop iteration.
- > Each bump switch's state is checked:
- > If a switch is pressed (pin reads LOW because of the pull-up resistor configuration), it prints a
corresponding message to the Serial Monitor indicating the action associated with that switch (e.g.,
"Turned Left" for `bs1`).
General Purpose:
- > The code serves as a fundamental example of reading rotary encoder input for determining rotation
direction and magnitude, and detecting button presses using Arduino. It illustrates basic principles of
hardware interaction, conditional logic, and real-time feedback through the Serial Monitor, useful in
robotics, interactive installations, or DIY projects involving manual controls.
The interaction between the Python code, Arduino, and a virtual game involves several steps, which
are outlined below. These steps explain how the Python script receives data from the Arduino and uses
it to control a virtual game through simulated keyboard inputs using `pyautogui`.
1. Arduino Setup: In the Arduino script, sensor data (such as from rotary encoders or bump switches)
is processed, and based on certain conditions or events (e.g., the direction of rotation or switch
activation), the Arduino sends specific strings like "Left", "Right", "Forward", or "Backward" via the
serial port using `Serial.println()`.
2. Serial Communication: The Arduino is connected to a computer via a USB cable. It communicates
with the Python script running on the computer through serial communication. The Arduino script
specifies the COM port and baud rate (9600 in this case), which must match the settings in the Python
script.
1. Serial Initialization: The Python script uses the `serial` library to open a serial connection to the
Arduino. It listens on the specified COM port ('COM8' as defined in the script) at the correct baud rate
(9600).
2. Reading Serial Data: Using an infinite loop (`while True`), the script continuously checks if new
data is available (`ser.in_waiting > 0`). When data is available, it reads the line using `ser.readline()`,
decodes it from bytes to a UTF-8 string, and strips any extraneous whitespace or newline characters.
1. Interpreting Commands: Depending on the decoded string received from the Arduino (like "Left" or
"Right"), the Python script determines which action to simulate.
2. Simulating Keyboard Input: The `pyautogui` library is used to simulate keyboard presses. In the
provided example, regardless of the specific directional command, `pyautogui.press('space')` is
executed. This could be customized to simulate pressing arrow keys or other keys that correspond to
actions in the game. For example:
- `pyautogui.press('left')` to move left in the game,
- `pyautogui.press('right')` to move right, etc.
Communication Systems: ASVs can be equipped with communication systems, such as VHF radios or
AIS (Automatic Identification System), to communicate with nearby boats. This enables them to signal
their presence, intentions, and movements, ensuring that other vessels are aware of their activities and
can respond accordingly.Navigation Cooperation: ASVs can collaborate with manned or unmanned
boats to optimize navigation and garbage collection operations. By sharing information about garbage
accumulation areas, navigation routes, and potential obstacles, ASVs and boats can work together to
cover larger areas more efficiently.
Safety Protocols: Clear safety protocols should be established for interactions between ASVs and boats
to minimize risks and ensure smooth coordination on the water. This may include designated lanes for
ASVs, speed limits, and rules of priority to govern right-of-way situations.
Remote Monitoring: Real-time monitoring systems can track the movements and activities of ASVs and
boats from a central control station or through satellite communication. This allows operators to oversee
operations, intervene if necessary, and ensure compliance with safety protocols.
Conclusion:
The development of water garbage cleaner projects like water garbage cleaner represents a significant
step forward in combating the pervasive issue of water pollution caused by garbage and waste
materials. Through the integration of advanced sensors, robotics, and artificial intelligence, these
innovative systems offer a promising solution to the challenges posed by accumulating debris in
rivers, lakes, and oceans.
By leveraging cutting-edge technology, water garbage cleaners can detect, identify, and collect various
types of garbage efficiently and effectively. Autonomous surface vehicles equipped with cameras,
LiDAR, sonar, and other sensors enable precise navigation and mapping of garbage accumulation
areas, optimizing cleanup efforts and minimizing environmental impact.
Furthermore, the continuous improvement and adaptation of machine learning algorithms enhance the
system's ability to detect and classify garbage, allowing for greater flexibility and scalability across
different environments and types of debris. Additionally, the integration of water quality sensors
provides valuable insights into the health of water bodies, enabling proactive measures to prevent
pollution and preserve ecosystems.
In conclusion, water garbage cleaner projects offer a holistic approach to addressing water pollution,
combining technological innovation with environmental stewardship. By working collaboratively with
stakeholders, including governments, environmental organizations, and local communities, we can
harness the potential of these systems to protect and restore our precious water resources for future
generations. Through ongoing research, development, and implementation, we can strive towards
cleaner, healthier water bodies and a more sustainable planet.
Certificate: