Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 97

Automatic Solar Panel Cleaning System

Report submitted in partial fulfillment of the requirement for the


degree of

B. Tech.
In

Electronics & Communication Engineering


Under the Supervision of
Mr. Ankit Jain
(Associate Professor)

By
Abhishek Gupta (2001640310001)
Ankita Singh (2001640310018)
Avinash Singh (2001640310029)

Srishti Vishwakarma (2001640310103)

Pranveer Singh Institute of Technology, Kanpur


Dr. A P J A K Technical University
Lucknow

April 2024
Automatic Solar Panel Cleaning System

Report submitted in partial fulfillment of the requirement for the


degree of

B. Tech.
In

Electronics & Communication Engineering


Under the Supervision of
Mr. Ankit Jain
(Associate Professor)

By

Abhishek Gupta (2001640310001)


Ankita Singh (2001640310018)
Avinash Singh (2001640310029)
Srishti Vishwakarma (2001640310103)

Pranveer Singh Institute of Technology, Kanpur


Dr. A P J A K Technical University
Lucknow

April 2024
DECLARATION

This is to certify that Report entitled “Automatic Solar Panel Cleaning


System” which is submitted by me in partial fulfillment of the requirement
for the award of degree B. Tech. in Electronics & Communication
Engineering to PSIT College of Engineering, Kanpur Dr. A.P.J.A.K
Technical University, Lucknow comprises only my own work and due
acknowledgement has been made in the text to all other material used.

Date: Name of Student:

Abhishek Gupta

Ankita Singh

Avinash Singh

Srishti Vishwakarma

Approved by:
Dr. Raghvendra Singh

Head & Associate Professor


Electronics & Communication Engineering
PSIT, Kanpur

i
CERTIFICATE

This is to certify that Report entitled “Automatic Solar Panel Cleaning


System” which is submitted by Abhishek Gupta, Ankita Singh, Avinash
Singh and Srishti Vishwakarma in partial fulfillment of the requirement
for the award of degree B. Tech. in Electronics & Communication
Engineering to Pranveer Singh Institute of Technology, Kanpur Dr. A P J
A K Technical University, Lucknow is a record of the candidate own work
carried out by him under my supervision. The matter embodied in this
thesis is original and has not been submitted for the award of any other
degree.

Date: Supervisor Name & Signature

Mr. Ankit Jain


(Associate Professor)
Electronics & Communication Engineering
PSIT, Kanpur

ii
AKNOWLEDGEMENT

It gives us a great sense of pleasure to present the project report undertaken


during B. Tech. Final Year. We owe special debt of gratitude to Mr. Ankit
Jain, Associate Professor, Department of Electronics & Communication
Engineering, PSIT, Kanpur, for his constant support and guidance
throughout the course of our work. His sincerity, thoroughness and
perseverance have been a constant source of inspiration for us.
It is only his cognizant efforts that our endeavors have seen light of the
day. We also take the opportunity to acknowledge the contribution of Dr.
Raghvendra Singh, Head of Department of Electronics &
Communication Engineering, PSIT, Kanpur, for his full support and
assistance during the development of the project.
We also do not like to miss the opportunity to acknowledge the
contribution of all faculty members of the department for their kind
assistance and cooperation during the development of our project. Last
but not the least;
we acknowledge our family & friends for their contribution in the
completion of the project.

Signature: Signature:
Name: Abhishek Gupta Name: Avinash Singh
Roll No.:2001640310001 Roll No.:2001640310029

Signature: Signature:
Name: Ankita Singh Name: Srishti
Roll No.:2001640310018 Vishwakarma
RollNo.:2001640310103

iii
iv
ABSTRACT

An automatic solar panel cleaning system is a crucial innovation designed to enhance the
efficiency and longevity of solar panels. Solar panels, typically installed in large arrays, are
prone to accumulating dust, debris, bird droppings, and other environmental contaminants that
can significantly reduce their energy conversion efficiency. In regions with little rainfall or in
industrial settings, this accumulation can be rapid and substantial. To combat this issue, the
automatic solar panel cleaning system provides a mechanized solution that ensures the panels
remain clean without the need for manual labor.

The system operates based on various mechanisms, often including robotic devices or
automated brushes, coupled with controlled water systems. These cleaning units are generally
programmed to perform cleaning cycles during non-peak solar generating times, such as early
morning or late evening, to avoid disrupting energy production. Some advanced systems are
equipped with sensors that detect the level of dirt accumulation on the panels and initiate
cleaning processes accordingly.

Key components of these systems include motorized brushes or rubber squeegees, fluid
dispensers for water or cleaning solutions, and control units equipped with software that
manages the cleaning schedule and operation based on weather conditions and dirt detection
sensors. The system's design allows for minimal water usage, which is particularly
advantageous in arid areas where water conservation is essential.

Solar energy is one of the most promising sources of renewable energy, and solar panels play a
crucial role in harnessing this energy. However, solar panels tend to accumulate dust, dirt, and
other debris over time, which can significantly reduce their efficiency. Regular cleaning is
necessary to maintain optimal performance and maximize energy generation.

Manual cleaning of solar panels can be time-consuming, labor-intensive, and costly, especially
in large-scale solar installations. To address this challenge, an automatic solar panel cleaning
system using the Internet of Things (IoT) can be implemented. This system combines IoT
technology, sensors, and automation to remotely monitor and clean solar panels efficiently and
effectively.
v
The benefits of implementing an automatic solar panel cleaning system are multifaceted.
Primarily, it maintains or even increases the efficiency of solar panels by ensuring they are
always clean, thus optimizing light absorption. It also reduces the need for human intervention,
decreasing ongoing maintenance costs and enhancing safety by minimizing the risks associated
with manual cleaning. Furthermore, the system extends the operational lifespan of solar panels
by preventing the abrasive effects of dirt and other residues.

With growing costs of electricity and concern for the environmental impact of fossil fuels,
implementation of eco-friendly energy sources like solar power are rising. The main method for
harnessing solar power is with arrays made up of photovoltaic (PV) panels. Accumulation of
dust and debris on even one panel in an array reduces their efficiency in energy generation
considerably and emphasizes the need to keep the panels’ surface as clean as possible. The goal
of our project is to create an automated solar panel cleaner that will address the adverse impact
of soiling on commercial photovoltaic cells. Specifically, we hoped to create a device that
increases the maximum power output of a soiled panel by 10% (recovering the amount of power
lost). Furthermore, autonomous cleaning robots are often only economical on a larger scale due
to both installation costs and the fact that custom-made parts are needed to fit the plant.

Overall, automatic solar panel cleaning systems represent a smart and efficient solution to a
common problem faced in solar energy management, ensuring that solar power remains a viable
and effective energy source for the future.

Index Terms: - Solar Panel, Automated System, Internet of Things, Blynk IOT, Real Time
Clock….

vi
Table of Contents

Declaration.........................................................................................................................I
Certificate.........................................................................................................................II
Acknowledgement..........................................................................................................III
Abstract.............................................................................................................................V
List of Abbreviations......................................................................................................IX
List of Figure....................................................................................................................X
List of Table…..............................................................................................................XI

Chapter INTRODUCTION…...................................................................................1-3

1.1 Introduction.............................................................................................1-2

1.2 Motivation..................................................................................................3

Chapter LITERATURE REVIEW…........................................................................4-9

2.1 Literature Review...................................................................................4-9

Chapter 3 METHODOLOGY…............................................................................10-17

3.1 Methodology.......................................................................................11-16

3.2 Block Diagram....................................................................................17-27

3.3 Coding and Cost..................................................................................28-30

Chapter 4 HARDWARE DESCRIPTION…........................................................18-38

4.1 Node MCU……………………………………………………………18-22

4.1.1 Key Features........................................................................................... 31-34

4.1.2 Application..........................................................................................35

4.1.3 Pin Configuration..........................................................................36-38

vii
4.1.4 Advantages of Node MCU………………………………………. 21

4.1.5 Future scope and outlook………………………………………22

4.1.6 Conclusion……………………………………………………….22

4.2 ULN2003 IC…………………………………………………………23-25

4.2.1 Key Features…………………………………………………….23

4.2.2 Working Principles………………………………………………24

4.2.3 Applications of ULN2003 IC…………………………………24

4.2.4 Advantages of ULN2003


IC……………………………………….25

4.2.5 Conclusion…………………………………………………………25

4.3 Wipers……………………………………………………………………26-27

4.3.1 History of wipers…………………………………………………..26

4.3.2 Working Mechanism…………………………………………….27

4.3.3 Conclusion…………………………………………………….27\

4.4 Solar Panel……………………………………………………………….28-30

4.4.1 Benefits of solar panel……………………………………………..28

4.4.2 Future Outlook of solar panel……………………………………..29

4.4.3 Conclusion………………………………………………………..30

4.5 Bluetooth Module………………………………………………………..31-33

4.5.1 Types of Bluetooth module……………………………..……….31-32

4.5.2 Applications……………………………………………………32

4.5.3 Advantages………………………………………………………32

4.5.4 Future Trends…………………………………………………33

4.5.5 Conclusion………………………………………………………33

4.6 Relay Module………………………………………………………………34-36


viii
4.6.1 How Relay Module works……………………..………………….34

4.6.2 Types of Relay module………………………..…………………35

4.6.3 Advantages……………………………………..……………..35-36

4.6.4 Future Trends………………………………….………………….36

4.6.5 Conclusions………………………………...……………………..36

4.7 Real Time Clock……………………………………………………….37-40

4.7.1 Key Features……………………………………………………………38

4.7.2 Working Principle……………………..………………………….38

4.7.3 Applications………………………………………………………..38

4.7.4 Advantages……………………………………………………….39

4.7.5 Conclusion…………………………..……………………………..39

Chapter 5 SOFTWARE DESCRIPTION…........................................................39-44

5.1 IDE.........................................................................................................42

5.1.1 Arduino IDE.................................................................................42-46

5.1.2 Conclusion..........................................................................................47

5.1.3 Blynk App………………………………………………………43-44

Chapter CONCLUSION….....................................................................................45-46

6.1 Conclusion...............................................................................................45

6.2 Limitations of Our Systems....................................................................46

6.3 Scope in future.......................................................................................46

Reference..................................................................................................................47

Appendix..................................................................................................................48-80

ix
List of Abbreviations

IOT Internet Of Things

SCADA Supervisory Control and Data Acquisition

MCU Micro Controller Unit

MPPT Maximum Power Point Tracking

PV Photo-Voltaic

CSP Concentrated Solar Power

IC Integrated Circuit

RTC Real Time Clock

DC Direct current

PCB Printed Circuit Board

LED Light Emitting Diode

x
List of Figure

Fig 1.1 – Solar Panel Cleaning System using Sprinkler


Fig 2.1 – Manual Solar Panel Cleaning Technique
Fig 2.2 –IOT Based Solar Panel Cleaning Technique
Fig 3.1.1- Flow Chart Of Solar Panel Cleaning System
Fig 3.1.2 - Simulation circuit of the system
Fig 3.2.1-Block Diagram Of Automatic Solar panel Cleaning System
Fig 3.2.2 - Autocad Stekch of Automatic Solar Panel Cleaning System
Fig 3.2.3 - Circuit Diagram of Automatic Solar Panel Cleaning System
Fig 4.1.1 – Pin Diagram of Node MCU

Fig 4.1.2 – Pin configuration of Nofe MCU

Fig 4.2.1 – Pin Diagram of ULN2003 IC


Fig 4.3.1 - Wipers

Fig 4.4.1 – Solar Panel

Fig 4.5.1 – Pin Diagram of Bluetooth Module

Fig 4.6.1 - Pin Diagram of Relay Module


Fig 4.7.1 – Pin Diagram of RTC

xi
List of Table

Table 1 - The device cost by part


Table 2 - Summary of Arduino mini
Table 3 – Technical Specification

xii
xiii
xiv
CHAPTER 1

1.1 INTRODUCTION

In the era of Industry 4.0, automation has become a crucial support system for
organizations. Industry 4.0 represents a cyber-physical system where machines in
manufacturing processes communicate with each other, creating an intelligent
environment. Solar power stations rely on vast arrays of tens of thousands of solar panels
to generate energy. In many tropical countries, solar panel farms often face significant dirt
and dust accumulation. Among the many factors affecting solar panel efficiency, the
presence of dirt and dust is a major concern, as it can diminish energy production. Node
MCU, a microcontroller designed for solar power systems with a built-in Wi Fi module,
plays a pivotal role in ensuring reliable electricity generation from solar power plants. It
monitors issues like weak connections between solar panels, dust build-up affecting
output, and other variables impacting solar energy production. Hence, an Internet of
Things (IoT)based automated solar power monitoring system is introduced, enabling
remote monitoring from anywhere on the planet. This system employs a Node MCU
controller to oversee the performance of the solar panel array. It continuously monitors the
panels and transmits power production data to an IoT platform. Solar power parameters are
sent to the IoT Blynk server via the internet using the Blynk app. A user-friendly interface
displays this information to users and triggers alerts if the output unexpectedly drops. An
automated cleaning process is initiated when output parameters fall below a specific
threshold. Without thorough cleaning every two months, a substantial 40-50% loss in
efficiency can be anticipated. Frequent cleaning is essential to maximize power production
efficiency. The system automatically removes dust at specified intervals using a controller
circuit to drive DC motors for panel cleaning. This paper explores the potential for
enhancing solar panel production through regular cleaning.

1 | Page
Figure 1.1: Solar Panel Cleaning System using Sprinkler

Figure 1 describes, it is designed to maintain the efficiency of solar panels by removing dust,
debris, and other residues that accumulate on their surface. This system typically incorporates a
network of sprinklers that are strategically placed around the solar panels. The sprinklers can be
programmed to activate at specific intervals, ensuring regular cleaning without the need for manual
labor.

The system utilizes water, which is sprayed over the solar panels to wash away the accumulated
dirt. The water can be sourced sustainably, such as through rainwater harvesting, to minimize
environmental impact. Some systems also include sensors that detect dirt levels, optimizing water
usage only when necessary, which conserves water and reduces operational costs. This automated
approach ensures that the solar panels operate at optimal efficiency, thereby maximizing energy
production and prolonging the lifespan of the panels.

2 | Page
1.2 MOTIVATION

The motivation behind developing an Automatic Solar Panel Cleaning System center on
enhancing the efficiency and longevity of solar panels. Solar panels are prone to
accumulating dust, debris, and bird droppings, which can significantly reduce their ability
to absorb sunlight and generate electricity, often by as much as 30%. Regular cleaning is
crucial, but manual cleaning can be labor-intensive, costly, and potentially risky, especially
for large-scale solar farms.

An Automatic Solar Panel Cleaning System addresses these challenges by using robotic
solutions or water-efficient cleaning methods to maintain clean surfaces without the need
for human intervention. This automation ensures that panels operate at optimal efficiency,
maximizes energy output, and reduces the downtime and costs associated with manual
maintenance. Furthermore, these systems are designed to be environmentally friendly,
using minimal water and avoiding harmful chemicals, aligning with the sustainable ethos
of solar energy. Thus, these systems play a critical role in the cost-effective and efficient
management.

3 | Page
CHAPTER 2

2.1 LITERATURE REVIEW

V. Bhuvaneswari et al. (2014) described The Internet of Things (IoT) is the most promising area
which penetrates the advantages of Wireless Sensor and Actuator Networks (WSAN) and
Pervasive Computing domains. Different applications of IoT have been developed and researchers
of IoT well identified the opportunities, problems, challenges and the technology standards used in
IoT such as Radio Frequency Identification (RFID) tags, sensors, actuators, mobile phones, etc.
This paper is of two fold; the first fold covers the different applications that adopted smart
technologies so far. The second fold of this paper presents the overview of the sensors and its
standards. Kelebaone Tsamaase et al. (2017) presented the development of an automated dust
detection and cleaning system which could be used to clean photovoltaic (PV) modules. Dust
accumulation is one of the factors which negatively impact of the PV module output because it
obstructs solar radiation to incident on the module surface hence reducing the overall performance
of the system. The system was designed by writing a C program and compiled with Arduino IDE
to read voltage and sense current from the PV and calculate power output. The circuit was built
with proteus 8 professional. Simulation results show that the system was able to detector power
loss due to dust accumulation on module surface and as a results the motor drive for the cleaning
mechanism responded accordingly to operate cleaning mechanism. The work is still ongoing
whereby a prototype will be built to demonstrate the practicality of the system. Swanand S. Wable
et al. (2017) proposed the Solar Panels Farms are generally situated in dirt and dust areas which
are mostly in case of tropical countries. The performance of solar panels depends on various
factors, the power generated by farm can decreased if there is dust and dirt on panels and this is
the main factor for reduction. One can generally assume a reduction of about 40% - 50%, if the
panels are not clean properly for 1-2 months. So to overcome this problem and to increase the
efficiency of power production cleaning of module on regular basis is necessary. To clean the
dust, an automatic cleaning robot is developed, which will clean the panels on regular interval of
time. The mechanism is based on control circuit, DC motor; microfiber (bristles) to clean the
panels. The paper provides you with the idea how the robot will work and its effect on the energy
production by solar farms. It will also to help to understand the problem arise due to not cleaning
of solar cells. Manju B. et al. (2018) described energy is one of the major issues that the world is
facing in India, the supply of energy has been one of the major problems for both urban and rural
4|Page
households. About 60% to 70% of the energy demand of the country is met by fuel wood and
agriculture residues. Solar energy is a renewable source of energy, which has a great potential and
it is radiated by the sun. Renewable energy is important to replace the using of electric energy
generated by petroleum. Solar power has become a source of renewable energy and solar energy
application should be enhanced. The solar PV modules are generally employed in dusty
environments which are the case tropical countries like India. The dust gets accumulated on the
front surface of the module and blocks the incident light from the sun. It reduces the power
generation capacity of the module. The power output reduces as much as by 50% if the module is
not cleaned for a month. The cleaning system has been designed cleans the module by controlling
the Arduino programming. To remove the dust in the PV modules to improving the power
efficiency. Subhasri.G et al. (2018) presented a sunlight based framework is the device for
orienting solar photovoltaic modules and solar thermal collectors toward the sun.

In order to create an appropriate automatic solar panel cleaning system, understanding overview
of solar energy and its importance in renewable energy systems. Solar Panel Cleaning Systems
play a crucial role in maintaining the efficiency and performance of solar energy systems. Solar
energy is a vital component of renewable energy systems, offering sustainable and eco-friendly
power generation. However, solar panels face challenges such as reduced efficiency due to the
accumulation of dirt, dust, bird droppings, and other debris over time.
Automatic solar panel cleaning systems are designed to address these challenges by implementing
automated cleaning processes. These systems utilize various technologies like sensors, actuators,
and IoT connectivity to monitor the cleanliness of solar panels and initiate cleaning actions when
necessary. By keeping solar panels clean, these systems ensure optimal performance and
maximum energy output.
The benefits of automatic solar panel cleaning systems include improved energy efficiency,
extended lifespan of solar panels, reduced maintenance costs, and increased overall reliability of
solar energy systems. They contribute significantly to the sustainability and effectiveness of solar
power generation, making them essential components in modern renewable energy infrastructure.
Thinking about the state of the art of the innovation, successful strategy, robust control philosophy
and the potential added benefit of different research work which can be employed on an extensive
scale in maintainable manner. Presently we are entering in a new period of processing innovation
i.e. Internet of things (IoT). IoT is a sort of “universal global neural network” in the cloud which
associates various things. The IoT is a intelligently connected devices and framework contain
brilliant machine connecting and communicate with different machines, environments, objects and
5|Page
infrastructures and the radio frequency identification (RFID) and sensor network technologies will
rise to meet this new challenge. Furthermore the investigation gives the different related works on
iot empowered solar panel monitoring modules for the proficient way of gain power from the solar
radiation. Tushar Pokharkar et al. (2018) presented the solar PV modules are generally employed
in tropical countries like India. Dust and dirt particles accumulating on PV panels decreases the
solar energy reaching the cells, thereby reducing their overall power output. The power output
reduces as much as by 50% if the module is not cleaned for a month. Hence, cleaning the PV
panels is a problem of great practical engineering interest in solar PV power generation. In this
paper, the problem is reviewed and methods for dust removal are discussed. In order to regularly
clean the dust, an automatic cleaning system has been designed, which senses the dust on the solar
panel and also cleans the module automatically. This automatic system helps in maintaining the
overall output of the solar firm. For cleaning the PV modules, a mechanism consists of a
slidingbrushes has been developed. In terms of daily energy generation, the presented automatic-
cleaning scheme provides about 30% more energy output when compared to the dust accumulated
PV module. Abhishek Naik et al. (2019) proposed the solar PV modules are generally employed
in dusty environments which is the case in tropical countries like India. The dust gets accumulated
on the front surface of the module and blocks the incident light from the sun. It reduces the power
generation capacity of the module. The power output reduces as much as by 50% if the module is
not cleaned for a month. In order to regularly clean the dust, an automatic cleaning system has
been designed, which senses the dust on the solar panel and also cleans the module automatically.
In terms of daily energy generation, the presented automatic cleaning scheme provides about 30%
more energy output when compared to the dust accumulated PV module. Gargi Ashtaputre et al.
(2019) proposed the efficiency of Solar PV panel is greatly affected due to the accumulation of
dust, dirt and sea salt on panel. This paper aims at developing a low-cost automatic robot which
will smartly clean the panel. The project is divided into two parts: Cleaning System and
Monitoring System. Cleaning task is completed according to the data received from monitoring
system. Wireless technology has been implemented in order to collect all the data from individual
panel. The power output of each panel is monitored thoroughly and depending on the information
collected at each node, the cleaning action is triggered. This system is also able to detect breakage
of panel. The system can be operated remotely and user can access all the information on field
from any part of the world. Milan Vaghani et al. (2019) presented transparency in cleaning system
by using the most newly invented technology, which provide a better performance, integrity,
consistency, cost-effective and scalable solution for the removal of dust and speck. The presented
cleaning system provides about 32% more energy output compared to the dust accumulated solar
6|Page
panel. This system is control by application from whole world. Also this system reduces
manpower for cleaning of solar panel. This is automatic solar panel cleaning system. Sharvari
Nikesh Ghate et al. (2019) proposed energy demands are increasing sharply, therefore the need to
conserve energy and utilize available energy efficiently is very important. There are many forms
of renewable energy available, with the increasing demands there is a need to exploit renewable
sources of energy. Solar is one of them and it is a time-dependent and intermittent energy source.
Thus, it is important to store available energy and use later on when the need is greatest. While
storing solar energy which will drive us towards the goal of universal energy access, there is one
major drawback. This paper aims to eradicate that drawback by designing and installing an
automatic solar panel cleaning system. Dust accumulation on PV modules is the area of growing
concern for the reliability of solar panels. So, developing such a mechanism that will maintain the
efficiency of PV modules connected in arrays as in solar farms spread over a large area and also
for the rooftop assemblies at low cost is the main concern. This paper includes the study of effects
of change in efficiency of PV modules due to the accumulation of different dust particles found in
different regions, factors governing for the decrease in efficiency accounts a lot due to soiling and
developing an automated mechanism for cleaning. Labor-based cleaning methods for PV modules
are expensive and uses a large amount of water. This prototype includes DC motors controlled by
a drive unit that moves a cleaning head horizontally with or without using a spraying system. This
results in an increase in efficiency of overall PV modules, the amount of renewable energy
harnessed is more, less water usage and less water usage.
This paper is arranged according to the following sections: Section II deals with various cleaning
techniques which can be employed in PV panel cleaning. Section III gives the details of operation
proposed automated cleaning system. Section IV gives the results and analysis while Section V
gives conclusion and future work.

I. Manual Cleaning Techniques


There are different techniques of cleaning accumulated dust, example, dry cleaning technique
which consists of sliding brushes on PV panel surface [3]. Also,electrostatic cleaning is used
where the dust is shaken off the PV panel when an electrically charged wave breaks over the
surface of the PV panel. Another technique IS wet cleaning. One of the wet cleaning examples
include Heliotex, which is an automatic cleaning system that washes and rinses solar panel
surfaces [6]. The Heliotex system sources the water from the residence via a hose pipe connected
to the pump and attached to nozzles on the solar panel surface without causing rubbing. The
advantage of wet cleaning is that effectiveness of the PV panels is improved. Disadvantages of the
7|Page
system are that plenty of water and equipment such as pumps are required.

Figure-2.1: Manual Solar Panel Cleaning Technique

II. Automated Cleaning System Techniques


For this research the drycleaning method was used. The automated cleaning system for PV
modules was developed considering the type of dust detection or monitoring technique, method of
cleaning and the cleaning mechanism. Therefore, the cleaning software was modelled to work
hand-in-hand with the amount of irradiance produced from the sun and the software operation as
illustrated by the flowchart below. According to the developed algorithm the software
development for monitoring the efficiency and cleaning is operational during the day only when it
is sunny. The software implementation was written in C and uploaded to a microcontroller using
an IDE provided by Arduino and the simulation was carried out. The system consisted of the two
DC motors connected to the Arduino UNO via control circuit of the L293D motor driver. The
monitoring circuit and the light sensor were also connected to the Arduino UNO board. The
sensor was used to detect the presence of the light and the microcontroller will respond to this by
measuring output power from the panel if it is clear day or the output is “HIGH”. The cleaning
mechanism will be active only when the efficiency or the output power is low (20% below
average value.). As per the flow chart below, the sensor detects presence of solar radiation and if it
is not available it remains in idle or standby mode. When it detects the solar radiation the system
measures power PV module power output resulting from that radiation and compares it with the
average power. If the output power is less than 20% below average the system interprets that as
8|Page
normal and does not activate the cleaning mechanism. When the output power is 20% or more
below the average the system activates cleaning mechanism with motor making forward rotation
hence moving cleaning arm along the panel surface. The cleaning arm moves until reaching limit
switch which then activates reverse rotation of the motor. The reverse rotation moves the cleaning
arm back to its original position where it is stopped by another limit switch. The cyclic process
will continue until the measured output power is within the limit of not more than 20% below
average value.

Figure-2.2: IOT Based Solar Panel Cleaning Technique

9|Page
CHAPTER 3

3.1 METHODOLOGY

The methodology of an automatic solar panel cleaning system involves designing a mechanism
capable of efficiently removing dust, dirt, and debris from solar panels to maintain their optimal
performance. The system typically employs sensors to detect the level of soiling on the panels,
triggering the cleaning process when necessary. Brushes or wipers, often automated and powered
by motors, are strategically positioned to sweep across the surface of the solar panels, effectively
removing accumulated particles. Additionally, water jets or a cleaning solution may be integrated
to enhance the cleaning process. The system can be programmed to operate at specific intervals or
in response to environmental conditions. Regular monitoring and feedback mechanisms ensure the
system's effectiveness, contributing to increased energy production and the longevity of solar
panel installations.

10 | P a g e
Figure 3.1.1: Flow Chart Of Solar Panel Cleaning System

a) The following equipment and instruments are utilized in the experimental setup
฀ Arduino UNO - (0 V- 5V input) micro-controller board which is based on the
ATmega328.
฀ PV panel, rated 18V, 0.83A, 15W.
฀ Hall-Effect linear current sensor
฀ Voltage measurement unit: 18 V/ 5V voltage divider
฀ Motor drive to provide the control of the two DC motors used for cleaning mechanism.
฀ DC motors: two dc motors rated at 12V-100r.p.m.
฀ Photodiode to generate a current signal proportional to the light intensity.
The output voltage of the micro-controller was calculated as follows:

b) Simulation circuit of the system

An IoT-based solar panel cleaning system simulation circuit is typically designed to automate and
optimize the cleaning process, ensuring maximum efficiency of solar panels. The core
components of this system would include a microcontroller, sensors, a motor driver, and motors.
The microcontroller, such as an Arduino or ESP32, acts as the brain of the system. It processes
input from various sensors and controls the motors through the motor driver. In this setup, sensors
play a critical role; they might include moisture sensors, dust particle sensors, and light sensors.
These sensors help in determining the optimal cleaning times by detecting dirt, dust accumulation,
or reduced solar efficiency.
The motor driver circuit is crucial as it facilitates the control of motors that operate the cleaning
mechanism, typically brushes or wipers. The driver receives commands from the microcontroller
to activate the motors when cleaning is needed.
Additionally, an IoT aspect can be incorporated using a WiFi or GSM module, allowing the
system to be monitored and controlled remotely. This enables data collection on panel efficiency
and system performance, which can be accessed via a smartphone app or web dashboard.
For simulation, software like Proteus or MATLAB can be used to design and test the electronic
circuitry before actual implementation. This simulation would typically involve setting up the
microcontroller with connected sensors and motor drivers in the software, programming the
11 | P a g e
cleaning logic, and testing under different conditions to ensure reliability and effectiveness.

Figure 3.1.2: Simulation circuit of the system

3.2 Block Diagram

An IoT-based solar panel cleaning system utilizes Internet of Things technology to ensure that
solar panels operate at optimum efficiency by keeping them clean and free from debris. Here's an
outline of its block diagram and components:

 Solar Panels: These are the primary components of the system, responsible for converting
sunlight into electrical energy.

 Sensors: Integrated onto or near the solar panels, these sensors detect dirt, dust, or any
other form of coverage that can affect the efficiency of the panels. Common types of
sensors include optical sensors that detect the opacity on the panel surface and
photovoltaic sensors that measure the output efficiency of the panels.

 Communication Module: This component facilitates IoT connectivity. It enables the


system to send sensor data to a remote server or cloud platform and receive commands
back. Typically, this could involve the use of Wi-Fi, Bluetooth, or other wireless
communication technologies.
12 | P a g e
 Actuator System: Connected to the microcontroller, this system activates the cleaning
mechanism when instructed. It typically consists of motors that drive mechanical brushes
or water jets to clean the solar panel surfaces.

 Cleaning Mechanism: This includes brushes, wipers, or water jets designed to effectively
remove the dust and dirt from the solar panels without damaging them.

 Power Supply: The entire system can be powered by the energy produced by the solar
panels themselves, making it self-sustaining. A battery backup might also be included to
ensure the system operates during non-sunny conditions.

 User Interface/Control Panel: This allows users to monitor the system, set cleaning
schedules, and view real-time data and analytics on cleaning efficiency and solar output.
This interface can be accessed via a smartphone app or a web-based dashboard.

 Cloud Server/Database: This stores all the data collected from various sensors and user
inputs. It helps in analyzing the performance over time and can also be used for further
optimization of the cleaning schedule and method based on historical data.

This IoT-based solar panel cleaning system optimizes the cleaning process by automating
operations, thus ensuring maximum efficiency of the solar panels while reducing manual labor
and maintenance costs.

13 | P a g e
Figure 3.2.1-Block Diagram Of Automatic Solar panel Cleaning System

An IoT-based solar panel cleaning system features a smart, automated solution to maintain the
efficiency of solar panels. The architecture typically consists of various sensors, such as dust and
humidity sensors, that monitor the condition of the solar panels. These sensors are connected to a
microcontroller or an IoT gateway that processes the sensor data to determine when cleaning is
necessary. Actuators are then activated to control mechanical cleaning devices like brushes or
sprayers. The system often includes a communication module that enables remote monitoring and
control via a cloud platform, allowing operators to optimize cleaning schedules and monitor
system performance from anywhere

14 | P a g e
Figure 3.2.2: Autocad Stekch of Automatic Solar Panel Cleaning System

A circuit diagram for an IoT-based solar panel cleaning system typically incorporates several key
components to ensure effective operation and remote monitoring. The central component is a
microcontroller, such as an Arduino or Raspberry Pi, which acts as the brain of the system.
Connected to the microcontroller are various sensors, such as moisture sensors to detect rain or
dew and light sensors to measure the intensity of sunlight, triggering the cleaning mechanism
when required.

For the cleaning mechanism, servo motors or stepper motors are used to control brushes or wipers
mounted on the solar panels. The motors are driven by a motor driver circuit connected to the
microcontroller. Additionally, a Wi-Fi module is included to enable IoT connectivity. This module
allows the system to send real-time data about the solar panel's status and the cleaning process to a
remote server or mobile application.

15 | P a g e
Power management is crucial, often involving a power supply module that can switch between
solar power and battery power as necessary. Safety circuits, like fuses and relays, are integrated to
protect against overcurrent and ensure safe operation under various conditions. All these
components are interconnected with appropriate wiring to form a complete IoT-based solar panel
cleaning system circuit.

Figure 3.2.3: Circuit Diagram of Automatic Solar Panel Cleaning System

3.3.1 Cost Analysis

An IoT-based solar panel cleaning system presents an efficient way to enhance solar energy
production by maintaining the cleanliness of solar panels, which significantly improves their
efficiency. The cost analysis of such a system includes initial setup costs, operational costs, and
potential savings. The initial investment primarily encompasses the purchase of IoT devices,
sensors, and automated cleaning mechanisms. Additionally, integrating software for real-time
monitoring and control adds to the setup expense. Operational costs involve maintenance of the
IoT devices and periodic updates to the software. However, these costs are often offset by the
increased energy output due to regular cleaning, which ensures minimal dirt and debris
16 | P a g e
accumulation. The system can also reduce labor costs, as manual cleaning requirements decrease
with automated solutions. Over time, the increase in energy production can provide substantial
savings, potentially leading to a favorable return on investment. The economic feasibility is
enhanced by the potential extension of the panels’ lifespan, contributing further to long-term
savings. Overall, an IoT-based system, despite its upfront costs, can prove economical by
maximizing solar efficiency and minimizing maintenance expenses.
Table 3 - The device cost by part

3.3.2 Coding

Creating a simplified version of an IoT-based solar panel cleaning system requires integrating
sensors and actuators with a microcontroller, such as an Arduino, that communicates with the
Internet via a Wi Fi module. Here’s a brief overview:

 Begin by setting up an Arduino board with a Wi Fi module like the ESP8266 to enable IoT
capabilities. Connect soil moisture sensors to Arduino analog pins to detect dirt or dust
accumulation on the solar panels. Additionally, integrate water level sensors to monitor the
availability of cleaning water in the system's reservoir.
17 | P a g e
 Write a code for the Arduino to periodically read data from the soil moisture sensors. If the
sensors indicate a high level of dirt accumulation, the Arduino sends a signal to activate
water pumps or servos controlling cleaning brushes, depending on your mechanical setup.
To manage water resources efficiently, incorporate logic to check the water level sensor
before activating the cleaning mechanism.

 For IoT functionality, use the ESP8266 module to send sensor data to a cloud platform like
Thing Speak or Blynk. This allows remote monitoring of the panel's cleanliness and water
tank levels. Through the cloud platform, you can also manually trigger the cleaning
process from anywhere via the Internet.

This setup not only automates the cleaning process but also enhances the efficiency and lifespan
of solar panels by maintaining optimal exposure to sunlight.

CHAPTER 4

HARDWARE DESCRIPTION

4.1.1 NODE MCU

Node MCU is an open-source platform and development board that is based on the ESP8266 Wi-
Fi module. It was created to facilitate the development of Internet of Things (IoT) applications by
providing an easy-to-use, affordable, and flexible solution for connecting devices to the internet.
Node MCU offers a powerful yet simple environment for programming, thanks to its
compatibility with the Lua scripting language, as well as support for other programming
18 | P a g e
languages such as Arduino IDE and MicroPython.

Figure 4.1.1 Pin Diagram of Node MCU

4.1.2 Key Features of Node MCU:

 ESP8266 Module: The core of Node MCU is the ESP8266 microcontroller, which
features an integrated Wi-Fi chip for wireless connectivity and an advanced processor for
handling data.

 Programmable in Lua: Node MCU can be programmed using the Lua scripting language,
a lightweight and easy-to-learn language suitable for embedded applications.

 Support for Arduino IDE: Node MCU is also compatible with the Arduino IDE,
allowing users to program the board using C/C++ programming languages and access a
wide range of Arduino libraries.

 GPIO Pins: The development board offers a variety of General purpose Input/Output
(GPIO) pins, enabling connections to sensors, actuators, and other external components.

 Low Cost: Node MCU is known for its affordability, making it accessible to hobbyists,
students, and professional developers.

19 | P a g e
4.1.5 Applications of Node MCU:

 Internet of Things (IoT): Node MCU is ideal for developing IoT projects, such as smart
home devices, environmental monitoring, and wearable technology.

 Home Automation: Node MCU can be used to control lights, appliances, and other smart
devices remotely using a smartphone or other devices.

 Data Logging and Monitoring: Node MCU can collect data from various sensors and
send it to the cloud for analysis and monitoring.

 Prototyping and Hobby Projects: Node MCU's ease of use and low cost make it a
popular choice for prototyping and DIY projects.

20 | P a g e
Figure 4.2.2 Pin configuration of NODE MCU

4.1.4 Advantages of Node MCU:

 Easy to Use: Node MCU's simplicity and support for multiple programming environments
make it accessible to users with different skill levels.

 Wi-Fi Connectivity: The integrated Wi-Fi chip allows Node MCU to connect to networks
and communicate with other devices or cloud servers.

 Community Support: Node MCU has a large community of developers and enthusiasts
who contribute libraries, tutorials, and support.

 Low Power Consumption: Node MCU is designed for low power consumption, making
it suitable for battery-operated projects.

21 | P a g e
4.1.5 Future Trends and Outlook:

Node MCU continues to be a popular choice for IoT development due to its flexibility and
affordability. Future trends may include improved security features, better power management
options, and enhanced compatibility with emerging technologies. As IoT continues to grow, Node
MCU will likely play a central role in connecting and controlling devices in smart homes,
industries, and other environments.

4.1.6 Conclusion:

Node MCU is a versatile and powerful development board that simplifies the process of creating
connected devices and IoT applications. Its combination of an advanced microcontroller, support
for multiple programming languages, and affordability make it an excellent choice for developers
and hobbyists alike.

22 | P a g e
4.2.1 ULN2003 IC:

The ULN2003 IC is a commonly used integrated circuit that serves as a high-voltage and high-
current Darlington transistor array. It is designed to drive various types of loads, such as relays,
solenoids, DC motors, and stepper motors, by providing an interface between a low-power control
signal and a high-power load. The ULN2003 is popular in automation, robotics, and other
applications where efficient control of high-power devices is needed.

Figure 4.2.1 Pin Diagram Of ULN2003 IC

4.2.2 KEY FEATURES:

 Darlington Transistor Array: The ULN2003 contains seven Darlington pairs, which are
made up of two transistors connected in a way that amplifies the input current. This design
allows the IC to handle high currents and voltages.

 High-Voltage and High-Current Capability: The ULN2003 can handle voltages up to


50V and currents up to 500mA per channel, making it suitable for driving a wide range of
loads.

23 | P a g e
 Built-In Clamp Diodes: The IC includes built-in flyback diodes for each channel,
providing protection against voltage spikes when inductive loads are de-energized.

 Compact Design: The ULN2003 is available in compact packages, such as DIP and
SOIC, making it easy to integrate into electronic circuits.

4.2.3 Working Principles:

The ULN2003 IC acts as a switch that can control high-power loads using low-power signals.
Each of the seven channels in the IC consists of a Darlington pair, which amplifies the input
current and allows the control of loads with higher current and voltage requirements. The input
signals are typically provided by a microcontroller or other control circuits.

When a low-power input signal is applied to one of the IC's inputs, it triggers the corresponding
Darlington pair, allowing current to flow through the load connected to the output. The built-in
flyback diodes protect the IC and the connected components from voltage spikes generated by
inductive load

4.2.4 Applications Of ULN2003 IC:

 Motor Control: The IC can control stepper motors, DC motors, and other types of motors
in various applications, including robotics, automation, and CNC machines.

 Relay and Solenoid Control: The IC can drive relays and solenoids, enabling efficient
control of electrical circuits and mechanical devices.

 LED and Lamp Control: The IC can be used to control high-power LEDs and lamps,
making it suitable for lighting applications.

 Industrial Control Systems: The IC is often used in industrial control systems to drive
various high-power device.

24 | P a g e
4.2.5 Advantages of ULN2003 IC:

 Ease of Use: The IC's straightforward design and multiple channels make it easy to
integrate into electronic circuits.

 High Load Capability: The IC can handle high voltages and currents, allowing it to drive
a variety of loads.

 Protection Features: The built-in clamp diodes provide protection against voltage spikes,
enhancing the reliability and longevity of the IC and connected components.

 Cost-Effective: The ULN2003 is an affordable solution for driving high-power loads,


making it accessible to hobbyists and professionals alike.

4.2.6 Conclusion:

The ULN2003 IC is a versatile and reliable integrated circuit that serves as an interface between
low-power control signals and high-power loads. Its high-current and high-voltage capabilities,
built-in protection features, and ease of use make it an essential component in a variety of
applications, from motor control to relay and solenoid driving. Whether used in hobby projects or
professional applications, the ULN2003 offers efficient and effective control of high-power
devices.

25 | P a g e
4.3.1 Wipers

Wipers are an essential component of any vehicle, ensuring safe and clear visibility for drivers
during adverse weather conditions such as rain, snow, or fog. These seemingly simple devices
play a crucial role in maintaining road safety and preventing accidents. In this comprehensive
overview, we will explore the history, types, working mechanisms, maintenance, and future
advancements of wipers.

Figure 4.3.1 Wiper

4.3.2 History of Wipers:

Wipers have a rich history dating back to the early 20th century. The first wiper patent was filed in
1903 by Mary Anderson, an American inventor, who developed a manually operated wiper system
to clear snow and rain from the windshield. Anderson's invention consisted of a lever-operated
arm with a rubber blade that could be pulled across the windshield from inside the vehicle.
Over the years, windshield wipers have undergone numerous improvements and innovations,
including the introduction of electric motors in the 1920s and the development of intermittent
wipers in the 1960s. Today, modern windshield wipers come in various designs and are equipped
with advanced features such as rain sensors and adaptive speed control.

26 | P a g e
4.3.3 Working Mechanism of Wipers:

Windshield wipers operate through a combination of mechanical and electrical components.


The primary components of a wiper system include:

 Wiper Motor: The wiper motor provides the power to move the wiper arms and blades
across the windshield. It is typically controlled by a switch on the dashboard, allowing
the driver to adjust the speed and mode of the wipers.

 Wiper Arms and Blades: The wiper arms are attached to the wiper motor and hold the
wiper blades in place. The blades, made of rubber, glide across the windshield to remove
water, snow, and debris.

 Linkage: The linkage connects the wiper motor to the wiper arms, translating the
rotational motion of the motor into the back-and-forth motion of the wipers.

 Control Switch: The control switch allows the driver to adjust the wiper settings,
including speed and mode (continuous, intermittent, or mist).

4.3.4 Conclusion:

Windshield wipers are a vital safety feature in vehicles, providing drivers with clear visibility in
adverse weather conditions. Over the years, wipers have evolved significantly, with advancements
in design and technology enhancing their performance and efficiency. Proper maintenance and
care are essential for ensuring the longevity and effectiveness of wipers. As automotive
technology continues to advance, we can expect further innovations in wiper systems that improve
safety and convenience for drivers worldwide.

27 | P a g e
4.4.1 Solar Panel

Solar panels, or photovoltaic (PV) panels, have emerged as a key technology in the
transition to renewable energy sources. They convert sunlight into electricity and play a
critical role in reducing carbon emissions and combatting climate change. In this essay, we
will explore the principles behind solar panels, their types, benefits, challenges, and future
outlook.

Figure 4.4.1: Solar Panel

4.4.2 Benefits of Solar Panel:

Solar panels offer numerous advantages that contribute to a sustainable energy future:

 Renewable and Clean Energy: Solar panels generate electricity from sunlight, a
renewable resource. This process does not produce greenhouse gases or other
pollutants, making it an environmentally friendly option.

 Cost Savings: Once installed, solar panels can significantly reduce electricity bills
and may even generate excess energy that can be sold back to the grid.

 Energy Independence: Solar panels enable individuals and communities to


generate their own electricity, reducing reliance on centralized power sources.

 Low Maintenance: Solar panels require minimal maintenance and have long
28 | P a g e
lifespans, often lasting 25 years or more.

 Job Creation: The solar industry creates jobs in manufacturing, installation,


maintenance, and research and development.

4.4.3 Future Outlook of Solar Panels:

The future of solar panels looks promising, with ongoing research and innovation driving
improvements in efficiency, cost, and integration:

 Decreasing Costs: The cost of solar panels is expected to continue decreasing due
to advancements in manufacturing and economies of scale.

 Increased Efficiency: Research into new materials and designs will lead to higher
efficiency rates, allowing panels to generate more electricity from the same surface
area.

 Energy Storage Solutions: Improved battery technology will enable more


efficient storage of solar energy, making it possible to use solar power during non-
sunny periods.

 Integration with Smart Grids: Solar panels will play a key role in the
development of smart grids, providing decentralized energy generation and
contributing to grid stability.

 Expanding Applications: Solar panels will find new applications in areas such as
smart cities, wearable technology, and even space exploration.

29 | P a g e
4.4.4 Conclusion:

Solar panels are a central element in the global transition to renewable energy sources and
a sustainable future. Their ability to generate clean electricity from sunlight, coupled with
ongoing advancements in technology, positions them as a key player in addressing climate
change and promoting energy independence. As the world continues to embrace solar
energy, we can expect.

30 | P a g e
4.5.1 Bluetooth Module:

Bluetooth modules play a key role in enabling wireless communication between electronic
devices over short distances. This technology has become an integral part of modern life,
connecting a wide range of devices such as smartphones, computers, wearables, smart
home devices, and audio accessories. Bluetooth modules consist of a Bluetooth
transceiver, antenna, and control circuitry that manage data transmission and reception.

Figure 4.5.1 Pin diagram of Bluetooth Module HC-05

4.5.2 Types of Bluetooth Modules:

 Bluetooth Classic: Designed for continuous data transfer, these modules are ideal
for audio streaming and file transfers.

 Bluetooth Low Energy (BLE): Optimized for low power consumption, BLE
modules are used in devices that require long battery life, such as fitness trackers
and IoT sensors.
31 | P a g e
 Dual-Mode Modules: Supporting both Bluetooth Classic and BLE, these modules
offer flexibility for devices that need to handle various types of data transmission.

4.5.3 Applications of Bluetooth Modules:

 Consumer Electronics: Bluetooth modules enable wireless connections for


headphones, speakers, gaming controllers, and smart home devices.

 Healthcare: BLE modules are used in medical devices for real-time monitoring
and data transmission.

 Automotive: Bluetooth supports hands-free calling and audio streaming in vehicles


for safety and convenience.

 Industrial IoT: In industrial settings, BLE modules are used in sensors and
monitoring devices for predictive maintenance and operational efficiency.

 Wearable Technology: Bluetooth modules power smartwatches and fitness


trackers, enabling connectivity with smartphones.

4.5.4 Advantages:

 Wireless Convenience: Bluetooth provides a wireless connection, eliminating the


need for physical cables.

 Energy Efficiency: BLE modules offer low power consumption, extending battery
life in connected devices.

 Global Standardization: Bluetooth is a globally accepted standard, ensuring


compatibility across a wide range of devices.

32 | P a g e
 Ease of Integration: Bluetooth modules can be integrated into electronic designs,
facilitating wireless connectivity.

4.5.5 Future Trends:


As Bluetooth technology continues to evolve, the future promises faster speeds, longer
range, and even lower power consumption. The growing adoption of Bluetooth 5.0 and 5.1
standards brings improvements in data transfer rates, range, and connection stability.
Additionally, Bluetooth's role in the Internet of Things (IoT) is expected to expand,
enabling seamless communication between a diverse range of smart devices and sensors.

4.5.6 Conclusion:

Bluetooth modules are a vital component of modern technology, providing wireless


connectivity that enhances user experiences across various industries and applications.
Their continued evolution will contribute to further advancements in wireless
communication and connectivity.

33 | P a g e
4.6.1 RELAY MODULE:

A relay module is an electronic component that controls a high-power circuit using a low-
power signal. These modules play a crucial role in various applications, enabling
electronic devices to control high-voltage loads such as motors, lights, and appliances
while maintaining isolation from the control circuit. Relay modules are commonly used in
automation, home electronics, industrial control, and other applications requiring electrical
switching.

Figure 4.6.1 Pin diagram of Relay Module

4.6.2 How Relay Modules Work:

Relay modules function as electrically operated switches. They consist of an electromagnet


(coil) and a set of contacts. When a low-voltage signal is applied to the coil, it generates a
magnetic field that causes the contacts to open or close, allowing or interrupting the flow
of current in the high-power circuit. This separation between the control and power circuits
provides electrical isolation and safety.

4.6.3 Types of Relay Modules:

 Electromechanical Relays (EMRs): These are the most common type of relays,
using an electromagnet to move a mechanical armature and switch contacts. They
are durable and suitable for various applications.

34 | P a g e
 Solid-State Relays (SSRs): SSRs use semiconductor components (such as
transistors) to control the switching process. They offer faster switching speeds,
silent operation, and longer lifespans compared to EMRs.

 Reed Relays: Reed relays use a magnetic field to control reed switch contacts
within a glass envelope. They are ideal for low-power applications and provide fast
switching speeds.

4.6.4 Applications of Relay Modules:

 Home Automation: Relay modules enable the control of lights, fans, and other
appliances remotely or through automation systems.

 Industrial Control: In industrial settings, relay modules control machinery,


motors, and other high-power equipment.

 Automotive: Relay modules are used in vehicles for functions such as controlling
headlights, horns, and power windows.

 Power Management: Relay modules are used in power distribution systems to


control the flow of electricity and protect circuits from overload.

4.6.5 Advantages of Relay Modules:

 Isolation: Relay modules provide electrical isolation between control and power
circuits, enhancing safety.

 Versatility: They can control a wide range of electrical loads, from low to high
power, making them suitable for various applications.

 Simple Control: Relay modules allow low-voltage signals to control high-power


circuits, simplifying circuit design and operation.

35 | P a g e
 Reliability: Relay modules are known for their durability and reliability, with
many designed to withstand high loads and frequent switching.

4.6.6 Future Trends:

The future of relay modules involves advancements in materials and designs for improved
performance. Solid-state relays are gaining popularity due to their fast switching speeds,
silent operation, and long lifespans. Additionally, miniaturization trends are leading to the
development of smaller relay modules that can be integrated into compact electronic
devices.

4.6.7 Conclusion:

Relay modules are essential components in electronic systems, providing reliable control
over high-power circuits with low-voltage signals. Their versatility and safety features
make them a key part of various applications, from home automation to industrial control.
As technology advances, relay modules will continue to evolve, offering improved
performance and new possibilities for automation and control.

36 | P a g e
4.7.1 REAL TIME CLOCK:

A real-time clock (RTC) is a timekeeping component found in many electronic devices,


including computers, smartphones, embedded systems, and various IoT devices. It keeps
track of the current time and date, even when the main power source is turned off, thanks
to its independent power supply, such as a coin cell battery. RTC modules are essential for
ensuring accurate timekeeping in a variety of applications and play a vital role in
scheduling tasks, providing timestamps, and maintaining accurate system time.

Figure 4.7.1 Pin diagram of Real Time Clock

4.7.2 Key Features:

 Timekeeping: RTCs provide accurate timekeeping, maintaining the current date


and time regardless of power interruptions.

 Low Power Consumption: RTCs are designed to consume minimal power,


allowing them to operate on small batteries for years.

 Back-Up Power Source: Most RTCs have a dedicated power source, such as a
coin cell battery, ensuring they continue to function even when the main power is
disconnected.

37 | P a g e
 Alarm Functions: Some RTCs include alarm features, which can trigger specific
events or wake up a device at predetermined times.

 Clock Calibration: High-precision RTCs offer calibration features that allow them
to maintain accuracy over time.

4.7.3 Working Principles:

RTCs use a quartz crystal oscillator to maintain a consistent frequency, which in turn
drives a counter to keep track of time. The clock's internal registers count seconds,
minutes, hours, and days, allowing the RTC to maintain an accurate calendar. When the
device is turned on, the main system can read the time from the RTC and synchronize its
own clock.
RTCs typically communicate with the main system through serial interfaces such as I2C or
SPI, allowing easy integration with microcontrollers and other electronic components.

4.7.4 Applications of Real-Time Clocks:

 Computers and Servers: RTCs maintain accurate system time, which is essential
for scheduling tasks, logs, and timestamps.

 Embedded Systems: RTCs provide accurate timekeeping in embedded systems,


such as industrial automation, smart home devices, and wearable technology.

 IoT Devices: IoT devices often use RTCs to manage scheduling tasks, data
logging, and maintaining synchronization with other devices.

 Consumer Electronics: RTCs are used in a variety of consumer electronics, such


as digital clocks, cameras, and appliances.

4.7.5 Advantages of Real-Time Clocks:

 Accurate Timekeeping: RTCs ensure consistent and precise timekeeping, even


38 | P a g e
during power interruptions.

 Low Power Usage: RTCs consume very little power, allowing them to operate on
small batteries for long periods.

 Easy Integration: RTCs can be easily integrated with various microcontrollers and
electronic systems using standard communication protocols.

 Alarm and Interrupt Functions: RTCs with alarm and interrupt features enable
event-driven actions, such as waking up a device at a specific time.

4.7.6 Conclusion:

Real-time clocks are crucial components in modern electronic devices, providing accurate
and consistent timekeeping across a range of applications. Their low power consumption
and easy integration make them a versatile and reliable choice for developers and
engineers. As technology continues to advance, RTCs will play an essential role in
ensuring the precise timing and scheduling necessary for efficient operation in both
consumer and industrial electronic systems.

39 | P a g e
CHAPTER 5

SOFTWARE DESCRIPTION

5.1 IDE (Integrated Development Environment)

An integrated development environment (IDE) is a software application that


provides comprehensive facilities to computer programmers for software
development. An IDE normally consists of at least a source code editor, build
automation tools, and a debugger. The boundary between an IDE and other parts of
the broader software development environment is not well-defined; sometimes a
version control system or various tools to simplify the construction of a graphical user
interface (GUI) are integrated. Many modern IDEs also have a class browser, an
object browser, and a class hierarchy diagram for use in object-oriented software
development.

5.1.2 ARDUINO IDE

Arduino IDE is an open-source software that is mainly used for writing and compiling
the code into the Arduino Module. It is an official Arduino software, making code
compilation too easy that even a common person with no prior technical knowledge
can get their feet wet with the learning process. It is easily available for operating
systems like MAC, Windows, Linux and runs on the Java Platform that comes with
inbuilt functions and commands that play a vital role for debugging, editing and
compiling the code in the environment.

The main code, also known as a sketch, created on the IDE platform will ultimately
generate a Hex File which is then transferred and uploaded in the controller on the
board. The IDE environment mainly contains two basic parts: Editor and Compiler
where former is used for writing the required code and later is used for compiling and
uploading the code into the given Arduino Module. This environment supports both C
and C++ languages.

40 | P a g e
The ATmega328 on the Arduino Mini comes reburned with a bootloader that allows
you to upload new code to it without the use of an external hardware programmer. It
communicates using the original STK500 protocol (reference, C header files). You
can also bypass the bootloader and program the microcontroller through the ICSP (in
Circuit Serial Programming) header; see these instructions for details. The
ATmega16U2 (or 8U2 in the rev1 and rev2 boards) firmware source code is available.
The ATmega16U2/8U2 is loaded with a DFU bootloader.

The IDE environment is mainly distributed into three sections:


 Menu Bar
 Text Editor
 Output Pane
As you download and open the IDE software, it will appear like an image below.

The bar appearing on the top is called Menu Bar that comes with five different options as
follow:

 File – You can open a new window for writing the code or open an existing one.
Following table shows the number of further subdivisions the file option is
categorized into:

41 | P a g e
As you go to the preference section and check the compilation section, the Output Pane
will show the code compilation as you click the upload button.

And at the end of compilation, it will show you the hex file it has generated for the recent
sketch that will send to the Arduino Board for the specific task you aim to achieve.

42 | P a g e
 Edit – Used for copying and pasting the code with further modification for font
 Sketch – For compiling and programming
 Tools – Mainly used for testing projects. The Programmer section in this panel is
used for burning a bootloader to the new microcontroller.
 Help – In case you are feeling skeptical about software, complete help is available
from getting started to troubleshooting.

5.1.2 CONCLUSION
Arduino ide is an open-source platform which provide free programing of Arduino
board. It provides a beginner to learn about programming to the pro one to make large
project based on IoT and artificial intelligent. For. the programming is done in simple C
language without dealing with brainstorming machine language or assembly
language.it is the main reason of become popular among the student and project
developers.

43 | P a g e
5.2.1 BLYNK IOT APP:
Blynk IoT app facilitates seamless control of an automatic solar panel cleaning system. Users
can remotely schedule and monitor cleaning cycles, ensuring optimal energy production. Real-
time data on cleaning status and efficiency are accessible, enhancing the efficiency of solar
panels while minimizing manual intervention.

The Bluetooth Serial Monitor App is a mobile app that has a user interface that looks like the
Serial Monitor of Arduino IDE. It is originally designed for Arduino but can work with any
devices that support Classic Bluetooth or Bluetooth Low Energy BLE (Bluetooth 4.0). You can
interact with Bluetooth devices via this app as if It is the Serial Monitor of Arduino IDE on
your PC. There are also some improvements:

 Data sent from the Bluetooth Serial Monitor app is also shown on the console to make
it easy to see the history

 Data sent from the Bluetooth Serial Monitor app is marked with blue color (Bluetooth
color)

 Data received by the Bluetooth Serial Monitor app is marked with cyan color (Arduino
color)

44 | P a g e
Blynk is free to use for personal use and prototyping. Their business model generates profits by
selling subscriptions to businesses that want to publish Blynk-powered apps for their hardware
products or services.

Let’s take a closer look at each component of the Blynk Platform.

5.1.2 Conclusion
Blynk IoT is a highly effective platform that offers a user-friendly interface for building and
managing IoT applications. It simplifies the creation of IoT solutions by enabling users to design,
deploy, and scale their projects efficiently, without requiring deep technical knowledge in hardware
and software integration. With its modular widgets and customizable project dashboards, Blynk
allows users to rapidly develop prototypes and bring IoT concepts to fruition. The platform supports
a wide range of hardware devices and connectivity options, making it versatile for various IoT
applications, from smart home devices to industrial IoT systems. Additionally, Blynk’s cloud service
ensures data is securely managed and easily accessible, facilitating remote monitoring and control.
The community and support around Blynk are strong, offering abundant resources and examples
which further ease the development process. Overall, Blynk stands out as a robust, accessible tool
that empowers both hobbyists and professionals to innovate within the IoT space.

45 | P a g e
CHAPTER 6

CONCLUSION AND FUTURE WORKS

6.1 CONCLUSION

The Solar Panel Cleaning System project aimed to bring a better solution for maintaining solar
efficiency. The main scope was to develop a machine that can clean a solar panel by a proper
control system. This project is a developed prototype to expand on a new and increasing market.
The project team hit many obstacles along the way. Designing the control system required
learning Raspberry Pi configurations, python coding and its interference with the electrical
components. Using soldering boards to implement the designed circuit, hardware wiring, relays
and machinery were new experiences. This being said, the project fulfilled the desired design with
the planned control and mechanism. The DC motors were controlled by both relays and drivers to
accomplish speed and directions control. Also, control code for the DC motors and the water
pump were written then implemented in the system. Finally, the MPPT charge controller was
connected to the off grid system. However, the prototype was not completed because of the
challenges and the limitations that were mentioned earlier.

46 | P a g e
6.2 LIMITATIONS OF OUR SYSTEMS

Here are some limitations of our project: -

 High initial investment for installation and maintenance


 Components can wear out or malfunction, especially in harsh weather conditions.
 May not effectively clean all types of debris or stains.
 Systems that use water may not be suitable for areas with water scarcity.

6.2 SCOPE FOR FUTURE WORK

However, many up gradations can be done to our existing project. Some of which are listed
below-
The scope for future work on an Automatic Solar Panel Cleaning System is expansive and
can focus on several key areas. Innovations could aim to enhance cleaning efficiency using
advanced robotics and artificial intelligence to optimize cleaning schedules based on
weather conditions and dust accumulation. Energy self-sufficiency is another area, with
systems powered by solar energy itself to reduce operational costs and improve
sustainability. Additionally, integrating IoT sensors could provide real-time data on panel
cleanliness and performance, enabling predictive maintenance. Finally, developing scalable
and modular designs could help tailor systems for different sizes and configurations of solar
installations, making them more accessible globally.

47 | P a g e
REFERENCES

 F. Mejia, J. Kleissl & J. L. Bosch, 2013. The Effect Of Dust On Solar Panel

Systems, Energy Procedia 49 (2014), pp. 2370 – 2376.

 Shaharin Anwar Sulaimana, Atul Kumar Singhb and et al, 2014. Influence

Of Dirt Accumulation On Performance Of solar Panels, Energy Procedia

50(2014), pp. 50- 56.

 N. Ketjoy & M. Konyu, 2014. Study Of Dust Effect On Solar Module For

Solar Power Plant, Energy Procedia 52 (2014), pp. 431-437

 S. B. Halbhavi, S. G. Kikani and et al, 2014. Microcontroller Based

Automatic Cleaning Of Solar Panel, Ijltet 5 (4), pp. 99-103.

 Selvaganesh, P.S. Manoharan & V.Seetharaman, 2017. Cleaning Solar

Panels Using Portable Robot System, Ijcta 10 (02), pp. 195-203.

 Yiannis P. Markopoulos, June 2014. Robotic Device For Cleaning

Photovoltaic Panel Arrays, Sustainable Technology And Energy

Solutions,Researcher Gate, pp. 38-42.

 Athira Sivan, Lakshmi Priya and et al, May 2017. Automatic Self Cleaning

Solar Panel, Irjet4, pp. 20352037.

 Dipankar Deba, Nisarg L. Brahmbhatt, 2017. Review Of Yield Increase Of

Solar Panels Through Soiling Prevention, And A proposed Water-Free

 Automated Cleaning Solution, Elsevier 2017.

48 | P a g e
APPENDIX

CODE 1 (Blynk State) : -

enum State {
MODE_WAIT_CONFIG,
MODE_CONFIGURING,
MODE_CONNECTING_NET,
MODE_CONNECTING_CLOUD,
MODE_RUNNING,
MODE_OTA_UPGRADE,
MODE_SWITCH_TO_STA,
MODE_RESET_CONFIG,
MODE_ERROR,

MODE_MAX_VALUE
};

#if defined(APP_DEBUG)
const char* StateStr[MODE_MAX_VALUE+1] = {
"WAIT_CONFIG",
"CONFIGURING",
"CONNECTING_NET",
"CONNECTING_CLOUD",
"RUNNING",
"OTA_UPGRADE",
"SWITCH_TO_STA",
"RESET_CONFIG",
"ERROR",

"INIT"
};
#endif

namespace BlynkState
{
49 | P a g e
volatile State state = MODE_MAX_VALUE;

State get() { return state; }


bool is (State m) { return (state == m); }
void set(State m);
};

CODE 2 (Configuration Mode) : -

#include <WiFiClient.h>
#include <WebServer.h>
#include <DNSServer.h>
#include <Update.h>

#include <nvs.h>
#include <nvs_flash.h>

WebServer server(80);
DNSServer dnsServer;
const byte DNS_PORT = 53;

#ifdef BLYNK_USE_SPIFFS
#include "SPIFFS.h"
#else
const char* config_form = R"html(
<!DOCTYPE HTML>
<html>
<head>
<title>WiFi setup</title>
<style>
body {
background-color: #fcfcfc;
box-sizing: border-box;
}
body, input {
font-family: Roboto, sans-serif;
font-weight: 400;
font-size: 16px;
}
50 | P a g e
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

padding: 20px;
background-color: #ccc;
border-radius: 4px;
}
td { padding:0 0 0 5px; }
label { white-space:nowrap; }
input { width: 20em; }
input[name="port"] { width: 5em; }
input[type="submit"], img { margin: auto; display: block; width: 30%; }
</style>
</head>
<body>
<div class="centered">
<form method="get" action="config">
<table>
<tr><td><label for="ssid">WiFi SSID:</label></td> <td><input type="text" name="ssid"
length=64 required="required"></td></tr>
<tr><td><label for="pass">Password:</label></td> <td><input type="text" name="pass"
length=64></td></tr>
<tr><td><label for="blynk">Auth token:</label></td><td><input type="text" name="blynk"
placeholder="a0b1c2d..." pattern="[-_a-zA-Z0-9]{32}" maxlength="32"
required="required"></td></tr>
<tr><td><label for="host">Host:</label></td> <td><input type="text" name="host"
value="blynk.cloud" length=64></td></tr>
<tr><td><label for="port_ssl">Port:</label></td> <td><input type="number"
name="port_ssl" value="443" min="1" max="65535"></td></tr>
</table><br/>
<input type="submit" value="Apply">
</form>
</div>
</body>
</html>
)html";
#endif

51 | P a g e
static const char serverUpdateForm[] PROGMEM =
R"(<html><body>
<form method='POST' action='' enctype='multipart/form-data'>
<input type='file' name='update'>
<input type='submit' value='Update'>
</form>
</body></html>)";

void restartMCU() {
ESP.restart();
while(1) {};
}

void eraseMcuConfig() {
// Erase ESP32 NVS
int err;
//err=nvs_flash_init();
//BLYNK_LOG2("nvs_flash_init: ", err ? String(err) : "Success");
err=nvs_flash_erase();
BLYNK_LOG2("nvs_flash_erase: ", err ? String(err) : "Success");
}

void getWiFiName(char* buff, size_t len, bool withPrefix = true) {


const uint64_t chipId = ESP.getEfuseMac();
uint32_t unique = 0;
for (int i=0; i<4; i++) {
unique = BlynkCRC32(&chipId, sizeof(chipId), unique);
}
unique &= 0xFFFFF;

if (withPrefix) {
snprintf(buff, len, "Blynk %s-%05X", BLYNK_DEVICE_NAME, unique);
} else {
snprintf(buff, len, "%s-%05X", BLYNK_DEVICE_NAME, unique);
}
}

void enterConfigMode()
52 | P a g e
{
char ssidBuff[64];
getWiFiName(ssidBuff, sizeof(ssidBuff));

WiFi.mode(WIFI_OFF);
delay(100);
WiFi.mode(WIFI_AP);
delay(2000);
WiFi.softAPConfig(WIFI_AP_IP, WIFI_AP_IP, WIFI_AP_Subnet);
WiFi.softAP(ssidBuff);
delay(500);

IPAddress myIP = WiFi.softAPIP();


DEBUG_PRINT(String("AP SSID: ") + ssidBuff);
DEBUG_PRINT(String("AP IP: ") + myIP[0] + "." + myIP[1] + "." + myIP[2] + "." +
myIP[3]);

// Set up DNS Server


dnsServer.setTTL(300); // Time-to-live 300s
dnsServer.setErrorReplyCode(DNSReplyCode::ServerFailure); // Return code for non-
accessible domains
#ifdef WIFI_CAPTIVE_PORTAL_ENABLE
dnsServer.start(DNS_PORT, "*", WiFi.softAPIP()); // Point all to our IP
server.onNotFound(handleRoot);
#else
dnsServer.start(DNS_PORT, CONFIG_AP_URL, WiFi.softAPIP());
DEBUG_PRINT(String("AP URL: ") + CONFIG_AP_URL);
#endif

server.on("/update", HTTP_GET, []() {


server.sendHeader("Connection", "close");
server.send(200, "text/html", serverUpdateForm);
});
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
if (!Update.hasError()) {
server.send(200, "text/plain", "OK");
} else {
server.send(500, "text/plain", "FAIL");

53 | P a g e
}
delay(1000);
restartMCU();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
DEBUG_PRINT(String("Update: ") + upload.filename);
//WiFiUDP::stop();

if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size


Update.printError(BLYNK_PRINT);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(BLYNK_PRINT);
}
BLYNK_PRINT.print(".");
} else if (upload.status == UPLOAD_FILE_END) {
BLYNK_PRINT.println();
DEBUG_PRINT("Finishing...");
if (Update.end(true)) { //true to set the size to the current progress
DEBUG_PRINT("Update Success. Rebooting");
} else {
Update.printError(BLYNK_PRINT);
}
}
});

server.on("/config", []() {
DEBUG_PRINT("Applying configuration...");
String ssid = server.arg("ssid");
String ssidManual = server.arg("ssidManual");
String pass = server.arg("pass");
if (ssidManual != "") {
ssid = ssidManual;
}
String token = server.arg("blynk");
String host = server.arg("host");
54 | P a g e
String port = server.arg("port_ssl");

String ip = server.arg("ip");
String mask = server.arg("mask");
String gw = server.arg("gw");
String dns = server.arg("dns");
String dns2 = server.arg("dns2");

bool save = server.arg("save").toInt();

String content;

DEBUG_PRINT(String("WiFi SSID: ") + ssid + " Pass: " + pass);


DEBUG_PRINT(String("Blynk cloud: ") + token + " @ " + host + ":" + port);

if (token.length() == 32 && ssid.length() > 0) {


configStore.setFlag(CONFIG_FLAG_VALID, false);
CopyString(ssid, configStore.wifiSSID);
CopyString(pass, configStore.wifiPass);
CopyString(token, configStore.cloudToken);
if (host.length()) {
CopyString(host, configStore.cloudHost);
}
if (port.length()) {
configStore.cloudPort = port.toInt();
}

IPAddress addr;

if (ip.length() && addr.fromString(ip)) {


configStore.staticIP = addr;
configStore.setFlag(CONFIG_FLAG_STATIC_IP, true);
} else {
configStore.setFlag(CONFIG_FLAG_STATIC_IP, false);
}
if (mask.length() && addr.fromString(mask)) {
configStore.staticMask = addr;
}
if (gw.length() && addr.fromString(gw)) {
55 | P a g e
configStore.staticGW = addr;
}
if (dns.length() && addr.fromString(dns)) {
configStore.staticDNS = addr;
}
if (dns2.length() && addr.fromString(dns2)) {
configStore.staticDNS2 = addr;
}

if (save) {
configStore.setFlag(CONFIG_FLAG_VALID, true);
config_save();

content = R"json({"status":"ok","msg":"Configuration saved"})json";


} else {
content = R"json({"status":"ok","msg":"Trying to connect..."})json";
}
server.send(200, "application/json", content);

BlynkState::set(MODE_SWITCH_TO_STA);
} else {
DEBUG_PRINT("Configuration invalid");
content = R"json({"status":"error","msg":"Configuration invalid"})json";
server.send(500, "application/json", content);
}
});
server.on("/board_info.json", []() {
DEBUG_PRINT("Sending board info...");
const char* tmpl = BLYNK_TEMPLATE_ID;
char ssidBuff[64];
getWiFiName(ssidBuff, sizeof(ssidBuff));
char buff[512];
snprintf(buff, sizeof(buff),

R"json({"board":"%s","tmpl_id":"%s","fw_type":"%s","fw_ver":"%s","ssid":"%s","bssid":"%s
","last_error":%d,"wifi_scan":true,"static_ip":true})json",
BLYNK_DEVICE_NAME,
tmpl ? tmpl : "Unknown",
BLYNK_FIRMWARE_TYPE,

56 | P a g e
BLYNK_FIRMWARE_VERSION,
ssidBuff,
WiFi.softAPmacAddress().c_str(),
configStore.last_error
);
server.send(200, "application/json", buff);
});
server.on("/wifi_scan.json", []() {
DEBUG_PRINT("Scanning networks...");
int wifi_nets = WiFi.scanNetworks(true, true);
const uint32_t t = millis();
while (wifi_nets < 0 &&
millis() - t < 20000)
{
delay(20);
wifi_nets = WiFi.scanComplete();
}
DEBUG_PRINT(String("Found networks: ") + wifi_nets);

if (wifi_nets > 0) {
// Sort networks
int indices[wifi_nets];
for (int i = 0; i < wifi_nets; i++) {
indices[i] = i;
}
for (int i = 0; i < wifi_nets; i++) {
for (int j = i + 1; j < wifi_nets; j++) {
if (WiFi.RSSI(indices[j]) > WiFi.RSSI(indices[i])) {
std::swap(indices[i], indices[j]);
}
}
}

wifi_nets = BlynkMin(15, wifi_nets); // Show top 15 networks

// TODO: skip empty names


String result = "[\n";

char buff[256];
57 | P a g e
for (int i = 0; i < wifi_nets; i++){
int id = indices[i];

const char* sec;


switch (WiFi.encryptionType(id)) {
case WIFI_AUTH_WEP: sec = "WEP"; break;
case WIFI_AUTH_WPA_PSK: sec = "WPA/PSK"; break;
case WIFI_AUTH_WPA2_PSK: sec = "WPA2/PSK"; break;
case WIFI_AUTH_WPA_WPA2_PSK: sec = "WPA/WPA2/PSK"; break;
case WIFI_AUTH_OPEN: sec = "OPEN"; break;
default: sec = "unknown"; break;
}

snprintf(buff, sizeof(buff),
R"json( {"ssid":"%s","bssid":"%s","rssi":%i,"sec":"%s","ch":%i})json",
WiFi.SSID(id).c_str(),
WiFi.BSSIDstr(id).c_str(),
WiFi.RSSI(id),
sec,
WiFi.channel(id)
);

result += buff;
if (i != wifi_nets-1) result += ",\n";
}
server.send(200, "application/json", result + "\n]");
} else {
server.send(200, "application/json", "[]");
}
});
server.on("/reset", []() {
BlynkState::set(MODE_RESET_CONFIG);
server.send(200, "application/json", R"json({"status":"ok","msg":"Configuration
reset"})json");
});
server.on("/reboot", []() {
restartMCU();
});

58 | P a g e
#ifdef BLYNK_USE_SPIFFS
if (SPIFFS.begin()) {
server.serveStatic("/img/favicon.png", SPIFFS, "/img/favicon.png");
server.serveStatic("/img/logo.png", SPIFFS, "/img/logo.png");
server.serveStatic("/", SPIFFS, "/index.html");
} else {
DEBUG_PRINT("Webpage: No SPIFFS");
}
#endif

server.begin();

while (BlynkState::is(MODE_WAIT_CONFIG) || BlynkState::is(MODE_CONFIGURING)) {


delay(10);
dnsServer.processNextRequest();
server.handleClient();
app_loop();
if (BlynkState::is(MODE_WAIT_CONFIG) && WiFi.softAPgetStationNum() > 0) {
BlynkState::set(MODE_CONFIGURING);
} else if (BlynkState::is(MODE_CONFIGURING) && WiFi.softAPgetStationNum() == 0) {
BlynkState::set(MODE_WAIT_CONFIG);
}
}

server.stop();

#ifdef BLYNK_USE_SPIFFS
SPIFFS.end();
#endif
}

void enterConnectNet() {
BlynkState::set(MODE_CONNECTING_NET);
DEBUG_PRINT(String("Connecting to WiFi: ") + configStore.wifiSSID);

char ssidBuff[64];
getWiFiName(ssidBuff, sizeof(ssidBuff));
String hostname(ssidBuff);
hostname.replace(" ", "-");
59 | P a g e
WiFi.setHostname(hostname.c_str());

if (configStore.getFlag(CONFIG_FLAG_STATIC_IP)) {
if (!WiFi.config(configStore.staticIP,
configStore.staticGW,
configStore.staticMask,
configStore.staticDNS,
configStore.staticDNS2)
){
DEBUG_PRINT("Failed to configure Static IP");
config_set_last_error(BLYNK_PROV_ERR_CONFIG);
BlynkState::set(MODE_ERROR);
return;
}
}

WiFi.begin(configStore.wifiSSID, configStore.wifiPass);

unsigned long timeoutMs = millis() + WIFI_NET_CONNECT_TIMEOUT;


while ((timeoutMs > millis()) && (WiFi.status() != WL_CONNECTED))
{
delay(10);
app_loop();

if (!BlynkState::is(MODE_CONNECTING_NET)) {
WiFi.disconnect();
return;
}
}

if (WiFi.status() == WL_CONNECTED) {
IPAddress localip = WiFi.localIP();
if (configStore.getFlag(CONFIG_FLAG_STATIC_IP)) {
BLYNK_LOG_IP("Using Static IP: ", localip);
} else {
BLYNK_LOG_IP("Using Dynamic IP: ", localip);
}

BlynkState::set(MODE_CONNECTING_CLOUD);
60 | P a g e
} else {
config_set_last_error(BLYNK_PROV_ERR_NETWORK);
BlynkState::set(MODE_ERROR);
}
}

void enterConnectCloud() {
BlynkState::set(MODE_CONNECTING_CLOUD);

Blynk.config(configStore.cloudToken, configStore.cloudHost, configStore.cloudPort);


Blynk.connect(0);

unsigned long timeoutMs = millis() + WIFI_CLOUD_CONNECT_TIMEOUT;


while ((timeoutMs > millis()) &&
(!Blynk.isTokenInvalid()) &&
(Blynk.connected() == false))
{
delay(10);
Blynk.run();
app_loop();
if (!BlynkState::is(MODE_CONNECTING_CLOUD)) {
Blynk.disconnect();
return;
}
}

if (millis() > timeoutMs) {


DEBUG_PRINT("Timeout");
}

if (Blynk.isTokenInvalid()) {
config_set_last_error(BLYNK_PROV_ERR_TOKEN);
BlynkState::set(MODE_WAIT_CONFIG);
} else if (Blynk.connected()) {
BlynkState::set(MODE_RUNNING);

if (!configStore.getFlag(CONFIG_FLAG_VALID)) {
configStore.last_error = BLYNK_PROV_ERR_NONE;
configStore.setFlag(CONFIG_FLAG_VALID, true);
61 | P a g e
config_save();
}
} else {
config_set_last_error(BLYNK_PROV_ERR_CLOUD);
BlynkState::set(MODE_ERROR);
}
}

void enterSwitchToSTA() {
BlynkState::set(MODE_SWITCH_TO_STA);

DEBUG_PRINT("Switching to STA...");

delay(1000);
WiFi.mode(WIFI_OFF);
delay(100);
WiFi.mode(WIFI_STA);

BlynkState::set(MODE_CONNECTING_NET);
}

void enterError() {
BlynkState::set(MODE_ERROR);

unsigned long timeoutMs = millis() + 10000;


while (timeoutMs > millis() || g_buttonPressed)
{
delay(10);
app_loop();
if (!BlynkState::is(MODE_ERROR)) {
return;
}
}
DEBUG_PRINT("Restarting after error.");
delay(10);

restartMCU();
}

62 | P a g e
CODE 3 (Configuration Store) : -

#define CONFIG_FLAG_VALID 0x01


#define CONFIG_FLAG_STATIC_IP 0x02

#define BLYNK_PROV_ERR_NONE 0 // All good


#define BLYNK_PROV_ERR_CONFIG 700 // Invalid config from app (malformed token,etc)
#define BLYNK_PROV_ERR_NETWORK 701 // Could not connect to the router
#define BLYNK_PROV_ERR_CLOUD 702 // Could not connect to the cloud
#define BLYNK_PROV_ERR_TOKEN 703 // Invalid token error (after connection)
#define BLYNK_PROV_ERR_INTERNAL 704 // Other issues (i.e. hardware failure)

struct ConfigStore {
uint32_t magic;
char version[15];
uint8_t flags;

char wifiSSID[34];
char wifiPass[64];

char cloudToken[34];
char cloudHost[34];
uint16_t cloudPort;

uint32_t staticIP;
uint32_t staticMask;
uint32_t staticGW;
uint32_t staticDNS;
uint32_t staticDNS2;

int last_error;

void setFlag(uint8_t mask, bool value) {


if (value) {
flags |= mask;
} else {
flags &= ~mask;
}
}

bool getFlag(uint8_t mask) {


return (flags & mask) == mask;
}
} __attribute__((packed));

ConfigStore configStore;

const ConfigStore configDefault = {


0x626C6E6B,
BLYNK_FIRMWARE_VERSION,
0x00,
63 | P a g e
"",
"",

"invalid token",
CONFIG_DEFAULT_SERVER,
CONFIG_DEFAULT_PORT,
0,
BLYNK_PROV_ERR_NONE
};

template<typename T, int size>


void CopyString(const String& s, T(&arr)[size]) {
s.toCharArray(arr, size);
}

static bool config_load_blnkopt()


{
static const char blnkopt[] = "blnkopt\0"
BLYNK_PARAM_KV("ssid" , BLYNK_PARAM_PLACEHOLDER_64
BLYNK_PARAM_PLACEHOLDER_64
BLYNK_PARAM_PLACEHOLDER_64
BLYNK_PARAM_PLACEHOLDER_64)
BLYNK_PARAM_KV("host" , CONFIG_DEFAULT_SERVER)
BLYNK_PARAM_KV("port" , BLYNK_TOSTRING(CONFIG_DEFAULT_PORT))
"\0";

BlynkParam prov(blnkopt+8, sizeof(blnkopt)-8-2);


BlynkParam::iterator ssid = prov["ssid"];
BlynkParam::iterator pass = prov["pass"];
BlynkParam::iterator auth = prov["auth"];
BlynkParam::iterator host = prov["host"];
BlynkParam::iterator port = prov["port"];

if (!(ssid.isValid() && auth.isValid())) {


return false;
}

// reset to defaut before loading values from blnkopt


configStore = configDefault;

if (ssid.isValid()) { CopyString(ssid.asStr(), configStore.wifiSSID); }


if (pass.isValid()) { CopyString(pass.asStr(), configStore.wifiPass); }
if (auth.isValid()) { CopyString(auth.asStr(), configStore.cloudToken); }
if (host.isValid()) { CopyString(host.asStr(), configStore.cloudHost); }
if (port.isValid()) { configStore.cloudPort = port.asInt(); }

return true;
}

#include <Preferences.h>
Preferences preferences;
64 | P a g e
void config_load()
{
memset(&configStore, 0, sizeof(configStore));
preferences.getBytes("config", &configStore, sizeof(configStore));
if (configStore.magic != configDefault.magic) {
DEBUG_PRINT("Using default config.");
configStore = configDefault;
return;
}
}

bool config_save()
{
preferences.putBytes("config", &configStore, sizeof(configStore));
DEBUG_PRINT("Configuration stored to flash");
return true;
}

bool config_init()
{
preferences.begin("blynk", false);
config_load();
return true;
}

void enterResetConfig()
{
DEBUG_PRINT("Resetting configuration!");
configStore = configDefault;
config_save();
eraseMcuConfig();
BlynkState::set(MODE_WAIT_CONFIG);
}

void config_set_last_error(int error) {


// Only set error if not provisioned
if (!configStore.getFlag(CONFIG_FLAG_VALID)) {
configStore = configDefault;
configStore.last_error = error;
BLYNK_LOG2("Last error code: ", error);
config_save();
}
}

CODE 4(Console) :-

#include <Blynk/BlynkConsole.h>

BlynkConsole edgentConsole;

65 | P a g e
void console_init()
{
edgentConsole.init(BLYNK_PRINT);

edgentConsole.print("\n>");

edgentConsole.addCommand("reboot", []() {
edgentConsole.print(R"json({"status":"OK","msg":"resetting device"})json" "\n");
delay(100);
restartMCU();
});

edgentConsole.addCommand("config", []() {
edgentConsole.print(R"json({"status":"OK","msg":"entering configuration mode"})json" "\n");
BlynkState::set(MODE_WAIT_CONFIG);
});

edgentConsole.addCommand("devinfo", []() {
edgentConsole.printf(
R"json({"board":"%s","tmpl_id":"%s","fw_type":"%s","fw_ver":"%s"})json" "\n",
BLYNK_DEVICE_NAME,
BLYNK_TEMPLATE_ID,
BLYNK_FIRMWARE_TYPE,
BLYNK_FIRMWARE_VERSION
);
});

edgentConsole.addCommand("netinfo", []() {
char ssidBuff[64];
getWiFiName(ssidBuff, sizeof(ssidBuff));

byte mac[6] = { 0, };
WiFi.macAddress(mac);

edgentConsole.printf(
R"json({"ssid":"%s","bssid":"%02x:%02x:%02x:%02x:%02x:%02x","rssi":%d})json" "\n",
ssidBuff,
mac[5], mac[4], mac[3], mac[2], mac[1], mac[0],
WiFi.RSSI()
);
});

BLYNK_WRITE(InternalPinDBG) {
String cmd = String(param.asStr()) + "\n";
edgentConsole.runCommand((char*)cmd.c_str());
}

CODE 5(Indicator) :-

66 | P a g e
#if defined(BOARD_LED_PIN_WS2812)
#include <Adafruit_NeoPixel.h> // Library: https://github.com/adafruit/Adafruit_NeoPixel

Adafruit_NeoPixel rgb = Adafruit_NeoPixel(1, BOARD_LED_PIN_WS2812, NEO_GRB +


NEO_KHZ800);
#endif

void indicator_run();

#if !defined(BOARD_LED_BRIGHTNESS)
#define BOARD_LED_BRIGHTNESS 255
#endif

#if defined(BOARD_LED_PIN_WS2812) || defined(BOARD_LED_PIN_R)


#define BOARD_LED_IS_RGB
#endif

#define DIMM(x) ((uint32_t)(x)*(BOARD_LED_BRIGHTNESS)/255)


#define RGB(r,g,b) (DIMM(r) << 16 | DIMM(g) << 8 | DIMM(b) << 0)
#define TO_PWM(x) ((uint32_t)(x)*(BOARD_PWM_MAX)/255)

class Indicator {
public:

enum Colors {
COLOR_BLACK = RGB(0x00, 0x00, 0x00),
COLOR_WHITE = RGB(0xFF, 0xFF, 0xE7),
COLOR_BLUE = RGB(0x0D, 0x36, 0xFF),
COLOR_BLYNK = RGB(0x2E, 0xFF, 0xB9),
COLOR_RED = RGB(0xFF, 0x10, 0x08),
COLOR_MAGENTA = RGB(0xA7, 0x00, 0xFF),
};

Indicator() {
}

void init() {
m_Counter = 0;
initLED();
}

uint32_t run() {
State currState = BlynkState::get();

// Reset counter if indicator state changes


if (m_PrevState != currState) {
m_PrevState = currState;
m_Counter = 0;
}

if (g_buttonPressed) {
67 | P a g e
if (millis() - g_buttonPressTime > BUTTON_HOLD_TIME_ACTION) { return
beatLED(COLOR_WHITE, (int[]){ 100, 100 }); }
if (millis() - g_buttonPressTime > BUTTON_HOLD_TIME_INDICATION) { return
waveLED(COLOR_WHITE, 1000); }
}
switch (currState) {
case MODE_RESET_CONFIG:
case MODE_WAIT_CONFIG: return beatLED(COLOR_BLUE, (int[]){ 50, 500 });
case MODE_CONFIGURING: return beatLED(COLOR_BLUE, (int[]){ 200, 200 });
case MODE_CONNECTING_NET: return beatLED(COLOR_BLYNK, (int[]){ 50, 500 });
case MODE_CONNECTING_CLOUD: return beatLED(COLOR_BLYNK, (int[]){ 100,
100 });
case MODE_RUNNING: return waveLED(COLOR_BLYNK, 5000);
case MODE_OTA_UPGRADE: return beatLED(COLOR_MAGENTA, (int[]){ 50, 50 });
default: return beatLED(COLOR_RED, (int[]){ 80, 100, 80, 1000 } );
}
}

protected:

/*
* LED drivers
*/

#if defined(BOARD_LED_PIN_WS2812) // Addressable, NeoPixel RGB LED

void initLED() {
rgb.begin();
setRGB(COLOR_BLACK);
}

void setRGB(uint32_t color) {


rgb.setPixelColor(0, color);
rgb.show();
}

#elif defined(BOARD_LED_PIN_R) // Normal RGB LED (common anode or common


cathode)

void initLED() {
ledcAttachPin(BOARD_LED_PIN_R, BOARD_LEDC_CHANNEL_1);
ledcAttachPin(BOARD_LED_PIN_G, BOARD_LEDC_CHANNEL_2);
ledcAttachPin(BOARD_LED_PIN_B, BOARD_LEDC_CHANNEL_3);

ledcSetup(BOARD_LEDC_CHANNEL_1, BOARD_LEDC_BASE_FREQ,
BOARD_LEDC_TIMER_BITS);
ledcSetup(BOARD_LEDC_CHANNEL_2, BOARD_LEDC_BASE_FREQ,
BOARD_LEDC_TIMER_BITS);
ledcSetup(BOARD_LEDC_CHANNEL_3, BOARD_LEDC_BASE_FREQ,
BOARD_LEDC_TIMER_BITS);
}

68 | P a g e
void setRGB(uint32_t color) {
uint8_t r = (color & 0xFF0000) >> 16;
uint8_t g = (color & 0x00FF00) >> 8;
uint8_t b = (color & 0x0000FF);
#if BOARD_LED_INVERSE
ledcWrite(BOARD_LEDC_CHANNEL_1, TO_PWM(255 - r));
ledcWrite(BOARD_LEDC_CHANNEL_2, TO_PWM(255 - g));
ledcWrite(BOARD_LEDC_CHANNEL_3, TO_PWM(255 - b));
#else
ledcWrite(BOARD_LEDC_CHANNEL_1, TO_PWM(r));
ledcWrite(BOARD_LEDC_CHANNEL_2, TO_PWM(g));
ledcWrite(BOARD_LEDC_CHANNEL_3, TO_PWM(b));
#endif
}

#elif defined(BOARD_LED_PIN) // Single color LED

void initLED() {
ledcSetup(BOARD_LEDC_CHANNEL_1, BOARD_LEDC_BASE_FREQ,
BOARD_LEDC_TIMER_BITS);
ledcAttachPin(BOARD_LED_PIN, BOARD_LEDC_CHANNEL_1);
}

void setLED(uint32_t color) {


#if BOARD_LED_INVERSE
ledcWrite(BOARD_LEDC_CHANNEL_1, TO_PWM(255 - color));
#else
ledcWrite(BOARD_LEDC_CHANNEL_1, TO_PWM(color));
#endif
}

#else

#warning Invalid LED configuration.

void initLED() {
}

void setLED(uint32_t color) {


}

#endif

/*
* Animations
*/

uint32_t skipLED() {
return 20;
}

#if defined(BOARD_LED_IS_RGB)
69 | P a g e
template<typename T>
uint32_t beatLED(uint32_t onColor, const T& beat) {
const uint8_t cnt = sizeof(beat)/sizeof(beat[0]);
setRGB((m_Counter % 2 == 0) ? onColor : (uint32_t)COLOR_BLACK);
uint32_t next = beat[m_Counter % cnt];
m_Counter = (m_Counter+1) % cnt;
return next;
}

uint32_t waveLED(uint32_t colorMax, unsigned breathePeriod) {


uint8_t redMax = (colorMax & 0xFF0000) >> 16;
uint8_t greenMax = (colorMax & 0x00FF00) >> 8;
uint8_t blueMax = (colorMax & 0x0000FF);

// Brightness will rise from 0 to 128, then fall back to 0


uint8_t brightness = (m_Counter < 128) ? m_Counter : 255 - m_Counter;

// Multiply our three colors by the brightness:


redMax *= ((float)brightness / 128.0);
greenMax *= ((float)brightness / 128.0);
blueMax *= ((float)brightness / 128.0);
// And turn the LED to that color:
setRGB((redMax << 16) | (greenMax << 8) | blueMax);

// This function relies on the 8-bit, unsigned m_Counter rolling over.


m_Counter = (m_Counter+1) % 256;
return breathePeriod / 256;
}

#else

template<typename T>
uint32_t beatLED(uint32_t, const T& beat) {
const uint8_t cnt = sizeof(beat)/sizeof(beat[0]);
setLED((m_Counter % 2 == 0) ? BOARD_LED_BRIGHTNESS : 0);
uint32_t next = beat[m_Counter % cnt];
m_Counter = (m_Counter+1) % cnt;
return next;
}

uint32_t waveLED(uint32_t, unsigned breathePeriod) {


uint32_t brightness = (m_Counter < 128) ? m_Counter : 255 - m_Counter;

setLED(DIMM(brightness*2));

// This function relies on the 8-bit, unsigned m_Counter rolling over.


m_Counter = (m_Counter+1) % 256;
return breathePeriod / 256;
}

#endif
70 | P a g e
private:
uint8_t m_Counter;
State m_PrevState;
};

Indicator indicator;

/*
* Animation timers
*/

#if defined(USE_TICKER)

#include <Ticker.h>

Ticker blinker;

void indicator_run() {
uint32_t returnTime = indicator.run();
if (returnTime) {
blinker.attach_ms(returnTime, indicator_run);
}
}

void indicator_init() {
indicator.init();
blinker.attach_ms(100, indicator_run);
}

#elif defined(USE_PTHREAD)

#include <pthread.h>

pthread_t blinker;

void* indicator_thread(void*) {
while (true) {
uint32_t returnTime = indicator.run();
returnTime = BlynkMathClamp(returnTime, 1, 10000);
vTaskDelay(returnTime);
}
}

void indicator_init() {
indicator.init();
pthread_create(&blinker, NULL, indicator_thread, NULL);
}

#elif defined(USE_TIMER_ONE)

#include <TimerOne.h>
71 | P a g e
void indicator_run() {
uint32_t returnTime = indicator.run();
if (returnTime) {
Timer1.initialize(returnTime*1000);
}
}

void indicator_init() {
indicator.init();
Timer1.initialize(100*1000);
Timer1.attachInterrupt(indicator_run);
}

#elif defined(USE_TIMER_THREE)

#include <TimerThree.h>

void indicator_run() {
uint32_t returnTime = indicator.run();
if (returnTime) {
Timer3.initialize(returnTime*1000);
}
}

void indicator_init() {
indicator.init();
Timer3.initialize(100*1000);
Timer3.attachInterrupt(indicator_run);
}

#elif defined(USE_TIMER_FIVE)

#include <Timer5.h> // Library: https://github.com/michael71/Timer5

int indicator_counter = -1;


void indicator_run() {
indicator_counter -= 10;
if (indicator_counter < 0) {
indicator_counter = indicator.run();
}
}

void indicator_init() {
indicator.init();
MyTimer5.begin(1000/10);
MyTimer5.attachInterrupt(indicator_run);
MyTimer5.start();
}

#else

72 | P a g e
#warning LED indicator needs a functional timer!

void indicator_run() {}
void indicator_init() {}

#endif

CODE 6(Reset Button):-

volatile bool g_buttonPressed = false;


volatile uint32_t g_buttonPressTime = -1;

void button_action(void)
{
BlynkState::set(MODE_RESET_CONFIG);
}

void button_change(void)
{
#if BOARD_BUTTON_ACTIVE_LOW
bool buttonState = !digitalRead(BOARD_BUTTON_PIN);
#else
bool buttonState = digitalRead(BOARD_BUTTON_PIN);
#endif

if (buttonState && !g_buttonPressed) {


g_buttonPressTime = millis();
g_buttonPressed = true;
DEBUG_PRINT("Hold the button for 10 seconds to reset configuration...");
} else if (!buttonState && g_buttonPressed) {
g_buttonPressed = false;
uint32_t buttonHoldTime = millis() - g_buttonPressTime;
if (buttonHoldTime >= BUTTON_HOLD_TIME_ACTION) {
button_action();
} else {
// User action
}
g_buttonPressTime = -1;
}
}

void button_init()
{
#if BOARD_BUTTON_ACTIVE_LOW
pinMode(BOARD_BUTTON_PIN, INPUT_PULLUP);
#else
pinMode(BOARD_BUTTON_PIN, INPUT_PULLDOWN);
#endif
attachInterrupt(BOARD_BUTTON_PIN, button_change, CHANGE);
}

CODE 8(Setting):-
73 | P a g e
/*
* Board configuration (see examples below).
*/

#if defined(USE_WROVER_BOARD)

#define BOARD_BUTTON_PIN 15
#define BOARD_BUTTON_ACTIVE_LOW true

#define BOARD_LED_PIN_R 0
#define BOARD_LED_PIN_G 2
#define BOARD_LED_PIN_B 4
#define BOARD_LED_INVERSE false
#define BOARD_LED_BRIGHTNESS 128

#elif defined(USE_TTGO_T7)

// This board does not have a built-in button


// Connect a button to gpio0 <> GND
#define BOARD_BUTTON_PIN 0
#define BOARD_BUTTON_ACTIVE_LOW true

#define BOARD_LED_PIN 19
#define BOARD_LED_INVERSE false
#define BOARD_LED_BRIGHTNESS 64

#else

#warning "Custom board configuration is used"

#define BOARD_BUTTON_PIN 0 // Pin where user button is attached


#define BOARD_BUTTON_ACTIVE_LOW true // true if button is "active-low"

#define BOARD_LED_PIN 4 // Set LED pin - if you have a single-color


LED attached
//#define BOARD_LED_PIN_R 15 // Set R,G,B pins - if your LED is PWM
RGB
//#define BOARD_LED_PIN_G 12
//#define BOARD_LED_PIN_B 13
//#define BOARD_LED_PIN_WS2812 4 // Set if your LED is WS2812 RGB
#define BOARD_LED_INVERSE false // true if LED is common anode, false if
common cathode
#define BOARD_LED_BRIGHTNESS 64 // 0..255 brightness control

#endif

/*
* Advanced options
*/
74 | P a g e
#define BUTTON_HOLD_TIME_INDICATION 3000
#define BUTTON_HOLD_TIME_ACTION 10000

#define BOARD_PWM_MAX 1023

#define BOARD_LEDC_CHANNEL_1 1
#define BOARD_LEDC_CHANNEL_2 2
#define BOARD_LEDC_CHANNEL_3 3
#define BOARD_LEDC_TIMER_BITS 10
#define BOARD_LEDC_BASE_FREQ 12000

#define CONFIG_AP_URL "blynk.setup"


#define CONFIG_DEFAULT_SERVER "blynk.cloud"
#define CONFIG_DEFAULT_PORT 443

#define WIFI_NET_CONNECT_TIMEOUT 30000


#define WIFI_CLOUD_CONNECT_TIMEOUT 30000
#define WIFI_AP_IP IPAddress(192, 168, 4, 1)
#define WIFI_AP_Subnet IPAddress(255, 255, 255, 0)
//#define WIFI_CAPTIVE_PORTAL_ENABLE

//#define USE_TICKER
//#define USE_TIMER_ONE
//#define USE_TIMER_THREE
//#define USE_TIMER_FIVE
#define USE_PTHREAD

#define BLYNK_NO_DEFAULT_BANNER

#if defined(APP_DEBUG)
#define DEBUG_PRINT(...) BLYNK_LOG1(__VA_ARGS__)
#else
#define DEBUG_PRINT(...)
#endif

CODE 9(Solar Panel Cleaning ESP-32):-

#include <HardwareSerial.h>
#include <EEPROM.h>
#include <DS1307ESP.h>

HardwareSerial timeBt(1);
DS1307ESP rtc;
// Fill-in information from your Blynk Template here
//#define BLYNK_TEMPLATE_ID "TMPL3zNAytjXq"
//#define BLYNK_DEVICE_NAME "SolarPanelCleaner"
#define BLYNK_TEMPLATE_ID "TMPL3gCwGq8QT"
#define BLYNK_DEVICE_NAME "Sloar Panel Cleaner"

#define BLYNK_FIRMWARE_VERSION "0.1.0"

75 | P a g e
#define BLYNK_PRINT Serial
//#define BLYNK_DEBUG

#define APP_DEBUG

// Uncomment your board, or configure a custom board in Settings.h


#define USE_WROVER_BOARD
//#define USE_TTGO_T7
#include "BlynkEdgent.h"
BlynkTimer timer;

int numberOfLoop = 0;
unsigned int long lastTime = 0;
#define led 2
#define m1a 18
#define m1b 19
#define limitLeft 23
#define limitRight 5
// Your WiFi credentials.
// Set password to "" for open networks.
int bellTime[10];
byte Hours[10];
byte Mints[10];
int functionId = 0;
String timeString = "";
String prefix,hh,mm,ss,dd,mon,yyyy;
int currentTime = 0;
String temp ="";
int buzzerRecordTime = 0;

#define LED_GPIO 2
#define PWM1_Ch 0
#define PWM1_Res 8
#define PWM1_Freq 1000

void myTimerEvent(){

Serial.println("timer triggered");
String s1 = String(Hours[0]) + ":" + String(Mints[0]);
String s2 = String(Hours[1]) + ":" + String(Mints[1]);
Blynk.virtualWrite(V1,s1);
Blynk.virtualWrite(V2,s2);
Blynk.virtualWrite(V3,numberOfLoop);

BLYNK_WRITE(V0){
int pin1 = param.asInt();
Serial.print("Button1:");
Serial.println(pin1);
76 | P a g e
switch (pin1){
case 1:
startCleaning();
break;
case 0:
digitalWrite(led,LOW);
break;
}
}

// splitting a string and return the part nr index split by separator


String getStringBy(String data, char separator, int index) {
int stringData = 0; //variable to count data part nr
String dataPart = ""; //variable to hole the return text

for(int i = 0; i<data.length(); i++) { //Walk through the text one letter at a time
if(data[i]==separator) {
//Count the number of times separator character appears in the text
stringData++;
} else if(stringData==index) {
//get the text when separator is the rignt one
dataPart.concat(data[i]);
} else if(stringData>index) {
//return text and stop if the next separator appears - to save CPU-time
return dataPart;
break;
}
}
//return text if this is the last part
return dataPart;
}

void writeString(int ad,String data)


{
int _size = data.length();
int i;
for(i=0;i<_size;i++)
{
EEPROM.write(ad+i,data[i]);
}
EEPROM.write(ad+_size,'\0'); //Add termination null character for String Data
EEPROM.commit();
}
String read_String(int ad)
{
int i;
char data[100]; //Max 100 Bytes
int len=0;
unsigned char k;
k=EEPROM.read(ad);
while(k != '\0' && len<20) //Read until null character
77 | P a g e
{
k=EEPROM.read(ad+len);
data[len]=k;
len++;
}
data[len]='\0';
return String(data);
}

void startCleaning(){
for (int i =0;i< numberOfLoop; i++){

digitalWrite(m1a,HIGH);//turn on motor in forword

Serial.println("Motor in forword");
//wait for right limit pressed
do{
delay(50);
}while(digitalRead(limitRight)== true);
Serial.println("Right Limit pressed");
Serial.println("Motor in backword");

digitalWrite(m1a,LOW);//turn off motor

delay(1000);

digitalWrite(m1b,HIGH);

//wait for left limit pressed


do{
delay(50);
}while(digitalRead(limitLeft)== true);

Serial.println("Left limit pressed");


digitalWrite(m1b,LOW);

Serial.print("cleaning second-");
Serial.println(i);
delay(1000);
Serial.println("");
Serial.println("");

}
}

void setup(){

delay(100);
timeBt.begin(9600, SERIAL_8N1, 16, 17);
delay(100);
pinMode(led,OUTPUT);
78 | P a g e
pinMode(m1a,OUTPUT);
pinMode(m1b,OUTPUT);
digitalWrite(m1a,LOW);
digitalWrite(m1b,LOW);
ledcAttachPin(LED_GPIO, PWM1_Ch);
ledcSetup(PWM1_Ch, PWM1_Freq, PWM1_Res);
ledcWrite(PWM1_Ch, 50);
pinMode(limitLeft,INPUT);
pinMode(limitRight,INPUT);
Serial.begin(9600);
EEPROM.begin(100);
rtc.begin();
//rtc.DSadjust(0, 19, 21, 2022, 3, 16); // 00:19:21 16 Mar 2022
Hours[0] = EEPROM.read(0);
Mints[0] = EEPROM.read(1);

Hours[1] = EEPROM.read(2);
Mints[1] = EEPROM.read(3);

numberOfLoop = EEPROM.read(4);

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


Serial.print("Time:");
Serial.print(Hours[i]);
Serial.print(":");
Serial.print(Mints[i]);
Serial.print(", ");
bellTime[i] = (Hours[i] * 60) + (Mints[i]);
Serial.println(bellTime[i]);
}

//rtc.DSadjust(1, 1, 0, 2023, 8, 25); // 00:19:21 16 Mar 2022


BlynkEdgent.begin();
timer.setInterval(2000L, myTimerEvent);

void loop() {
BlynkEdgent.run();
timer.run();

if(millis() - lastTime >= 1000) {


lastTime = millis();
Serial.println("\n1 sec completed");
rtc.DSread();
//Serial.println(rtc.getMahmin(true)); // (String) true = 00:00 false = 00 00 (24h)
// Serial.println(rtc.getMihmin(true)); // (String) true = 12:00 false = 12 00 (12h)
Serial.println(rtc.getTime());

//change current time in to second


currentTime = (rtc.getHour().toInt() * 60) + rtc.getMinute().toInt();
Serial.print("Current Time:");
79 | P a g e
Serial.println(currentTime);
}

//check if any incoming data is available


if (timeBt.available() > 0){
Serial.println("data from bt");
delay(20);
timeString = timeBt.readStringUntil(10);
timeBt.print("Time:");
timeBt.println(timeString);

prefix =getStringBy(timeString,',',0);//decide action


functionId = prefix.toInt();
Serial.println(prefix);

switch (functionId){
case 0://store time
hh = getStringBy(timeString,',',1);//hours
mm = getStringBy(timeString,',',2);//mint
ss = getStringBy(timeString,',',3);//second
dd = getStringBy(timeString,',',4);//date
mon = getStringBy(timeString,',',5);//hours
yyyy = getStringBy(timeString,',',6);//hours
//hhm,mm,ss,year,month,date
rtc.DSadjust(hh.toInt(), mm.toInt(), ss.toInt(), yyyy.toInt(), mon.toInt(), dd.toInt()); // 00:19:21
16 Mar 2022
timeBt.println("Time Stored In Rtc");

break;
case 1://set st time
hh = getStringBy(timeString,',',1);//hours
mm = getStringBy(timeString,',',2);//mint
EEPROM.write(0,hh.toInt());
EEPROM.write(1,mm.toInt());
EEPROM.commit();
timeBt.println("Cleaning-1 Stored");
break;
case 2: //set 2nd time
hh = getStringBy(timeString,',',1);//hours
mm = getStringBy(timeString,',',2);//mint
EEPROM.write(2,hh.toInt());
EEPROM.write(3,mm.toInt());
EEPROM.commit();
timeBt.println("Cleaning-2 Stored");
break;
case 3:
temp = getStringBy(timeString,',',1);//number of loop
numberOfLoop = temp.toInt();
EEPROM.write(4,numberOfLoop);
EEPROM.commit();
timeBt.print(numberOfLoop);
timeBt.println("-Number Of Loop Stored");
80 | P a g e
break;
case 4:
timeBt.println("Rebooting in 5 seconds");
for(int i = 6; i > 0; i --){
timeBt.print("Rebooting in ");
timeBt.print(i - 1);
timeBt.println(" Seconds");

delay(1000);
}
ESP.restart();
break;

81 | P a g e

You might also like