You are on page 1of 106

EFFICIENT IMPLEMENTATION OF OFF-GRID

SOLAR POWER SOLUTION

Project Supervisor:

Prof. Dr. Mian Muhammad Saleem

Group Members:

2005-Elect-073 M Fawad Baig


2005-Elect-091 Shariq Riaz
2005-Elect-187 Muhammad Hassan
2005-Elect-190 Muhammad Ahmad
2005-Elect-243 Gohar M Khan

Department of Electrical Engineering


University of Engineering and Technology, Lahore
EFFICIENT IMPLEMENTATION OF OFF-GRID
SOLAR POWER SOLUTION
By
2005-Elect-073 M Fawad Baig
2005-Elect-091 Shariq Riaz
2005-Elect-187 Muhammad Hassan
2005-Elect-190 Muhammad Ahmad
2005-Elect-243 Gohar M Khan

This thesis is submitted to Department of Electrical Engineering, University of Engineering and


Technology, Lahore, to fulfill the requirement of Bachelor’s degree

of

Electrical Engineering

Supervised by

Prof. Dr. Mian Muhammad Saleem

__________________ ___________________

Prof. Dr. Mian Muhammad Saleem (External Examiner)

_________________________ ______________________________

Syed Abdul Rahman Kashif Chairman,


(Internal Examiners) Department of Electrical Engineering

Department of Electrical Engineering


University of Engineering and Technology, Lahore
August, 2009
Dedications
Dedicated to Our Beloved Parents & Family Who Provided Us Every Opportunity to Achieve Our
Goals and to Our Teachers Who Tried Their Level Best to Convey Us the Knowledge They Had.
Acknowledgements

In the name of ALLAH, who is the most merciful, the most compassionate; the one and only
supreme power, the one whose will makes everything possible, and the one without whose will the
simplest is impossible.

All thanks to our beloved Family members for their prayers, guidance, support and care. They
dreamed for our future and advised us to work hard to fulfill their dreams. Without their moral and
financial support it would not have been possible for us to become supreme professionals.

We are really thankful to Dr. Mian Muhammad Saleem, our project supervisor for his kind support
and guidance during each and every phase of this project.

We also thank to Babar Bhai who helped us a lot in design and manufacturing of sun tracking
structure.

Finally, we are also indebted to the University of Engineering & Technology, Lahore which
supported us throughout our stay by providing their best teachers, equipped labs and with suitable
conditions for us to work on the project.
Abstract

Nowadays electricity is one of the basic necessities of mankind. As the demand of electricity is
increasing day by day, there is need to exploit renewable sources of energy. In the current era of
power shortage in Pakistan, the use of solar energy could be beneficial to great extent. Considering
the high cost of solar panels, our project addresses to analyze, design and implement an efficient
algorithm for power extraction from solar panel using dc-dc converter and then utilizing that power
for the electricity requirement of off-grid system. Moreover this project also address to the study of
boosting efficiency of solar system by two dimensional sun tracking.
TABLE OF CONTENT
DEDICATIONS ...........................................................................................................................................................3
ACKNOWLEDGEMENTS .........................................................................................................................................4
ABSTRACT .................................................................................................................................................................5
TABLE OF CONTENT ...............................................................................................................................................6
1. ENERGY .............................................................................................................................................................8
1.1 INTRODUCTION .................................................................................................................................................8
1.2 ENERGY CRISIS IN PAKISTAN .............................................................................................................................8
1.3 SOURCES OF ENERGY ........................................................................................................................................9
1.4 WHY EVERY KIND OF ENERGY IS CONVERTED INTO ELECTRIC ENERGY ............................................................ 13
1.5 METHODS TO GENERATE ELECTRIC ENERGY .................................................................................................... 13
2. SOLAR ENERGY .............................................................................................................................................15
2.1 AVERAGE ENERGY OVER THE YEARS ......................................................................................................................... 15
2.2 HOW SOLAR ENERGY IS USED? ............................................................................................................................... 16
2.3 SOLAR CELLS ...................................................................................................................................................... 16
2.4 CONSTRUCTION .................................................................................................................................................. 20
2.5 SOLAR MODULE AND ARRAY .................................................................................................................................. 21
2.6 THEORY OF SOLAR CELLS ....................................................................................................................................... 22
3. ELECTRICAL CHARACTERISTICS OF SOLAR CELLS AND MAXIMUM POWER POINT ................25
3.1 EQUIVALENT CIRCUIT OF A SOLAR CELL ........................................................................................................... 25
3.2 CHARACTERISTIC EQUATION ............................................................................................................................ 26
3.3 I-V CURVE OF SOLAR CELL ............................................................................................................................. 28
4. DC-DC CONVERTERS AND IMPLEMENTATION OF MPPT ...................................................................30
4.1 DC-DC CONVERTER TYPES ............................................................................................................................. 30
4.2 BUCK CONVERTER .......................................................................................................................................... 31
4.3 OUR IMPLEMENTATION OF MPPT .................................................................................................................... 32
5. SUN TRACKING..............................................................................................................................................33
5.1 NEED OF SUN TRACKING ................................................................................................................................. 33
5.2 HOW TO TRACK .............................................................................................................................................. 35
5.3 ALGORITHMS FOR SUN TRACKING ................................................................................................................... 37
5.4 SENSORS ......................................................................................................................................................... 38
5.5 OUR STRUCTURE FOR SOLAR TRACKING .......................................................................................................... 39
6. INVERTERS .....................................................................................................................................................41
6.1 CIRCUIT TOPOLOGIES USED IN INVERTERS ........................................................................................................ 41
6.2 OUTPUT WAVEFORM ....................................................................................................................................... 42
6.3 THREE-PHASE INVERTERS ................................................................................................................................ 43
6.4 CONTROL SIGNALS .......................................................................................................................................... 43
7. COMMERCIAL IMPLEMENTATION OF SOLAR SYSTEM......................................................................44
7.1 GRID-TIED SYSTEMS ....................................................................................................................................... 44
7.2 OFF-GRID SOLAR SYSTEMS .............................................................................................................................. 46
7.3 SOLAR BATTERY BACKUP - THE PROS AND CONS OF SOLAR BATTERY SYSTEMS ............................................... 46
8. FINAL IMPLEMENTATION OF OUR SYSTEM ..........................................................................................47
8.1 SOLAR PANEL ................................................................................................................................................. 47
8.2 DC-DC CONVERTER ....................................................................................................................................... 49
8.3 SUN TRACKING ................................................................................................................................................ 49
8.4 CONTROL PART ............................................................................................................................................... 49
8.5 TRANSFORMER ................................................................................................................................................ 50
8.6 BATTERY ........................................................................................................................................................ 51
8.7 INVERTER ....................................................................................................................................................... 52
8.8 SCHEMATICS ................................................................................................................................................... 53
8.9 PCB LAYOUT .................................................................................................................................................. 56
A. BATTERIES .....................................................................................................................................................58
A.1 INTRODUCTION ..................................................................................................................................................... 58
A.2 CATEGORIES OF BATTERIES ....................................................................................................................................... 59
B. TRANSFORMER DESIGN ..............................................................................................................................62
C. INDUCTOR DESIGN .......................................................................................................................................63
D. SOURCE CODE.....................................................................................................................................................64
D.1 16F877A_MODIFIED.H ........................................................................................................................................... 64
D.2 ALLOCATIONS.H ..................................................................................................................................................... 79
D.3 SPECSANDDEFS.H .................................................................................................................................................. 83
D.4 MAIN.C ............................................................................................................................................................... 85
D.5 MPPT.C .............................................................................................................................................................. 88
D.6 SUNTRACK.C ......................................................................................................................................................... 95
D.7 LCD.C ................................................................................................................................................................. 99
D.8 MISC.C .............................................................................................................................................................. 104
REFERENCES......................................................................................................................................................... 106
1. Energy
1.1 Introduction

Energy is fundamental to the quality of our lives. Nowadays, we are totally dependent on an
abundant and uninterrupted supply of energy for living and working. It is a key ingredient in
all sectors of modern economies. We use it constantly at home, at work and for leisure.
Energy maintains our standard of living and economy. From the time you wake up to the time
you go to sleep at night, energy has affected your life. Energy is important in everyone’s life,
whether you notice it or not. Without it people would have a harder time waking up and an
even harder time getting anywhere. Energy is important in many ways like. You wake up to
the sound of your alarm clock, in a nice warm home. Energy is important to heat our homes,
and most houses have gas, oil or electric heaters. The mechanical energy in a wind up alarm
or electric energy in a battery or plug in alarm is important to wake you up. Energy is needed
to heat water, which is used when you take a shower or wash your face in the morning.
Energy even effects when you put on fresh clothes in the morning. Your clothing were
probably made in a factory, which was powered by electricity. Now a days energy has
become more important for the collective good than individual’s need. Electricity runs like
blood through the veins of economy without it the economy will tremble and it will be
difficult for it to survive. Taking in account the diminishing natural resource known to
mankind it the need of the hour, that someone stood up and discover new horizons explore
more possibilities and bring forward new ideas to fulfill the exponentially increasing energy
needs of the world’s population.

1.2 Energy Crisis in Pakistan

Energy is one of the most problematic issues in the world. Whereas oil prices are steadily
rising and no stability is seen in near future. Demands of energy from the emerging markets
like China and India growing day by day. Pakistan with official figures of growth rate of 8%
will have a definite rise in demand of energy for minimum 3% In USA the Gulf of Mexico is
famous for oil producing and refining facilities. The prosperity of Houston is only due to oil
industry being flourished. However the weather is not so kind on this area and hurricanes and
tornadoes commonly hit the southern part of USA and Caribbean. Such is the volatility of
fuel market now that just news of one hurricane developing in Caribbean shoots the oil prices
in the world. A few years before oil was being traded on 20$ and nobody ever thought that
the weather conditions in the gulf can affect the oil market. Politically the Iran situation is
deteriorating day by day where as Iraq condition is not stabilizing. Oil today is being traded
around 65 $/, and the most vital question now is what will happen if the prices rises to 75 $ or
even one hundred $/barrel. Pakistan with small manufacturing market, surrounded by major
8
Energy

emerging economies like China, India, Malaysia, Indonesia, Philippines and Bangladesh will
be worst effected with the rise of energy prices. As a rule of thumb modern day
manufacturing industries utilize at least 33% production cost in terms of energy prices. An
increase of energy cost will affect their production cost and will force the manufacturers that
either to reduce the labor cost or to remain competitive in market by improving the quality
standards. Major giants China and India will benefit with this condition and smaller
economies will suffer badly. Are our policy makers in Islamabad thinking for the gravity of
problem which is now just standing on our door step? On famous oil embargo days a lot of
research in Europe was carried out to find the alternate source of energy. However with the
drop of oil prices such alternatives were uneconomical and therefore shelved. This is the time
that Pakistan now asses very carefully that in case of oil prices rising to 75 $ what actions it
should take to conserve energy and to find the alternate source of energy. A volunteer option
for all energy users is to conserve energy. To make the plants more efficient and to see that
each drop of petrol is saved .If we make serious study on this subject then we may achieve up
to 20% saving in energy ,hence saving in our production cost and making our products more
attractive in international market. Of course the energy conservation programs cost money.
However the investment will be rewarding and will be beneficial in long terms. Pakistan’s
thermal units are day by day become aging, reducing their output power. With the rise of
demand we are seeing an acute shortage of energy and hence load shedding and shutting of
the industrial units. This will seriously affect our competitiveness in the international market.
This is the responsibility of government to look for the alternate options for finding the
energy resources. This investment can only be made by the federal government. This is the
time of survival. Only the countries which are prepared for the worst will have a prosperous
future. But it is extremely difficult for the government with the current economy to blindly
invest a large amount in alternate energy projects. In light of above facts we volunteer to
analyze, study and implement Alternate energy project and to see the difficulties and it’s cost
comparison.

1.3 Sources of Energy

Nonrenewable

Non-renewable energy is energy, taken from "finite resources that will eventually dwindle,
becoming too expensive or too environmentally damaging to retrieve", as opposed to
renewable energy sources, which "are naturally replenished in a relatively short period of
time.

Following are the details of some Non-renewable energy sources know to man from at least
two centuries.

9
Energy

Coal

Coal, a fossil fuel, is the largest source of energy for the generation of electricity worldwide,
as well as one of the largest worldwide anthropogenic sources of carbon dioxide emissions.
Gross carbon dioxide emissions from coal usage are slightly more than those from petroleum
and about double the amount from natural gas. Coal is extracted from the ground by mining,
either underground or in open pits.

Petroleum Oil

Petroleum or crude oil is a naturally occurring, flammable liquid found in rock formations in
the Earth consisting of a complex mixture of hydrocarbons of various molecular weights, plus
other organic compounds. Petroleum, in one form or another, is not a recent discovery but is
now an important part of politics society and technology. The invention of the internal
combustion engine was the major influence in the rise in the importance of petroleum. In the
modern world petroleum has an influence across society, including geopolitics.

Natural Gas

Natural gas is a gas consisting primarily of methane. It is found associated with fossil fuels,
in coal beds, as methane catharses, and is created by methanogenic organisms in marshes,
bogs, and landfills. It is an important fuel source, a major feedstock for fertilizers, and a
potent greenhouse gas.

Natural gas is often informally referred to as simply gas, especially when compared to other
energy sources such as electricity. Before natural gas can be used as a fuel, it must undergo
extensive processing to remove almost all materials other than methane. The by-products of
that processing include ethane, propane, butanes, pentanes and higher molecular weight
hydrocarbons, elemental sulfur, and sometimes helium and nitrogen.

Nuclear

Nuclear power is any nuclear technology designed to extract usable energy from atomic
nuclei via controlled nuclear reactions. The only method in use today is through nuclear
fission, though other methods might one day include nuclear fusion and radioactive decay
(see below). All utility-scale reactors heat water to produce steam, which is then converted
into mechanical work for the purpose of generating electricity or propulsion. In 2007, 14% of
the world's electricity came from nuclear power. Also, more than 150 nuclear-powered naval
vessels have been built, and a few radioisotope rockets have been produced. Nuclear power is
a low carbon power source.

10
Energy

Renewable

Renewable energy is energy generated from natural resources—such as sunlight, wind, rain,
tides, and geothermal heat—which are renewable (naturally replenished). In 2006, about 18%
of global final energy consumption came from renewable, with 13% coming from traditional
biomass, such as wood-burning. Hydroelectricity was the next largest renewable source,
providing 3% of global energy consumption and 15% of global electricity generation.

Wind power is growing at the rate of 30 percent annually, with a worldwide installed capacity
of 121,000 megawatts (MW) in 2008. The annual manufacturing output of the photovoltaic’s
industry reached 6,900 MW in 2008, The world's largest geothermal power installation is The
Geysers in California, with a rated capacity of 750 MW.[8] Brazil has one of the largest
renewable energy programs in the world, involving production of ethanol fuel from sugar
cane, and ethanol now provides 18 percent of the country's automotive fuel. Ethanol fuel is
also widely available in the USA. While most renewable energy projects and production is
large-scale, renewable technologies are also suited to small off-grid applications, sometimes
in rural and remote areas, where energy is often crucial in human development. Kenya has
the world's highest household solar ownership rate with roughly 30,000 small (20–100 watt)
solar power systems sold per year.

Some renewable-energy technologies are criticized for being intermittent or unsightly, yet the
renewable-energy market continues to grow. Climate-change concerns, coupled with high oil
prices, peak oil, and increasing government support, are driving increasing renewable-energy
legislation, incentives and commercialization. New government spending, regulation and
policies should help the industry weather the 2009 economic crisis better than many other
sectors.

Sun

The majority of renewable energy technologies are powered by the sun. The Earth-
Atmosphere system is in equilibrium such that heat radiation into space is equal to incoming
solar radiation, the resulting level of energy within the Earth-Atmosphere system can roughly
be described as the Earth's "climate." The hydrosphere (water) absorbs a major fraction of the
incoming radiation. Most radiation is absorbed at low latitudes around the equator, but this
energy is dissipated around the globe in the form of winds and ocean currents. Wave motion
may play a role in the process of transferring mechanical energy between the atmosphere and
the ocean through wind stress. Solar energy is also responsible for the distribution of
precipitation which is tapped by hydroelectric projects, and for the growth of plants used to
create biofuels.

11
Energy

Renewable energy is derived from natural processes that are replenished constantly. In its
various forms, it derives directly from the sun, or from heat generated deep within the earth.

Wind

Airflows can be used to run wind turbines. Modern wind turbines range from around 600 kW
to 5 MW of rated power, although turbines with rated output of 1.5–3 MW have become the
most common for commercial use; the power output of a turbine is a function of the cube of
the wind speed, so as wind speed increases, power output increases dramatically.

Areas where winds are stronger and more constant, such as offshore and high altitude sites
are preferred locations for wind farms.

Geo Thermal

Geothermal energy is energy obtained by tapping the heat of the earth itself, both from
kilometers deep into the Earth's crust in some places of the globe or from some meters in
geothermal heat pump in all the places of the planet. It is expensive to build a power station
but operating costs are low resulting in low energy costs for suitable sites. Ultimately, this
energy derives from heat in the Earth's core.
Three types of power plants are used to generate power from geothermal energy: dry steam,
flash, and binary. Dry steam plants take steam out of fractures in the ground and use it to
directly drive a turbine that spins a generator. Flash plants take hot water, usually at
temperatures over 200 °C, out of the ground, and allows it to boil as it rises to the surface
then separates the steam phase in steam/water separators and then runs the steam through a
turbine. In binary plants, the hot water flows through heat exchangers, boiling an organic
fluid that spins the turbine. The condensed steam and remaining geothermal fluid from all
three types of plants are injected back into the hot rock to pick up more heat.
The geothermal energy from the core of the Earth is closer to the surface in some areas than
in others. Where hot underground steam or water can be tapped and brought to the surface it
may be used to generate electricity.
There is also the potential to generate geothermal energy from hot dry rocks. Holes at least
3 km deep are drilled into the earth. Some of these holes pump water into the earth, while
other holes pump hot water out. The heat resource consists of hot underground radiogenic

12
Energy

granite rocks, which heat up when there is enough sediment between the rock and the earth’s
surface. Several companies in Australia are exploring this technology.

Weather

Power can also be obtained from sewage water. The technique used therefore is Microbial
fuel cells. Also using the same microbial fuel cells, instead of from wastewater, energy may
also be obtained directly from (certain) aquatic plants. These include reed sweet grass, cord
grass, rice, tomatoes, lupines, alga.

Bio Mass

Plants use photosynthesis to grow and produce biomass. Also known as biomaterial, biomass
can be used directly as fuel or to produce biofuels. Agriculturally produced biomass fuels,
such as biodiesel, ethanol and bagasse (often a by-product of sugar cane cultivation) can be
burned in internal combustion engines or boilers. Typically biofuel is burned to release its
stored chemical energy. Research into more efficient methods of converting biofuels and
other fuels into electricity utilizing fuel cells is an area of very active work.

1.4 Why Every Kind of Energy is Converted into Electric Energy

Every kind of energy is preferably converted into electrical energy because:

 It is easy to store electric energy.


 In this era there many devices that can convert electrical energy into any
other form of energy.
 It is easy to transport electric energy.

1.5 Methods to Generate Electric Energy

There are seven fundamental methods of directly transforming other forms of energy into
electrical energy:

A.1 Static electricity, from the physical separation and transport of charge
(examples: turboelectric effect and lightning)

13
Energy

A.2 Electromagnetic induction, where an electrical generator, dynamo or


alternator transforms kinetic energy (energy of motion) into electricity
A.3 Electrochemistry, the direct transformation of chemical energy into
electricity, as in a battery, fuel cell or nerve impulse
A.4 Photoelectric effect, the transformation of light into electrical energy, as in
solar cells
A.5 Thermoelectric effect, direct conversion of temperature differences to
electricity, as in thermocouples and thermopiles
A.6 Piezoelectric effect, from the mechanical strain of electrically anisotropic
molecules or crystals
A.7 Nuclear transformation, the creation and acceleration of charged particles
(examples: betavoltaics or alpha particle emission)

Almost all commercial electrical generation is done using electromagnetic induction, in


which mechanical energy forces an electrical generator to rotate. There are many different
methods of developing the mechanical energy, including heat engines, hydro, wind and tidal
power.

14
2. Solar Energy
Solar energy is the radiant light and heat from the Sun that has been exploiting by humans
since ancient times using a range of ever-evolving technologies. Solar radiation along with
secondary solar resources such as wind and wave power, hydroelectricity and biomass
account for most of the available renewable energy on Earth. Only a little fraction of the
available solar energy is used.

Solar energy refers primarily to the use of solar radiation for practical ends. However, all
renewable energies, other than geothermal and tidal, derive their energy from the sun.

Solar technologies are broadly characterized as either passive or active depending on the way
they capture, convert and distribute sunlight. Active solar techniques use photovoltaic panels,
pumps, and fans to convert sunlight into useful outputs. Passive solar techniques include
selecting materials with favorable thermal properties, designing spaces that naturally circulate
air, and referencing the position of a building to the Sun. Active solar technologies increase
the supply of energy and are considered supply side technologies, while passive solar
technologies reduce the need for alternate resources and are generally considered demand
side technologies.

2.1 Average Energy over the Years

The Earth receives 174 pet watts (PW) of incoming solar radiation at the upper atmosphere.
Approximately 30% is reflected back to space while the rest is absorbed by clouds, oceans
and land masses. The spectrum of solar light at the Earth's surface is mostly spread across the
visible and near-infrared ranges with a small part in the near-ultraviolet.

The total solar energy absorbed by Earth's atmosphere, oceans and land masses is
approximately 3,850,000 exajoules (EJ) per year. In 2002, this was more energy in one hour
than the world used in one year. Photosynthesis captures approximately 3,000 EJ per year in
biomass. The amount of solar energy reaching the surface of the planet is so vast that in one
year it is about twice as much as will ever be obtained from all of the Earth's non-renewable
resources of coal, oil, natural gas, and mined uranium combined.

15
Solar Energy

2.2 How Solar Energy is used?

 Generate electricity using photovoltaic solar cells.


 Generate electricity using concentrated solar power.
 Generate electricity by heating trapped air which rotates turbines in a solar
updraft tower.
 Generate hydrogen using photo electrochemical cells.
 Heat and cool air through use of solar chimneys.
 Heat buildings, directly, through passive solar building design.
 Heat foodstuffs, through solar ovens.
 Heat water or air for domestic hot water and space heating needs using solar-
thermal panels.
 Solar air conditioning

2.3 Solar Cells

A solar cell or photovoltaic cell is a device that converts light directly into electricity by the
photovoltaic effect. Sometimes the term solar cell is reserved for devices intended
specifically to capture energy from sunlight, while the term photovoltaic cell is used when the
light source is unspecified. Assemblies of cells are used to make solar panels, solar modules,
or photovoltaic arrays.

Types of Solar Cells

Crystalline

Historically, crystalline silicon (c-Si) has been used as the light-


absorbing semiconductor in most solar cells, even though it is a
relatively poor absorber of light and requires a considerable
thickness (several hundred microns) of material. Nevertheless, it

16
Solar Energy

has proved convenient because it yields stable solar cells with good efficiencies (11-16%,
half to two-thirds of the theoretical maximum) and uses process technology developed from
the huge knowledge base of the microelectronics industry.

Two types of crystalline silicon are used in the industry. The first is monocrystalline,
produced by slicing wafers (up to 150mm diameter and 350 microns thick) from a high-purity
single crystal boule. The second is multicrystalline silicon, made by sawing a cast block of
silicon first into bars and then wafers. The main trend in crystalline silicon cell manufacture
is toward multicrystalline technology.

For both mono- and multicrystalline Si, a semiconductor homojunction is formed by


diffusing phosphorus (an n-type dopant) into the top surface of the boron doped (p-type) Si
wafer. Screen-printed contacts are applied to the front and rear of the cell, with the front
contact pattern specially designed to allow maximum light exposure of the Si material with
minimum electrical (resistive) losses in the cell.

Amorphous

An amorphous solar cell is a type of solar cell that is relatively cheap to produce and widely
available. They are named so because of their composition at the microscopic scale.
Amorphous means "without shape". When the term is applied to solar cells it means that the
silicon material that makes up the cell is not highly structured or crystallized.

Amorphous solar cells are usually created by applying doped silicon material to the back of a
plate of glass. The cells usually appear dark brown on the sun-facing side and silvery on the
conductive side. When produced as a solar panel (a collection of many solar cells) it will
appear to have several thin parallel lines running across its surface. These thin lines are
actually breaks in the N and P layers of the silicon substrate and they create the boundaries of
individual cells in the panel. Amorphous solar panels usually come without any obvious
hook-up points or wires. It can be very puzzling to figure out how to use them!

17
Solar Energy

CIGS

Copper indium gallium (di)selenide (CIGS) is a I-III-VI2 compound semiconductor material


composed of copper, indium, gallium, and selenium. The material is a solid solution of
copper indium selenide (often abbreviated "CIS") and copper gallium selenide, with a
chemical formula of CuInxGa(1-x)Se2, where the value of x can vary from 1 (pure copper
indium selenide) to 0 (pure copper gallium selenide). It is a tetrahedrally-bonded
semiconductor, with the chalcopyrite crystal structure, and a bandgap varying continuously
with x from about 1.0eV (for copper indium selenide) to about 1.7eV (for copper gallium
selenide). It is used as light absorber material for thin-film solar cells.

CIGS is mainly used in photovoltaic cells (CIGS cells), in the form of polycrystalline thin
films. Unlike the silicon cells based on a homojunction p-n junction, the structure of CIGS
cells is a more complex heterojunction system. The best efficiency achieved as of December
2005 was 19.5% reported by Contreras et al. A team at the National Renewable Energy
Laboratory achieved 19.9% new world record efficiency by modifying the CIGS surface and
making it look like CIS. This idea was first introduced in the IEEE conference in 2005. The
19.9% efficiency is by far the highest compared with those achieved by other thin film
technologies such as Cadmium Telluride (CdTe) or amorphous silicon (a-Si). . As for CIS,
and CGS solar cells, the world record total area efficiencies are 15.0% and 10.2%
respectively.

CIGS solar cells are not as efficient as crystalline silicon solar cells, for which the record
efficiency lies at 24.7%, but they are expected to be substantially cheaper. CIGS can be
deposited directly onto molybdenum coated glass sheets in a polycrystalline form, saving the
(energy) expensive step of growing large crystals, as necessary for solar cells made from
crystalline silicon. The latter are made of slices of solid silicon and require therefore more
expensive semiconductor material.

Cross-section of Cu(In,Ga)Se2 solar cell

18
Solar Energy

Three generation of Solar Cells

Solar Cells are classified into three generations which indicates the order of which each
became important. At present there is concurrent research into all three generations while the
first generation technologies are most highly represented in commercial production,
accounting for 89.6% of 2007 production.

First generation

First generation cells consist of large-area, high quality and single junction devices. First
Generation technologies involve high energy and labor inputs which prevent any significant
progress in reducing production costs. Single junction silicon devices are approaching the
theoretical limiting efficiency of 31% and achieve cost parity with fossil fuel energy
generation after a payback period of 5–7 years.

Second generation

Second generation materials have been developed to address energy requirements and
production costs of solar cells. Alternative manufacturing techniques such as vapor
deposition, electroplating, and use of Ultrasonic Nozzles are advantageous as they reduce
high temperature processing significantly. It is commonly accepted that as manufacturing
techniques evolve production costs will be dominated by constituent material requirements,
whether this be a silicon substrate, or glass cover.

The most successful second generation materials have been cadmium telluride (CdTe),
copper indium gallium selenide, amorphous silicon and micromorphous silicon. These
materials are applied in a thin film to a supporting substrate such as glass or ceramics,
reducing material mass and therefore costs. These technologies do hold promise of higher
conversion efficiencies, particularly CIGS-CIS, DSC and CdTe offers significantly cheaper
production costs.

Among major manufacturers there is certainly a trend toward second generation technologies;
however commercialization of these technologies has proven difficult. In 2007 First Solar
produced 200 MW of CdTe solar cells making it the fifth largest producer of solar cells in
2007 and the first ever to reach the top 10 from production of second generation technologies
alone. Wurth Solar commercialized its CIGS technology in 2007 producing 15 MW.
Nanosolar commercialized its CIGS technology in 2007 with a production capacity of
430 MW for 2008 in the USA and Germany.

Third generation

Third generation technologies aim to enhance poor electrical performance of second


generation (thin-film technologies) while maintaining very low production costs.

Current research is targeting conversion efficiencies of 30-60% while retaining low cost
materials and manufacturing techniques. They can exceed the theoretical solar conversion
efficiency limit for a single energy threshold material, that was calculated in 1961 by
Shockley and Queisser as 31% under 1 sun illumination and 40.8% under the maximal

19
Solar Energy

artificial concentration of sunlight (46,200 suns, which makes the latter limit more difficult to
approach than the former).

There are a few approaches to achieving these high efficiencies including the use of
Multijunction photovoltaic cells, concentration of the incident spectrum, the use of thermal
generation by UV light to enhance voltage or carrier collection, or the use of the infrared
spectrum for night-time operation.

High efficiency cells

High efficiency solar cells are a class of solar cell that can generate more electricity per
incident solar power unit (watt/watt). Much of the industry is focused on the most cost
efficient technologies in terms of cost per generated power. The two main strategies to bring
down the cost of photovoltaic electricity are increasing the efficiency (as many of the costs
scale with the area occupied per unit of generated power), and decreasing the cost of the solar
cells per generated unit of power. The later approach might come at the expense of reduced
efficiency, so the overall cost of the photovoltaic electricity does not necessarily decrease by
decreasing the cost of the solar cells. The challenge of increasing the photovoltaic efficiency
is thus of great interest, both from the academic and economic points of view.

2.4 Construction

Silicon solar cells have been available for a relatively long period of time. In order to increase
the output from such solar cells it has been conventional to provide a single layer anti-
reflection coating overlaying the solar cell. Typically these single layer anti-reflection
coatings have been formed of silicon monoxide, a titanium oxide such as titanium dioxide or
gas reacted titanium monoxide as well as tantalum pentoxide. Since the tantalum pentoxide
and the titanium oxide have an index of refraction which is greater than that of silicon
monoxide, they form a better anti-reflection coating between the silicon solar cell and the
glass cover which conventionally covers such a solar cell.

The silicon solar cell construction consists of a body formed essentially of silicon and having
a surface with a photovoltaic junction formed thereon. First and second layers are formed on
the surface of the solar cell and serve to provide an anti-reflection coating which is effective
within the spectral range of 400 to 1200 nanometers. A glass solar cell cover is provided
which is secured to the body having the first and second layers thereon by a cement. The first
layer is, counting from the body, formed of material that has an index of refraction which is
less than that of the body and which is greater than that of the glass cover. The second layer is
formed of a material that has an index of refraction which is greater than that of the glass
cover but which is less than that of the first layer.

20
Solar Energy

Solar cells are in fact large area semiconductor diodes. Due to photovoltaic effect energy of
light (energy of photons) converts into electrical current. At p-n junction, an electric field is
built up which leads to the separation of the charge carriers (electrons and holes). At
incidence of photon stream onto semiconductor material the electrons are released, if the
energy of photons is sufficient. Contact to a solar cell is realised due to metal contacts. If the
circuit is closed, meaning an electrical load is connected, then direct current flows.

2.5 Solar Module and Array

Regardless of size, a typical silicon PV cell produces about 0.5 – 0.6 volt DC under open-
circuit, no-load conditions. The current (and power) output of a PV cell depends on its
efficiency and size (surface area), and is proportional the intensity of sunlight striking the
surface of the cell. For example, under peak sunlight conditions, a typical commercial PV cell
with a surface area of 160 cm^2 (~25 in^2) will produce about 2 watts peak power. If the
sunlight intensity were 40 percent of peak, this cell would produce about 0.8 watts.

PV cells can be arranged in a series configuration to form a module, and modules can then be
connected in parallel-series configurations to form arrays. When connecting cells or modules
in series, they must have the same current rating to produce an additive voltage output, and
similarly, modules must have the same voltage rating when connected in parallel to produce
larger currents.

21
Solar Energy

Solar cells are typically combined into modules that hold about 40 cells; about 10 of these
modules are mounted in PV arrays (Array: A collection of photovoltaic modules electrically
wired together in one structure to produce a specific amount of power) that can measure up to
several meters on a side. These flat-plate PV arrays can be mounted at a fixed angle facing
south, or they can be mounted on a tracking device that follows the sun, allowing them to
capture the most sunlight over the course of a day. About 10 to 20 PV arrays can provide
enough power for a household; for large electric utility or industrial applications, hundreds of
arrays can be interconnected to form a single, large PV system.

2.6 Theory of Solar cells


Simple explanation

1. Photons in sunlight hit the solar panel and are absorbed by semiconducting materials,
such as silicon.
2. Electrons (negatively charged) are knocked loose from their atoms, allowing them to
flow through the material to produce electricity. Due to the special composition of
solar cells, the electrons are only allowed to move in a single direction. The
complementary positive charges that are also created (like bubbles) are called holes
and flow in the direction opposite of the electrons in a silicon solar panel.
3. An array of solar cells converts solar energy into a usable amount of direct current
(DC) electricity.

22
Solar Energy

Photo generation of charge carriers

When a photon hits a piece of silicon, one of three things can happen:

1. the photon can pass straight through the silicon — this (generally) happens for lower
energy photons,
2. the photon can reflect off the surface,
3. The photon can be absorbed by the silicon, if the photon energy is higher than the
silicon band gap value. This generates an electron-hole pair and sometimes heat,
depending on the band structure.

When a photon is absorbed, its energy is given to an electron in the crystal lattice. Usually
this electron is in the valence band, and is tightly bound in covalent bonds between
neighboring atoms, and hence unable to move far. The energy given to it by the photon
"excites" it into the conduction band, where it is free to move around within the
semiconductor. The covalent bond that the electron was previously a part of now has one
fewer electron — this is known as a hole. The presence of a missing covalent bond allows the
bonded electrons of neighboring atoms to move into the "hole," leaving another hole behind,
and in this way a hole can move through the lattice. Thus, it can be said that photons
absorbed in the semiconductor create mobile electron-hole pairs.

A photon need only have greater energy than that of the band gap in order to excite an
electron from the valence band into the conduction band. However, the solar frequency
spectrum approximates a black body spectrum at ~6000 K, and as such, much of the solar
radiation reaching the Earth is composed of photons with energies greater than the band gap
of silicon. These higher energy photons will be absorbed by the solar cell, but the difference
in energy between these photons and the silicon band gap is converted into heat (via lattice
vibrations — called phonons) rather than into usable electrical energy.

23
Solar Energy

Charge Carrier Separation

There are two main modes for charge carrier separation in a solar cell:

1. Drift of carriers, driven by an electrostatic field established across the device


2. Diffusion of carriers from zones of high carrier concentration to zones of low carrier
concentration (following a gradient of electrochemical potential).

In the widely used p-n junction solar cells, the dominant mode of charge carrier separation is
by drift. However, in non-p-n-junction solar cells (typical of the third generation solar cell
research such as dye and polymer solar cells), a general electrostatic field has been confirmed
to be absent, and the dominant mode of separation is via charge carrier diffusion.

The p-n Junction

The most commonly known solar cell is configured as a large-area p-n junction made from
silicon. As a simplification, one can imagine bringing a layer of n-type silicon into direct
contact with a layer of p-type silicon. In practice, p-n junctions of silicon solar cells are not
made in this way, but rather, by diffusing an n-type dopant into one side of a p-type wafer (or
vice versa).
If a piece of p-type silicon is placed in intimate contact with a piece of n-type silicon, then a
diffusion of electrons occurs from the region of high electron concentration (the n-type side
of the junction) into the region of low electron concentration (p-type side of the junction).
When the electrons diffuse across the p-n junction, they recombine with holes on the p-type
side. The diffusion of carriers does not happen indefinitely however, because of an electri
field which is created by the imbalance of charge immediately on either side of the junction
which this diffusion creates. The electric field established across the p-n junction creates a
diode that promotes charge flow, known as drift current, that opposes and eventually balances
out the diffusion of electron and holes. This region where electrons and holes have diffused
across the junction is called the depletion region because it no longer contains any mobile
charge carriers. It is also known as the "space charge region".

Connection to an External Load

Ohmic metal-semiconductor contacts are made to both the n-type and p-type sides of the
solar cell, and the electrodes connected to an external load. Electrons that are created on the
n-type side, or have been "collected" by the junction and swept onto the n-type side, may
travel through the wire, power the load, and continue through the wire until they reach the p-
type semiconductor-metal contact. Here, they recombine with a hole that was either created
as an electron-hole pair on the p-type side of the solar cell, or are swept across the junction
from the n-type side after being created there.
The voltage measured is equal to the difference in the quasi Fermi levels of the minority
carriers i.e. electrons in the p-type portion, and holes in the n-type portion.

24
3. Electrical Characteristics of Solar
Cells and Maximum Power Point

3.1 Equivalent circuit of a solar cell

To understand the electronic behavior of a solar cell, it is useful to create a model which is
electrically equivalent, and is based on discrete electrical components whose behavior is well
known

The equivalent circuit of a solar cell

The schematic symbol of a solar cell

An ideal solar cell may be modeled by a current source in parallel with a diode; in practice
no solar cell is ideal, so a shunt resistance and a series resistance component are added to the
model. The resulting equivalent circuit of a solar cell is shown on the FIGURE NUMBER.
Also shown, on the FIGURE NUMBER, is the schematic representation of a solar cell for use
in circuit diagrams.

25
Electrical Characteristics of Solar Cells and MPP

3.2 Characteristic equation

From the equivalent circuit it is evident that the current produced by the solar cell is equal to
that produced by the current source, minus that which flows through the diode, minus that
which flows through the shunt resistor.

I = IL − ID − ISH

Where

 I = output current (amperes)


 IL = photo generated current (amperes)
 ID = diode current (amperes)
 ISH = shunt current (amperes)

The current through these elements is governed by the voltage across them:

Vj = V + IRS

Where

 Vj = voltage across both diode and resistor RSH (volts)


 V = voltage across the output terminals (volts)
 I = output current (amperes)
 RS = series resistance (Ω)

By the Shockley diode equation, the current diverted through the diode is:

where
 I0 = reverse saturation current(amperes)
 n = diode ideality factor (1 for an ideal diode)
 q = elementary charge
 k = Boltzmann's constant
 T = absolute temperature
 For silicon at 25°C

volts.

By Ohm's law, the current diverted through the shunt resistor is:

26
Electrical Characteristics of Solar Cells and MPP

where

7.1 RSH = shunt resistance (Ω)

Substituting these into the first equation produces the characteristic equation of a solar cell,
which relates solar cell parameters to the output current and voltage:

An alternative derivation produces an equation similar in appearance, but with V on the left-
hand side. The two alternatives are identities; that is, they yield precisely the same results.

In principle, given a particular operating voltage V the equation may be solved to determine
the operating current I at that voltage. However, because the equation involves I on both sides
in a transcendental function the equation has no general analytical solution. However, even
without a solution it is physically instructive. Furthermore, it is easily solved using numerical
methods. (A general analytical solution to the equation is possible using Lambert's W
function, but since Lambert's W generally itself must be solved numerically this is a
technicality.)

Since the parameters I0, n, RS, and RSH cannot be measured directly, the most common
application of the characteristic equation is nonlinear regression to extract the values of these
parameters on the basis of their combined effect on solar cell behavior.

Open-circuit voltage and short-circuit current

When the cell is operated at open circuit, I = 0 and the voltage across the output terminals is
defined as the open-circuit voltage. Assuming the shunt resistance is high enough to neglect
the final term of the characteristic equation, the open-circuit voltage VOC is:

Similarly, when the cell is operated at short circuit, V = 0 and the current I through the
terminals is defined as the short-circuit current. It can be shown that for a high-quality solar
cell (low RS and I0, and high RSH) the short-circuit current ISC is:

The values of I0, RS, and RSH are dependent upon the physical size of the solar cell. In
comparing otherwise identical cells, a cell with twice the surface area of another will, in

27
Electrical Characteristics of Solar Cells and MPP

principle, have double the I0 because it has twice the junction area across which current can
leak. It will also have half the RS and RSH because it has twice the cross-sectional area
through which current can flow. For this reason, the characteristic equation is frequently
written in terms of current density, or current produced per unit cell area:

Where

 J = current density (amperes/cm2)


 JL = photo generated current density (amperes/cm2)
 Jo= reverse saturation current density (amperes/cm2)
 rS = specific series resistance (Ω-cm2)
 rSH = specific shunt resistance (Ω-cm2)

This formulation has several advantages. One is that since cell characteristics are referenced
to a common cross-sectional area they may be compared for cells of different physical
dimensions. While this is of limited benefit in a manufacturing setting, where all cells tend to
be the same size, it is useful in research and in comparing cells between manufacturers.
Another advantage is that the density equation naturally scales the parameter values to similar
orders of magnitude, which can make numerical extraction of them simpler and more
accurate even with naive solution methods.

A practical limitation of this formulation is that as cell sizes shrink, certain parasitic effects
grow in importance and can affect the extracted parameter values. For example,
recombination and contamination of the junction tend to be greatest at the perimeter of the
cell, so very small cells may exhibit higher values of J0 or lower values of rSH than larger
cells that are otherwise identical. In such cases, comparisons between cells must be made
cautiously and with these effects in mind.

3.3 I-V Curve of Solar Cell

PV cells can be modeled as a current source in parallel with a diode. When there is no light
present to generate any current, the PV cell behaves like a diode. As the intensity of incident
light increases, current is generated by the PV cell, as illustrated in Figure.

Curve of PV Cell and Associated Electrical Diagram

28
Electrical Characteristics of Solar Cells and MPP

In an ideal cell, the total current I is equal to the current Iℓ generated by the photoelectric
effect minus the diode current ID, according to the equation:

where I0 is the saturation current of the diode, q is the elementary charge 1.6x10-19 Coulombs,
k is a constant of value 1.38x10-23J/K, T is the cell temperature in Kelvin, and V is the
measured cell voltage that is either produced (power quadrant) or applied (voltage bias).

The I-V curve of an illuminated PV cell has the shape shown in Figure as the voltage across
the measuring load is swept from zero to VOC..

29
4. DC-DC Converters and
Implementation of MPPT
DC to DC converters are electronic circuits which convert a DC voltage from one voltage
level to another. It is a class of power converter.

4.1 DC-DC Converter Types

DC-DC converters are generally classified on the basis of their possible input-output relations

Boost Converter

A boost converter (step-up converter) is a power converter with an output DC voltage greater
than its input DC voltage. The Figure below shows basic schematic of Boost Converter

Buck Converter

A buck converter is a step-down DC to DC converter. Its design is similar to the step-up


boost converter, and like the boost converter it is a switched-mode power supply that uses
two switches (a transistor and a diode) and an inductor. The figure below shows its
schematic.

30
DC-DC Converters and Implementation of MPPT

Buck-Boost Converter

The buck–boost converter is a type of DC-DC converter that has an output voltage magnitude
that is either greater than or less than the input voltage magnitude. It is a switch mode power
supply with a similar circuit topology to the boost converter and the buck converter. The
output voltage is adjustable based on the duty cycle of the switching transistor.

4.2 Buck Converter

Buck converter can operate in continuous and discontinuous mode. We have worked in
continuous mode

A buck converter operates in continuous mode if the current through the inductor (IL) never
falls to zero during the commutation cycle. In this mode, the operating principle is described
by the chronogram in fig.

 When the switch pictured above is closed (On-state, top of figure 2), the voltage
across the inductor is VL = Vi − Vo. The current through the inductor rises linearly. As
the diode is reverse-biased by the voltage source V, no current flows through it;

31
DC-DC Converters and Implementation of MPPT

 When the switch is opened (off state, bottom of figure 2), the diode is forward biased.
The voltage across the inductor is VL = − Vo (neglecting diode drop). The current IL
decreases.

It can be shown that the input-output relation for continuous mode is:

Vout = (Duty cycle of switch) * Vin

4.3 Our Implementation of MPPT

In our circuit, if inductor has sufficiently large value, converter will operate in continuous
mode and following relation will hold

Panel Voltage = (Duty Cycle of Switch) * (Battery Voltage)

In this way, the Voltage of the panel can be controlled by varying Duty Cycle of switch as
batter voltage remains almost constant.

32
5. Sun Tracking
A sun tracker or solar tracker is a device for orienting a day lighting reflector, solar
photovoltaic panel or concentrating solar reflector or lens toward the sun.

5.1 Need of Sun Tracking


A solar tracker is a device for orienting a day lighting reflector, solar photovoltaic panel or
concentrating solar reflector or lens toward the sun. The sun's position in the sky varies both
with the seasons and time of day as the sun moves across the sky. Solar powered equipment
works best when pointed at or near the sun, so a solar tracker can increase the effectiveness of
such equipment over any fixed position, at the cost of additional system complexity. There
are many types of solar trackers, of varying costs, sophistication, and performance. One well-
known type of solar tracker is the heliostat, a movable mirror that reflects the moving sun to a
fixed location, but many other approaches are used as well.

Tracker mount types

Solar trackers may be active or passive and may be single axis or dual axis. Single axis
trackers usually use a polar mount for maximum solar efficiency. Single axis trackers will
usually have a manual elevation (axis tilt) adjustment on a second axis which is adjusted on
regular intervals throughout the year. Compared to a fixed mount, a single axis tracker
increases annual output by approximately 30%, and a dual axis tracker an additional 6%.
There are two types of dual axis trackers, polar and altitude-azimuth.

Polar
Polar trackers have one axis aligned to be roughly parallel to the axis of rotation of the earth
around the north and south poles—hence the name polar. (With telescopes, this is called
equatorial mount.)

Single axis tracking is often used when combined with time-of-use metering, since strong
afternoon performance is particularly desirable for grid-tied photovoltaic systems, as
production at this time will match the peak demand time for summer season air-conditioning.
A fixed system oriented to optimize this limited time performance will have a relatively low

33
Sun Tracking

annual production. The polar axis should be angled towards due north, and the angle between
this axis and the vertical should be equal to your latitude.

Simple polar trackers with single axis tracking may also have an adjustment along a second
axis: the angle of declination. This allows you to angle the panel to face the sun when it is
higher in the sky (and further northward) in the summer, and to face it lower in the sky (and
further southward) in the winter. It might be set with manual or automated adjustments,
depending on your polar-tracking device. If one is not planning on adjusting this angle of
declination at all during the year, it is normally set to zero degrees, facing your panel straight
out perpendicular to the polar axis, as that is where the mean path of the sun is found.
Occasional or continuous adjustments to the declination compensate for the northward and
southward shift in the sun's path through the sky as it moves through the seasons (and around
the ecliptic) over the course of the year.

When the manual method is used for adjustment of the declination, it should be done at least
twice a year: Once at the autumnal equinox to establish the best position for the winter, and a
second adjustment on the vernal equinox, to optimize it for the summer. The sun's declination
at the spring equinox is 0o. It moves up to 22.5o in the summer, then drifts back down through
0o at fall equinox, and down to -22.5o in the winter. So, for example, you might choose to set
the declination at 15o or 20o as a reasonably optimal position for the summer months.

Horizontal axle

Several manufacturers can deliver single axis horizontal trackers which may be oriented by
either passive or active mechanisms, depending upon manufacturer. In these, a long
horizontal tube is supported on bearings mounted upon pylons or frames. The axis of the tube
is on a North-South line. Panels are mounted upon the tube, and the tube will rotate on its
axis to track the apparent motion of the sun through the day. Since these do not tilt toward the
equator they are not especially effective during winter mid day (unless located near the
equator), but add a substantial amount of productivity during the spring and summer seasons

When the solar path is high in the sky. These devices are less effective at higher latitudes.
The principal advantage is the inherent robustness of the supporting structure and the
simplicity of the mechanism. Since the panels are horizontal, they can be compactly placed
on the axle tube without danger of self-shading and are also readily accessible for cleaning.

34
Sun Tracking

For active mechanisms, a single control and motor may be used to actuate multiple rows of
panels.

Vertical axle

A single axis tracker may be constructed that pivots only about a vertical axle, with the
panels either vertical, at a fixed, adjustable, or tracked elevation angle. Such trackers with
fixed or (seasonably) adjustable angles are suitable for high latitudes, where the apparent
solar path is not especially high, but which leads to long days in Summer, with the sun
traveling through a long arc. This method has been used in the construction of a cylindrical
house in Austria (latitude above 45 degrees north) that rotates in its entirety to track the sun,
with vertical panels mounted on one side of the building.

Altitude-azimuth

A type of mounting that supports the weight of the solar tracker and allows it to move in two
directions to locate a specific target. One axis of support is horizontal (called the altitude) and
allows the telescope to move up and down. The other axis is vertical (called the azimuth) and
allows the telescope to swing in a circle parallel to the ground. This makes it easy to position
the telescope: swing it around in a circle and then lift it to the target. However, tracking an
object as the Earth turns is more complicated. The telescope needs to be adjusted in both
directions while tracking, which requires a computer to control the telescope.

5.2 How to Track

Drive Types
Active tracker

Active trackers use motors and gear trains to direct the tracker as commanded by a controller
responding to the solar direction.

35
Sun Tracking

Active two-axis trackers are also used to orient heliostats - movable mirrors that reflect
sunlight toward the absorber of a central power station. As each mirror in a large field will
have an individual orientation these are controlled programmatically through a central
computer system, which also allows the system to be shut down when necessary.

Light-sensing trackers typically have two photo sensors, such as photodiodes, configured
differentially so that they output a null when receiving the same light flux. Mechanically,
they should be Omni directional (i.e. flat) and are aimed 90 degrees apart. This will cause the
steepest part of their cosine transfer functions to balance at the steepest part, which translates
into maximum sensitivity.

Since the motors consume energy, one wants to use them only as necessary. So instead of a
continuous motion, the heliostat is moved in discrete steps. Also, if the light is below some
threshold there would not be enough power generated to warrant reorientation. This is also
true when there is not enough difference in light level from one direction to another, such as
when clouds are passing overhead. Consideration must be made to keep the tracker from
wasting energy during cloudy periods.

Passive tracker

Passive trackers use a low boiling point compressed gas fluid that is driven to one side or the
other (by solar heat creating gas pressure) to cause the tracker to move in response to an
imbalance. As this is a non-precision orientation it is unsuitable for certain types of
concentrating photovoltaic collectors but works fine for common PV panel types. These will
have viscous dampers to prevent excessive motion in response to wind gusts.
Shader/reflectors are used to reflect early morning sunlight to "wake up" the panel and tilt it
toward the sun, which can take nearly an hour. The time to do this can be greatly reduced by
adding a self-releasing tie down that positions the panel slightly past the zenith (so that the
fluid does not have to overcome gravity) and using the tie down in the evening. (A slack-
pulling spring will prevent release in windy overnight conditions.)
The term "passive tracker" is also used for photovoltaic modules that include a hologram
behind stripes of photovoltaic cells. That way, sunlight passes through the transparent part of
the module and reflects on the hologram. This allows sunlight to hit the cell from behind,
thereby increasing the module's efficiency. Also, the module does not have to move since the
hologram always reflects sunlight from the correct angle towards the cells.

Chronological tracker

A chronological tracker counteracts the Earth's rotation by turning at an equal rate as the
earth, but in the opposite direction. Actually the rates aren't quite equal, because as the earth
goes around the sun, the position of the sun changes with respect to the earth by 360° every
year or 365.24 days. A chronological tracker is a very simple yet potentially a very accurate
solar tracker specifically for use with a polar mount (see above). The drive method may be as
simple as a gear motor that rotates at a very slow average rate of one revolution per day (15
degrees per hour). In theory the tracker may rotate completely, assuming there is enough
clearance for a complete rotation, and assuming that twisting wires are not an issue, such as
with a solar concentrator, or the tracker may be reset each day to avoid these issues.
Alternatively, an electronic controller may be used, with a real time clock that is used to infer

36
Sun Tracking

the "solar time" (hour angle). Tracking adjustments can be made incrementally or
continuously.

5.3 Algorithms for Sun Tracking

Time Based Algorithm

In time based algorithm Panels are tracked according to tome. So structure initial must be fix
to some specific position to track sun correctly. In this technique sun path data accusing to
time is stored in the forms of tables and according to current time panels position is adjusted.
Usually tables are for 4 month each and after 4 months driver controller is up dated.

Real Time Tracking

In real time sun tracking sun is tracked by sensors. There are some algorithms for solar sun
tracking. Some are explained below

Perturb and Observe

The most commonly used MPPT algorithm is Perturb And Observe (P&O), due to its ease
of implementation in its basic form [I]. Figure 4 shows the P vs. V curve of a PV array,
which has a global maximum at the MPP. Thus, if the operating voltage of the PV array
is perturbed in a given direction and dP/dV > 0, it is known that the perturbation moved
the array's operating point toward the MPP. The P&O algorithm would then continue to
perturb the PV array voltage in the same direction. If dPIdV 0, then the change in operating
point moved the PV array away from the MPP, and the P&O algorithm reverses the
direction of the perturbation. A problem with P&O is that it oscillates around the MPP in
steady state operation. It also can track in the wrong direction, away from the MPP,
under rapidly increasing or decreasing irradiance levels .

37
Sun Tracking

There are several variations of the basic P&O that have been designed to minimize
these drawbacks. These include using an average of several samples of the array power
and dynamically adjusting the magnitude of the perturbation of the PV operating point.

5.4 Sensors
LDR

A photo resistor or light dependent resistor or cadmium sulfide (CdS) cell is a resistor whose
resistance decreases with increasing incident light intensity. It can also be referenced as a
photoconductor.

A photo resistor is made of a high resistance semiconductor. If light falling on the device is of
high enough frequency, photons absorbed by the semiconductor give bound electrons enough
energy to jump into the conduction band. The resulting free electron (and its hole partner)
conduct electricity, thereby lowering resistance.

A photoelectric device can be either intrinsic or extrinsic. An intrinsic semiconductor has its
own charge carriers and is not an efficient semiconductor, e.g. silicon. In intrinsic devices the
only available electrons are in the valence band, and hence the photon must have enough
energy to excite the electron across the entire band gap. Extrinsic devices have impurities,
also called dopants, added whose ground state energy is closer to the conduction band; since
the electrons do not have as far to jump, lower energy photons (i.e., longer wavelengths and
lower frequencies) are sufficient to trigger the device. If a sample of silicon has some of its
atoms replaced by phosphorus atoms (impurities), there will be extra electrons available for
conduction. This is an example of an extrinsic semiconductor.

Photo Diodes

A photodiode is a type of photo detector capable of converting light into either current or
voltage, depending upon the mode of operation.

Photodiodes are similar to regular semiconductor diodes except that they may be either
exposed (to detect vacuum UV or X-rays) or packaged with a window or optical fiber
connection to allow light to reach the sensitive part of the device. Many diodes designed for
use specifically as a photodiode will also use a PIN junction rather than the typical PN
junction.
A photodiode is a PN junction or PIN structure. When a photon of sufficient energy strikes
the diode, it excites an electron, thereby creating a mobile electron and a positively charged
electron hole. If the absorption occurs in the junction's depletion region, or one diffusion
length away from it, these carriers are swept from the junction by the built-in field of the
depletion region. Thus holes move toward the anode, and electrons toward the cathode, and a
photocurrent is produced.

38
Sun Tracking

PV Cells

A solar cell or photovoltaic cell is a device that converts light directly into electricity by the
photovoltaic effect. Sometimes the term solar cell is reserved for devices intended
specifically to capture energy from sunlight, while the term photovoltaic cell is used when the
light source is unspecified. Assemblies of cells are used to make solar panels, solar modules,
or photovoltaic arrays. Photovoltaic is the field of technology and research related to the
application of solar cells in producing electricity for practical use. The energy generated this
way is an example of solar energy

5.5 Our Structure for Solar Tracking


Azimuth Tracking

39
Sun Tracking

Altitude Tracking

40
6. Inverters
Electrical Inverter is a device that converts direct current to alternating current

6.1 Circuit Topologies used in inverters


Push-Pull Configuration

A push–pull converter is a type of DC to DC converter that uses a transformer to change the


voltage of a DC power supply. The transformer's ratio is arbitrary but fixed; however, in
many circuit implementations the duty cycle of the switching action can be varied to effect a
range of voltage ratios. The primary advantages of push–pull converters are their simplicity
and ability to scale up to high power throughput, earning them a place in industrial DC power
applications.

Bridge Configuration

An H-bridge is an electronic circuit which enables a voltage to be applied across a load in


either direction. These circuits are often used in robotics and other applications to allow DC
motors to run forwards and backwards. H-bridges are available as integrated circuits, or can
be built from discrete components.

41
Inverters

6.2 Output Waveform

The switch in the simple inverter described above produces a square voltage waveform as
opposed to the sinusoidal waveform that is the usual waveform of an AC power supply.
Using Fourier analysis, periodic waveforms are represented as the sum of an infinite series of
sine waves. The sine wave that has the same frequency as the original waveform is called the
fundamental component. The other sine waves, called harmonics, that are included in the
series have frequencies that are integral multiples of the fundamental frequency.
The quality of the inverter output waveform can be expressed by using the Fourier analysis
data to calculate the total harmonic distortion (THD). The total harmonic distortion is the
square root of the sum of the squares of the harmonic voltages divided by the fundamental
voltage:

The quality of output waveform that is needed from an inverter depends on the characteristics
of the connected load. Some loads need a nearly perfect sine wave voltage supply in order to
work properly. Other loads may work quite well with a square wave voltage.

It is difficult to produce perfect sine wave using inverter, however different waveforms exist
which have less THD and have characteristics similar to sine wave. These waveforms include
Quasi-square, Step Sine, and Sinusoidal PWM

42
Inverters

6.3 Three-phase inverters

Three-phase inverters are used for variable-frequency drive applications and for high power
applications such as HVDC power transmission. A basic three-phase inverter consists of
three single-phase inverter switches each connected to one of the three load terminals. For the
most basic control scheme, the operation of the three switches is coordinated so that one
switch operates at each 60 degree point of the fundamental output waveform. This creates a
line-to-line output waveform that has six steps. The six-step waveform has a zero-voltage
step between the positive and negative sections of the square-wave such that the harmonics
that are multiples of three are eliminated as described above. When carrier-based PWM
techniques are applied to six-step waveforms, the basic overall shape, or envelope, of the
waveform is retained so that the 3rd harmonic and its multiples are cancelled.

To construct inverters with higher power ratings, two six-step three-phase inverters can be
connected in parallel for a higher current rating or in series for a higher voltage rating. In
either case, the output waveforms are phase shifted to obtain a 12-step waveform. If
additional inverters are combined, an 18-step inverter is obtained with three inverters etc.
Although inverters are usually combined for the purpose of achieving increased voltage or
current ratings, the quality of the waveform is improved as well.

6.4 Control Signals


The control Signal used for the driving of the switching devices are as follows
 Square wave.
 Step Sine.
 PWM.
 Cosi Square

43
7. Commercial Implementation of
Solar System
There are two types of solar system implementation at commercial level

 Grid Tied Systems


 Off Grid systems

7.1 Grid-Tied systems

Grid-tie systems generate electricity, sending this energy back to your utility company's
power grid. In effect, this means the utility company will be paying you to produce energy for
them, since the energy you produce counts against the energy your home or business uses.

Your solar panels will produce DC (Direct Current) electricity. This electricity will be run
through an inverter to produce AC (Alternating Current) electricity. This energy is then run
into your AC power panel, which feeds energy back to your utility companies power grid. If
your solar power array produced enough electricity, your utility meter would begin to run
backward!

44
Commercial Implementation of Solar System

The main components of an Grid-Tie system

Solar Panels You'll need solar panels to collect the solar energy and convert this to DC
power. The number and type of solar panels will determine how much energy
you can produce, as will your geographic location.
Combiner This box gathers all of the Solar Panel connections.
Box
DC Breaker Your array's breaker safely shuts down your solar power system at a moment's
Box notice, allowing for safe maintenance, repair, and inspection.
Inverter Inverters take Direct Current power and convert it to household (AC) power.
Grid A grid disconnect allows you to stop the flow of electricity between your solar
Disconnect power system and your electrical system. This provides for the safe
maintenance of electrical and utility systems.

Grid-Tied system with Battery Backup

When sun is shining, the PV panels generate power, which reduces the consumption of
electricity from the grid and cuts electric bills accordingly. The required balance of the power
is automatically provided by the utility. Under normal conditions, a small portion of the
power from the grid is used to keep the storage batteries charged. If the PV system generates
more electricity than your house is using, the system will feed the excess of the power
Back to the grid after the batteries are fully charged and spin your electric meter backwards.

45
Commercial Implementation of Solar System

Grid-Tied system without Battery Backup

At night or during inclement weather all the electricity is supplied by the utility. During the
daylight hours, the PV system generates some power, offsetting the consumption of
electricity from the utility and cutting electric bills. The balance of the power required by
your loads is automatically drawn from the utility grid. If the PV panels are producing more
electricity than you are using, the system will feed the surplus of the power back to the grid.
It may spin your electric meter backwards, further reducing your monthly bill

7.2 Off-Grid solar systems

Main advantage of off grid system is that the system is independent so free from power shut
downs. But as all load is taking energy from batteries so cost of system battery backup is very
high.

7.3 Solar Battery Backup - The Pros and Cons of Solar Battery Systems

Deciding whether or not to get a battery backup for your grid-tied system may not be so easy
as the advantages and disadvantages are not always obvious. A solar battery array will add
considerable expense to your system - how can you decide if it is really necessary or
appropriate for your situation?

A grid-tied system without batteries is much simpler and cheaper, as well as being more
efficient (mainly due to the losses involved in charging the batteries). Excess energy is fed
back into the grid, effectively using the grid itself as storage. It is important to note however
that these simple systems do not provide a backup source in the event of a general power
failure, even in sunny conditions.

Using solar battery backup means the system can continue to function in the event of a grid
power failure, even at night. Because a battery based system is less efficient it may supply up
to 10% less energy, and the expensive batteries will have to be replaced probably every ten
years or so. If your grid is quite reliable it is probably not worth the additional expense. If
however you have an unreliable grid, you may well consider the additional expense of a
battery backup system to be very worthwhile. In the event of a power failure a battery-backed
system is usually not designed to support every load in your home, and usually only the most
critical devices will be connected to the backup system. Heating, air conditioning and other
high power loads are generally not supported as supporting such loads from a battery backup
would be very expensive indeed.

If your utilities are very unreliable and not available for long periods of time then you may
even want to consider complete alternatives to electricity. Solar water heating can be very
effective if the climate is appropriate and it may be possible to substitute the higher power
electrical devices (such as for heating and cooking) with gas-fired appliances.

46
8. Final Implementation of our System
8.1 Solar Panel
We are using amporphous solar panel which we have imported from Canada. The cost of that is
$70 exclusive of GST and excise duty. This panel has following technical data.

Given Data
Power Rating: Up to 10 Watts
Current: Up to 700 mAmps @ 15Volts
Dimensions: (L x W x H) 26" x 14" x 2 3/4"
66 x 36 x 7 cm
Weight: 9.2 lbs
Made in China

Measured Data
OpenCircuit Voltage: 24V
Short Circuit Current: 500mA
Max Power: 6W

We first bougth a crystalline cell from local market to check the characteristics of the
solar cells but we found them marked deviated from the ideal characteristics they have a
large temperature effect on them which reduceses their efficiency drastically. After that
we make a panel of around 3W from six 0.5W amorphous cells also bought from the
local market, they were also not upto the standards.

Features
 Solar Panel includes blocking diode to prevent reverse current.
 It is allowable to operate vehicle while Solar Panel is connected, however, when driving
it is
 recommended to secure Solar Panel. Not doing so may be hazardous and is not
recommended.
 The 10W Solar Panel is weatherproof and can safely operate in most weather conditions.
 Testing of the Solar Panel can be done with the green LED voltage tester, lumination of
the light will
 indicate that the panel is operating at the proper voltage. To operate the green LED light,
connect
 light to the panel and place panel in a sunny area.

47
Final Implementation of our System

48
Final Implementation of our System

8.2 DC-DC Converter


The Open Circuit Voltage of the panel is 24V and its MPP is around 16V so we decided to use a
battery of 12V for our purposes. As we always need to step down the voltage hence we only
require buck converter for our system. Our buck takes power on MPP from panel and provide it
to 12V. The switch used in buck converter has it’s ends on 12V and 16V but the PWM signal
from microprocessor could only provide 5V maximum for the gate driving. Hence simple NPN
or NMOS switch could not be used. To over come that problem we designed the circuit as
shown.

Inductor

As the frequency of our PWM signal is around 25kHz so a normal inductor would not work.
First we tried inductor with EI striup core but its response is not satisfactory. Hence we designed
inductor with EE type ferrous core. The inductance of our designed inductor is 700mH.
Moreover we taped it during winding so that different inductances could be used as required.

Switch

The main switching service is PNP B772 transistor with following specifications
Reverse Voltage: 30V
Peak Current: 3A

8.3 Sun tracking

Our designed and manufactured structure is capable of Altitude-azimuth. It has two DC motors
equipped with proper gears. The gears provide a high torque and low speed essential for solar
tracking. The main spporting part of the structure is made up of iron wile the mobile parts has
been carved out of Teflon blocks, panel holding fram is composed of aluminum for its light
weight in addition to this two sheets of Bakelite are added for the support motors and controlling
hardware.
LDRs are used for the intensity comparison, tow set has been used consisting of up, down sensor
and clockwise and anticlockwise sensors.

8.4 Control Part


Hardware

The main controlling device is PIC16F877A. Panel current and panel voltage is properly scaled
and provided on the analogue pins of the microcontroller which are also attached to its internal
ADC. Microcontroller then update it’s registers for PWM signal provided to the buck switching
circuit based on the Algorithm.
Microcontroller is also being used for the local display of values on LCD. It is also used for the
transferring of data to the computer using RS232 protocol.
LDRS are also connected to the analogue pins of the microcontroller. Microcontroller also
generating the base signal of the H-bridges deriving motors for altitude and azimuth directions.

49
Final Implementation of our System

Software

The MPPT algorithm we are using is P&O (Perturb and observe) as explained earlier and its
code is given in Appendix. The Code in Appendix also contains files which are displaying data
on LCD and Sending data to computer. The code also contains the files for the solar tracking.
The flow chart of our MPPT algorithm is shown in following flow chart.

8.5 Transformer

Transformer we designed and manufactured has following Specifications.

Type: Center taped.


HT: 220V, 6 A, SWG=16, N=220
LT: 24V, 50 A, SWG=8, N=26
VA: 1000
No-load Current: 0.75A
Core: EI Strip.
Dimensions of middle limb: 2”x 3”

50
Final Implementation of our System

8.6 Battery

We are using Lead Acid battery for the purposes of Energy Storage the battery we are using has
following technical data
Voltage: 12V
Rating: 108Ah

51
Final Implementation of our System

8.7 Inverter

As we have a center tapped transformer with LT of 24Vand using only one 12V battery, hence
only push pull topology could be implemented. For the switching purposes NPN transistors
75NF75 is suited for our case with maximum reverse voltage rating of 75V and current rating of
75V. The controlling signal for the driving of transistors is given trough an multi-vibratory
astable IC (4047).

52
Final Implementation of our System

8.8 Schematics
Sheet 1

53
Final Implementation of our System

Sheet 2

54
Final Implementation of our System

Inverter

55
Final Implementation of our System

8.9 PCB Layout


Main Controll Board

Inverter

56
57
A. Batteries
A.1 Introduction

In electronics, a battery or voltaic cell is a combination of many electrochemical Galvanic


cells of identical type to store chemical energy and to deliver higher voltage or higher current
than with single cells.

The battery cells create a voltage difference between the terminals of each cell and hence to
its combination in battery. When an external electrical circuit is connected to the battery, then
the battery drives electrons through the circuit and electrical work is done. Since the
invention of the first Voltaic pile in 1800 by Alessandro Volta, the battery has become a
common power source for many household and industrial applications, and is now a multi-
billion dollar industry.

A battery is a device that converts chemical energy directly to electrical energy. It consists of
one or more voltaic cells; each voltaic cell consists of two half cells connected in series by a
conductive electrolyte containing anions and cations. One half-cell includes electrolyte and
the electrode to which anions (negatively-charged ions) migrate, i.e. the anode or negative
electrode; the other half-cell includes electrolyte and the electrode to which cations
(positively-charged ions) migrate, i.e. the cathode or positive electrode. In the redox reaction
that powers the battery, reduction (addition of electrons) occurs to cations at the cathode,
while oxidation (removal of electrons) occurs to anions at the anode. The electrodes do not
touch each other but are electrically connected by the electrolyte, which can be either solid or
liquid. Many cells use two half-cells with different electrolytes. In that case each half-cell is
enclosed in a container, and a separator that is porous to ions but not the bulk of the
electrolytes prevents mixing.

Each half cell has an electromotive force (or emf), determined by its ability to drive electric
current from the interior to the exterior of the cell. The net emf of the battery is the difference
between the emfs of its half-cells, as first recognized by Volta. Therefore, if the electrodes
have emfs and , then the net emf is ; in other words, the net emf is difference
between the reduction potentials of the half-reactions.

The electrical driving force or across the terminals of a battery is known as the
terminal voltage (difference) and is measured in volts. The terminal voltage of a battery that
is neither charging nor discharging is called the open-circuit voltage and equals the emf of the
battery. Because of internal resistance, the terminal voltage of a battery that is discharging is
smaller in magnitude than the open-circuit voltage and the terminal voltage of a battery that is
charging exceeds the open-circuit voltage. An ideal battery has negligible internal resistance,
so it would maintain a constant terminal voltage of until exhausted, then dropping to zero.

58
Source Code

If such a battery maintained 1.5 volts and stored a charge of one Coulomb then on complete
discharge it would perform 1.5 Joule of work. In actual batteries, the internal resistance
increases under discharge, and the open circuit voltage also decreases under discharge. If the
voltage and resistance are plotted against time, the resulting graphs typically are a curve; the
shape of the curve varies according to the chemistry and internal arrangement employed.

As stated above, the voltage developed across a cell’s terminals depends on the energy
release of the chemical reactions of its electrodes and electrolyte. Alkaline and carbon-zinc
cells have different chemistries but approximately the same emf of 1.5 volts; likewise NiCd
and NiMH cells have different chemistries, but approximately the same emf of 1.2 volts. On
the other hand the high electrochemical potential changes in the reactions of lithium
compounds give lithium cells emfs of 3 volts or more.

A.2 Categories of Batteries

Batteries are classified into two broad categories, each type with advantages and
disadvantages.

 Primary batteries irreversibly (within limits of practicality) transform chemical


energy to electrical energy. When the initial supply of reactants is exhausted, energy
cannot be readily restored to the battery by electrical means.
 Secondary batteries can be recharged; that is, they can have their chemical reactions
reversed by supplying electrical energy to the cell, restoring their original
composition.

Historically, some types of primary batteries used, for example, for telegraph circuits, were
restored to operation by replacing the components of the battery consumed by the chemical
reaction. Secondary batteries are not indefinitely rechargeable due to dissipation of the active
materials, loss of electrolyte and internal corrosion.

Primary batteries

Primary batteries can produce current immediately on assembly. Disposable batteries, also
called primary cells, are intended to be used once and discarded. These are most commonly
used in portable devices that have low current drain, are only used intermittently, or are used
well away from an alternative power source, such as in alarm and communication circuits
where other electric power is only intermittently available. Disposable primary cells cannot
be reliably recharged, since the chemical reactions are not easily reversible and active
materials may not return to their original forms. Battery manufacturers recommend against
attempting to recharge primary cells.

Common types of disposable batteries include zinc-carbon batteries and alkaline batteries.
Generally, these have higher energy densities than rechargeable batteries, but disposable
batteries do not fare well under high-drain applications with loads under 75 ohms (75 Ω).

59
Source Code

Secondary batteries

Secondary batteries must be charged before use; they are usually assembled with active
materials in the discharged state. Rechargeable batteries or secondary cells can be recharged
by applying electrical current, which reverses the chemical reactions that occur during its use.
Devices to supply the appropriate current are called chargers or rechargers.

The oldest form of rechargeable battery is the lead-acid battery, a type of wet cell. This
battery is notable in that it contains a liquid in an unsealed container, requiring that the
battery be kept upright and the area be well ventilated to ensure safe dispersal of the
hydrogen gas produced by these batteries during overcharging. The lead-acid battery is also
very heavy for the amount of electrical energy it can supply. Despite this, its low
manufacturing cost and its high surge current levels make its use common where a large
capacity (over approximately 10Ah) is required or where the weight and ease of handling are
not concerns.

A common form of the lead-acid battery is the modern car battery, which can generally
deliver a peak current of 450 amperes. An improved type of liquid electrolyte battery is the
sealed valve regulated lead acid (VRLA) battery, popular in the automotive industry as a
replacement for the lead-acid wet cell. The VRLA battery uses an immobilized sulfuric acid
electrolyte, reducing the chance of leakage and extending shelf life. VRLA batteries have the
electrolyte immobilized, usually by one of two means:

 Gel batteries (or "gel cell") contain a semi-solid electrolyte to prevent spillage.
 Absorbed Glass Mat (AGM) batteries absorb the electrolyte in a special fiberglass
matting

Other portable rechargeable batteries include several "dry cell" types, which are sealed units
and are therefore useful in appliances such as mobile phones and laptop computers. Cells of
this type (in order of increasing power density and cost) include nickel-cadmium (NiCd),
nickel metal hydride (NiMH) and lithium-ion (Li-ion) cells. By far, Li-ion has the highest
share of the dry cell rechargeable market. Meanwhile, NiMH has replaced NiCd in most
applications due to its higher capacity, but NiCd remains in use in power tools, two-way
radios, and medical equipment.

60
Source Code

61
B. Transformer Design
Induce voltage according to faradays law is:

Ø
= = = . Ø
√ √

The apparent transformer power Pt is sum of the input power Pi and output power Po

= +

The Voltage in transformer is given by

= Ø
So
= Ø
And
= Ø
We also know
= +

= =

Ac = Cross sectional Area fo the flux path and B


Number of ampere turns (NI) is related to J as follows

=
Wa = Window area
Ku = fillfactor
= =
=
Where x and Kj is constant and depends upon core type. For EI core at 50oC
x = -0.13
Kj = 534

=
And

=

62
C. Inductor Design
The DC inductor is one of the most important component in power converter.
The inductance L is given by
μ μ
= = ∗
Or it can be written as
μ
= = ∗
+ +μ
As We know
= =
Ø
Gives

= =
Ø
So

= =
Substituting J we get


=
The number of turns will be

63
D. Source Code
We used PIC16F877A microcontroller for controlling all the operations in project. The
language used for programming is C and compiler used is CCS PCWH C Compiler. We
edited header file to add some register names according to datasheet.
The Source Code is divided into many files. Below are all the files and the code contained in
them.

D.1 16F877A_modified.h

/********************************************************
* *
* This portion of header file is from CCS C Compiler *
* *
********************************************************/

#ifndef _16F877A_h
#define _16F877A_h
//////// Standard Header file for the PIC16F877A device
////////////////
#device PIC16F877A
#nolist
//////// Program memory: 8192x14 Data RAM: 367 Stack: 8
//////// I/O: 33 Analog Pins: 8
//////// Data EEPROM: 256
//////// C Scratch area: 77 ID Location: 2000
//////// Fuses:
LP,XT,HS,RC,NOWDT,WDT,NOPUT,PUT,PROTECT,DEBUG,NODEBUG
//////// Fuses:
NOPROTECT,NOBROWNOUT,BROWNOUT,LVP,NOLVP,CPD,NOCPD,WRT_50%
//////// Fuses: NOWRT,WRT_5%,WRT_25%
////////
//////////////////////////////////////////////////////////////
//// I/O
// Discrete I/O Functions: SET_TRIS_x(), OUTPUT_x(),
INPUT_x(),
// PORT_B_PULLUPS(), INPUT(),
// OUTPUT_LOW(), OUTPUT_HIGH(),
// OUTPUT_FLOAT(), OUTPUT_BIT()
// Constants used to identify pins in the above are:

#define PIN_A0 40
#define PIN_A1 41
#define PIN_A2 42
#define PIN_A3 43
#define PIN_A4 44
#define PIN_A5 45

#define PIN_B0 48

64
#define PIN_B1 49
#define PIN_B2 50
#define PIN_B3 51
#define PIN_B4 52
#define PIN_B5 53
#define PIN_B6 54
#define PIN_B7 55

#define PIN_C0 56
#define PIN_C1 57
#define PIN_C2 58
#define PIN_C3 59
#define PIN_C4 60
#define PIN_C5 61
#define PIN_C6 62
#define PIN_C7 63

#define PIN_D0 64
#define PIN_D1 65
#define PIN_D2 66
#define PIN_D3 67
#define PIN_D4 68
#define PIN_D5 69
#define PIN_D6 70
#define PIN_D7 71

#define PIN_E0 72
#define PIN_E1 73
#define PIN_E2 74

//////////////////////////////////////////////////////////////
//// Useful defines
#define FALSE 0
#define TRUE 1

#define BYTE int


#define BOOLEAN short int

#define getc getch


#define fgetc getch
#define getchar getch
#define putc putchar
#define fputc putchar
#define fgets gets
#define fputs puts

//////////////////////////////////////////////////////////////
//// Control
// Control Functions: RESET_CPU(), SLEEP(), RESTART_CAUSE()
// Constants returned from RESTART_CAUSE() are:
#define WDT_FROM_SLEEP 3
#define WDT_TIMEOUT 11
#define MCLR_FROM_SLEEP 19
#define MCLR_FROM_RUN 27
#define NORMAL_POWER_UP 24
#define BROWNOUT_RESTART 26

65
//////////////////////////////////////////////////////////////
//// Timer 0
// Timer 0 (AKA RTCC)Functions: SETUP_COUNTERS() or
SETUP_TIMER_0(),
// SET_TIMER0() or SET_RTCC(),
// GET_TIMER0() or GET_RTCC()
// Constants used for SETUP_TIMER_0() are:
#define RTCC_INTERNAL 0
#define RTCC_EXT_L_TO_H 32
#define RTCC_EXT_H_TO_L 48

#define RTCC_DIV_1 8
#define RTCC_DIV_2 0
#define RTCC_DIV_4 1
#define RTCC_DIV_8 2
#define RTCC_DIV_16 3
#define RTCC_DIV_32 4
#define RTCC_DIV_64 5
#define RTCC_DIV_128 6
#define RTCC_DIV_256 7

#define RTCC_8_BIT 0

// Constants used for SETUP_COUNTERS() are the above


// constants for the 1st param and the following for
// the 2nd param:

//////////////////////////////////////////////////////////////
//// WDT
// Watch Dog Timer Functions: SETUP_WDT() or SETUP_COUNTERS()
(see above)
// RESTART_WDT()
//
#define WDT_18MS 8
#define WDT_36MS 9
#define WDT_72MS 10
#define WDT_144MS 11
#define WDT_288MS 12
#define WDT_576MS 13
#define WDT_1152MS 14
#define WDT_2304MS 15

//////////////////////////////////////////////////////////////
//// Timer 1
// Timer 1 Functions: SETUP_TIMER_1, GET_TIMER1, SET_TIMER1
// Constants used for SETUP_TIMER_1() are:
// (or (via |) together constants from each group)
#define T1_DISABLED 0
#define T1_INTERNAL 0x85
#define T1_EXTERNAL 0x87
#define T1_EXTERNAL_SYNC 0x83

#define T1_CLK_OUT 8

#define T1_DIV_BY_1 0
#define T1_DIV_BY_2 0x10
#define T1_DIV_BY_4 0x20
66
#define T1_DIV_BY_8 0x30

//////////////////////////////////////////////////////////////
//// Timer 2
// Timer 2 Functions: SETUP_TIMER_2, GET_TIMER2, SET_TIMER2
// Constants used for SETUP_TIMER_2() are:
#define T2_DISABLED 0
#define T2_DIV_BY_1 4
#define T2_DIV_BY_4 5
#define T2_DIV_BY_16 6

//////////////////////////////////////////////////////////////
//// CCP
// CCP Functions: SETUP_CCPx, SET_PWMx_DUTY
// CCP Variables: CCP_x, CCP_x_LOW, CCP_x_HIGH
// Constants used for SETUP_CCPx() are:
#define CCP_OFF 0
#define CCP_CAPTURE_FE 4
#define CCP_CAPTURE_RE 5
#define CCP_CAPTURE_DIV_4 6
#define CCP_CAPTURE_DIV_16 7
#define CCP_COMPARE_SET_ON_MATCH 8
#define CCP_COMPARE_CLR_ON_MATCH 9
#define CCP_COMPARE_INT 0xA
#define CCP_COMPARE_RESET_TIMER 0xB
#define CCP_PWM 0xC
#define CCP_PWM_PLUS_1 0x1c
#define CCP_PWM_PLUS_2 0x2c
#define CCP_PWM_PLUS_3 0x3c
long CCP_1;
#byte CCP_1 = 0x15
#byte CCP_1_LOW= 0x15
#byte CCP_1_HIGH= 0x16
long CCP_2;
#byte CCP_2 = 0x1B
#byte CCP_2_LOW= 0x1B
#byte CCP_2_HIGH= 0x1C
//////////////////////////////////////////////////////////////
//// PSP
// PSP Functions: SETUP_PSP, PSP_INPUT_FULL(),
PSP_OUTPUT_FULL(),
// PSP_OVERFLOW(), INPUT_D(), OUTPUT_D()
// PSP Variables: PSP_DATA
// Constants used in SETUP_PSP() are:
#define PSP_ENABLED 0x10
#define PSP_DISABLED 0

#byte PSP_DATA= 8

//////////////////////////////////////////////////////////////
//// SPI
// SPI Functions: SETUP_SPI, SPI_WRITE, SPI_READ, SPI_DATA_IN
// Constants used in SETUP_SSP() are:
#define SPI_MASTER 0x20
#define SPI_SLAVE 0x24
#define SPI_L_TO_H 0
#define SPI_H_TO_L 0x10
#define SPI_CLK_DIV_4 0
67
#define SPI_CLK_DIV_16 1
#define SPI_CLK_DIV_64 2
#define SPI_CLK_T2 3
#define SPI_SS_DISABLED 1

#define SPI_SAMPLE_AT_END 0x8000


#define SPI_XMIT_L_TO_H 0x4000

//////////////////////////////////////////////////////////////
//// UART
// Constants used in setup_uart() are:
// FALSE - Turn UART off
// TRUE - Turn UART on
#define UART_ADDRESS 2
#define UART_DATA 4
//////////////////////////////////////////////////////////////
//// COMP
// Comparator Variables: C1OUT, C2OUT
// Constants used in setup_comparator() are:
#define A0_A3_A1_A3 0xfff04
#define A0_A3_A1_A2_OUT_ON_A4_A5 0xfcf03
#define A0_A3_A1_A3_OUT_ON_A4_A5 0xbcf05
#define NC_NC_NC_NC 0x0ff07
#define A0_A3_A1_A2 0xfff02
#define A0_A3_NC_NC_OUT_ON_A4 0x9ef01
#define A0_VR_A1_VR 0x3ff06
#define A3_VR_A2_VR 0xcff0e

#bit C1OUT = 0x9c.6


#bit C2OUT = 0x9c.7

//////////////////////////////////////////////////////////////
//// VREF
// Constants used in setup_vref() are:
//
#define VREF_LOW 0xa0
#define VREF_HIGH 0x80
// Or (with |) the above with a number 0-15
#define VREF_A2 0x40

//////////////////////////////////////////////////////////////
//// ADC
// ADC Functions: SETUP_ADC(), SETUP_ADC_PORTS() (aka
SETUP_PORT_A),
// SET_ADC_CHANNEL(), READ_ADC()
// Constants used for SETUP_ADC() are:
#define ADC_OFF 0 // ADC Off
#define ADC_CLOCK_DIV_2 0x10000
#define ADC_CLOCK_DIV_4 0x4000
#define ADC_CLOCK_DIV_8 0x0040
#define ADC_CLOCK_DIV_16 0x4040
#define ADC_CLOCK_DIV_32 0x0080
#define ADC_CLOCK_DIV_64 0x4080
#define ADC_CLOCK_INTERNAL 0x00c0 // Internal 2-
6us

68
// Constants used in SETUP_ADC_PORTS() are:
#define NO_ANALOGS 7 // None
#define ALL_ANALOG 0 // A0 A1 A2
A3 A5 E0 E1 E2
#define AN0_AN1_AN2_AN4_AN5_AN6_AN7_VSS_VREF 1 // A0 A1 A2
A5 E0 E1 E2 VRefh=A3
#define AN0_AN1_AN2_AN3_AN4 2 // A0 A1 A2
A3 A5
#define AN0_AN1_AN2_AN4_VSS_VREF 3 // A0 A1 A2
A5 VRefh=A3
#define AN0_AN1_AN3 4 // A0 A1 A3
#define AN0_AN1_VSS_VREF 5 // A0 A1
VRefh=A3
#define AN0_AN1_AN4_AN5_AN6_AN7_VREF_VREF 0x08 // A0 A1 A5
E0 E1 E2 VRefh=A3 VRefl=A2
#define AN0_AN1_AN2_AN3_AN4_AN5 0x09 // A0 A1 A2
A3 A5 E0
#define AN0_AN1_AN2_AN4_AN5_VSS_VREF 0x0A // A0 A1 A2
A5 E0 VRefh=A3
#define AN0_AN1_AN4_AN5_VREF_VREF 0x0B // A0 A1 A5
E0 VRefh=A3 VRefl=A2
#define AN0_AN1_AN4_VREF_VREF 0x0C // A0 A1 A5
VRefh=A3 VRefl=A2
#define AN0_AN1_VREF_VREF 0x0D // A0 A1
VRefh=A3 VRefl=A2
#define AN0 0x0E // A0
#define AN0_VREF_VREF 0x0F // A0
VRefh=A3 VRefl=A2
#define ANALOG_RA3_REF 0x1 //!old only
provided for compatibility
#define A_ANALOG 0x2 //!old only
provided for compatibility
#define A_ANALOG_RA3_REF 0x3 //!old only
provided for compatibility
#define RA0_RA1_RA3_ANALOG 0x4 //!old only
provided for compatibility
#define RA0_RA1_ANALOG_RA3_REF 0x5 //!old only
provided for compatibility
#define ANALOG_RA3_RA2_REF 0x8 //!old only
provided for compatibility
#define ANALOG_NOT_RE1_RE2 0x9 //!old only
provided for compatibility
#define ANALOG_NOT_RE1_RE2_REF_RA3 0xA //!old only
provided for compatibility
#define ANALOG_NOT_RE1_RE2_REF_RA3_RA2 0xB //!old only
provided for compatibility
#define A_ANALOG_RA3_RA2_REF 0xC //!old only
provided for compatibility
#define RA0_RA1_ANALOG_RA3_RA2_REF 0xD //!old only
provided for compatibility
#define RA0_ANALOG 0xE //!old only
provided for compatibility
#define RA0_ANALOG_RA3_RA2_REF 0xF //!old only
provided for compatibility

// Constants used in READ_ADC() are:

69
#define ADC_START_AND_READ 7 // This is the default if
nothing is specified
#define ADC_START_ONLY 1
#define ADC_READ_ONLY 6

//////////////////////////////////////////////////////////////
//// INT
// Interrupt Functions: ENABLE_INTERRUPTS(),
DISABLE_INTERRUPTS(),
// EXT_INT_EDGE()
//
// Constants used in EXT_INT_EDGE() are:
#define L_TO_H 0x40
#define H_TO_L 0
// Constants used in ENABLE/DISABLE_INTERRUPTS() are:
#define GLOBAL 0x0BC0
#define INT_RTCC 0x0B20
#define INT_RB 0x0B08
#define INT_EXT 0x0B10
#define INT_AD 0x8C40
#define INT_TBE 0x8C10
#define INT_RDA 0x8C20
#define INT_TIMER1 0x8C01
#define INT_TIMER2 0x8C02
#define INT_CCP1 0x8C04
#define INT_CCP2 0x8D01
#define INT_SSP 0x8C08
#define INT_PSP 0x8C80
#define INT_BUSCOL 0x8D08
#define INT_EEPROM 0x8D10
#define INT_TIMER0 0x0B20
#define INT_COMP 0x8D40

#list

/*************************************************************
*******
* *
* This portion of header file is from HI-TECH PICC-STD
Compiler *
* *
**************************************************************
******/

#define _16F877A
/*
* Header file for the Microchip
* PIC 16F873A chip
* PIC 16F874A chip
* PIC 16F876A chip
* PIC 16F877A chip
* Midrange Microcontroller
*/
70
#if defined(_16F874A) || defined(_16F877A)
#define __PINS_40
#endif

#byte INDF = 0x00


#byte TMR0 = 0x01
#byte PCL = 0x02
#byte STATUS = 0x03
#byte FSR = 0x04
#byte PORTA = 0x05
#byte PORTB = 0x06
#byte PORTC = 0x07
#ifdef __PINS_40
#byte PORTD = 0x08
#byte PORTE = 0x09
#endif
#byte PCLATH = 0x0A
#byte INTCON = 0x0B
#byte PIR1 = 0x0C
#byte PIR2 = 0x0D
#byte TMR1L = 0x0E
#byte TMR1H = 0x0F
#byte T1CON = 0x10
#byte TMR2 = 0x11
#byte T2CON = 0x12
#byte SSPBUF = 0x13
#byte SSPCON = 0x14
#byte CCPR1L = 0x15
#byte CCPR1H = 0x16
#byte CCP1CON = 0x17
#byte RCSTA = 0x18
#byte TXREG = 0x19
#byte RCREG = 0x1A
#byte CCPR2L = 0x1B
#byte CCPR2H = 0x1C
#byte CCP2CON = 0x1D
#byte ADRESH = 0x1E
#byte ADCON0 = 0x1F

/* bank 1 registers */
#byte OPTION = 0x81
#byte TRISA = 0x85
#byte TRISB = 0x86
#byte TRISC = 0x87
#ifdef __PINS_40
#byte TRISD = 0x88
#byte TRISE = 0x89
#endif
#byte PIE1 = 0x8C
#byte PIE2 = 0x8D
#byte PCON = 0x8E
#byte SSPCON2 = 0x91
#byte PR2 = 0x92
#byte SSPADD = 0x93
#byte SSPSTAT = 0x94
#byte TXSTA = 0x98
#byte SPBRG = 0x99
71
#byte CMCON = 0x9C
#byte CVRCON = 0x9D
#byte ADRESL = 0x9E
#byte ADCON1 = 0x9F

/* bank 2 registers */
#byte EEDATA = 0x10C
#byte EEADR = 0x10D
// Alternate definition
#byte EEADRL = 0x10D
#byte EEDATH = 0x10E
#byte EEADRH = 0x10F

/* bank 3 registers */
#byte EECON1 = 0x18C
#byte EECON2 = 0x18D

/* STATUS bits */
#bit IRP = STATUS.7
#bit RP1 = STATUS.6
#bit RP0 = STATUS.5
#bit TO = STATUS.4
#bit PD = STATUS.3
#bit ZERO = STATUS.2
#bit DC = STATUS.1
#bit CARRY = STATUS.0

/* PORTA bits */
#bit RA5 = PORTA.5
#bit RA4 = PORTA.4
#bit RA3 = PORTA.3
#bit RA2 = PORTA.2
#bit RA1 = PORTA.1
#bit RA0 = PORTA.0

/* PORTB bits */
#bit RB7 = PORTB.7
#bit RB6 = PORTB.6
#bit RB5 = PORTB.5
#bit RB4 = PORTB.4
#bit RB3 = PORTB.3
#bit RB2 = PORTB.2
#bit RB1 = PORTB.1
#bit RB0 = PORTB.0

/* PORTC bits */
#bit RC7 = PORTC.7
#bit RC6 = PORTC.6
#bit RC5 = PORTC.5
#bit RC4 = PORTC.4
#bit RC3 = PORTC.3
#bit RC2 = PORTC.2
#bit RC1 = PORTC.1
#bit RC0 = PORTC.0

/* PORTD bits */
#ifdef __PINS_40
#bit RD7 = PORTD.7
72
#bit RD6 = PORTD.6
#bit RD5 = PORTD.5
#bit RD4 = PORTD.4
#bit RD3 = PORTD.3
#bit RD2 = PORTD.2
#bit RD1 = PORTD.1
#bit RD0 = PORTD.0

/* PORTE bits */
#bit RE2 = PORTE.2
#bit RE1 = PORTE.1
#bit RE0 = PORTE.0
#endif

/* INTCON bits */
#bit GIE = INTCON.7
#bit PEIE = INTCON.6
#bit T0IE = INTCON.5
#bit INTE = INTCON.4
#bit RBIE = INTCON.3
#bit T0IF = INTCON.2
#bit INTF = INTCON.1
#bit RBIF = INTCON.0
// alternate definitions
#bit TMR0IE = INTCON.5
#bit TMR0IF = INTCON.2

/* PIR1 bits */
#ifdef __PINS_40
#bit PSPIF = PIR1.7
#endif
#bit ADIF = PIR1.6
#bit RCIF = PIR1.5
#bit TXIF = PIR1.4
#bit SSPIF = PIR1.3
#bit CCP1IF = PIR1.2
#bit TMR2IF = PIR1.1
#bit TMR1IF = PIR1.0

/* PIR2 bits */
#bit CMIF = PIR2.6
#bit EEIF = PIR2.4
#bit BCLIF = PIR2.3
#bit CCP2IF = PIR2.0

/* T1CON bits */
#bit T1CKPS1 = T1CON.5
#bit T1CKPS0 = T1CON.4
#bit T1OSCEN = T1CON.3
#bit T1SYNC = T1CON.2
#bit TMR1CS = T1CON.1
#bit TMR1ON = T1CON.0

/* T2CON bits */
#bit TOUTPS3 = T2CON.6
#bit TOUTPS2 = T2CON.5
#bit TOUTPS1 = T2CON.4
#bit TOUTPS0 = T2CON.3
73
#bit TMR2ON = T2CON.2
#bit T2CKPS1 = T2CON.1
#bit T2CKPS0 = T2CON.0

/* SSPCON bits */
#bit WCOL = SSPCON.7
#bit SSPOV = SSPCON.6
#bit SSPEN = SSPCON.5
#bit CKP = SSPCON.4
#bit SSPM3 = SSPCON.3
#bit SSPM2 = SSPCON.2
#bit SSPM1 = SSPCON.1
#bit SSPM0 = SSPCON.0

/* CCP1CON bits */
#bit CCP1X = CCP1CON.5
#bit CCP1Y = CCP1CON.4
#bit CCP1M3 = CCP1CON.3
#bit CCP1M2 = CCP1CON.2
#bit CCP1M1 = CCP1CON.1
#bit CCP1M0 = CCP1CON.0
/* RCSTA bits */
#bit SPEN = RCSTA.7
#bit RX9 = RCSTA.6
#bit SREN = RCSTA.5
#bit CREN = RCSTA.4
#bit ADDEN = RCSTA.3
#bit FERR = RCSTA.2
#bit OERR = RCSTA.1
#bit RX9D = RCSTA.0

/* CCP2CON bits */
#bit CCP2X = CCP2CON.5
#bit CCP2Y = CCP2CON.4
#bit CCP2M3 = CCP2CON.3
#bit CCP2M2 = CCP2CON.2
#bit CCP2M1 = CCP2CON.1
#bit CCP2M0 = CCP2CON.0

/* ADCON0 bits */
#bit ADCS1 = ADCON0.7
#bit ADCS0 = ADCON0.6
#bit CHS2 = ADCON0.5
#bit CHS1 = ADCON0.4
#bit CHS0 = ADCON0.3
#bit ADGO = ADCON0.2
// Alternate definition for compatibility with other devices
#bit GODONE = ADCON0.2
#bit ADON = ADCON0.0

/* OPTION bits */
#bit RBPU = OPTION.7
#bit INTEDG = OPTION.6
#bit T0CS = OPTION.5
#bit T0SE = OPTION.4
#bit PSA = OPTION.3
#bit PS2 = OPTION.2
74
#bit PS1 = OPTION.1
#bit PS0 = OPTION.0

/* TRISA bits */
#bit TRISA5 = TRISA.5
#bit TRISA4 = TRISA.4
#bit TRISA3 = TRISA.3
#bit TRISA2 = TRISA.2
#bit TRISA1 = TRISA.1
#bit TRISA0 = TRISA.0

/* TRISB bits */
#bit TRISB7 = TRISB.7
#bit TRISB6 = TRISB.6
#bit TRISB5 = TRISB.5
#bit TRISB4 = TRISB.4
#bit TRISB3 = TRISB.3
#bit TRISB2 = TRISB.2
#bit TRISB1 = TRISB.1
#bit TRISB0 = TRISB.0
/* TRISC bits */
#bit TRISC7 = TRISC.7
#bit TRISC6 = TRISC.6
#bit TRISC5 = TRISC.5
#bit TRISC4 = TRISC.4
#bit TRISC3 = TRISC.3
#bit TRISC2 = TRISC.2
#bit TRISC1 = TRISC.1
#bit TRISC0 = TRISC.0

#ifdef __PINS_40
/* TRISD bits */
#bit TRISD7 = TRISD.7
#bit TRISD6 = TRISD.6
#bit TRISD5 = TRISD.5
#bit TRISD4 = TRISD.4
#bit TRISD3 = TRISD.3
#bit TRISD2 = TRISD.2
#bit TRISD1 = TRISD.1
#bit TRISD0 = TRISD.0

/* TRISE bits */
#bit IBF = TRISE.7
#bit OBF = TRISE.6
#bit IBOV = TRISE.5
#bit PSPMODE = TRISE.4

#bit TRISE2 = TRISE.2


#bit TRISE1 = TRISE.1
#bit TRISE0 = TRISE.0
#endif

/* PIE1 bits */
#ifdef __PINS_40
#bit PSPIE = PIE1.7
#endif
#bit ADIE = PIE1.6
75
#bit RCIE = PIE1.5
#bit TXIE = PIE1.4
#bit SSPIE = PIE1.3
#bit CCP1IE = PIE1.2
#bit TMR2IE = PIE1.1
#bit TMR1IE = PIE1.0

/* PIE2 bits */
#bit CMIE = PIE2.6
#bit EEIE = PIE2.4
#bit BCLIE = PIE2.3
#bit CCP2IE = PIE2.0

/* PCON bits */
#bit POR = PCON.1
#bit BOR = PCON.0

/* SSPCON2 bits */
#bit GCEN = SSPCON2.7
#bit ACKSTAT = SSPCON2.6
#bit ACKDT = SSPCON2.5
#bit ACKEN = SSPCON2.4
#bit RCEN = SSPCON2.3
#bit PEN = SSPCON2.2
#bit RSEN = SSPCON2.1
#bit SEN = SSPCON2.0

/* SSPSTAT bits */
#bit SMP = SSPSTAT.7
#bit CKE = SSPSTAT.6
#bit DA = SSPSTAT.5
#bit STOP = SSPSTAT.4
#bit START = SSPSTAT.3
#bit RW = SSPSTAT.2
#bit UA = SSPSTAT.1
#bit BF = SSPSTAT.0
#ifdef __STAT_BACKWARD_COMPATIBILITY
#define STAT_SMP SMP
#define STAT_CKE CKE
#define STAT_DA DA
#define STAT_P STOP
#define STAT_S START
#define STAT_RW RW
#define STAT_UA UA
#define STAT_BF BF
#endif

/* TXSTA bits */
#bit CSRC = TXSTA.7
#bit TX9 = TXSTA.6
#bit TXEN = TXSTA.5
#bit SYNC = TXSTA.4
#bit BRGH = TXSTA.2
#bit TRMT = TXSTA.1
#bit TX9D = TXSTA.0

/* CMCON Bits */
//#bit C2OUT = CMCON.7 //already defined above
76
//#bit C1OUT = CMCON.6 //already defined above
#bit C2INV = CMCON.5
#bit C1INV = CMCON.4
#bit CIS = CMCON.3
#bit CM2 = CMCON.2
#bit CM1 = CMCON.1
#bit CM0 = CMCON.0

/* CVRCON Bits */
#bit CVREN = CVRCON.7
#bit CVROE = CVRCON.6
#bit CVRR = CVRCON.5
#bit CVR3 = CVRCON.3
#bit CVR2 = CVRCON.2
#bit CVR1 = CVRCON.1
#bit CVR0 = CVRCON.0

/* ADCON1 bits */
#bit ADFM = ADCON1.7
#bit ADCS2 = ADCON1.6
#bit PCFG3 = ADCON1.3
#bit PCFG2 = ADCON1.2
#bit PCFG1 = ADCON1.1
#bit PCFG0 = ADCON1.0

/* EECON1 bits */
#bit EEPGD = EECON1.7
#bit WRERR = EECON1.3
#bit WREN = EECON1.2
#bit WR = EECON1.1
#bit RD = EECON1.0

#define CONFIG_ADDR 0x2007

/*osc configurations*/
#define RC 0x3FFF // resistor/capacitor
#define HS 0x3FFE // high speed crystal/resonator
#define XT 0x3FFD // crystal/resonator
#define LP 0x3FFC // low power crystal/resonator

/*watchdog*/
#define WDTEN 0x3FFF // enable watchdog timer
#define WDTDIS 0x3FFB // disable watchdog timer

/*power up timer*/
#define PWRTEN 0x3FF7 // enable power up timer
#define PWRTDIS 0x3FFF // disable power up timer

/*brown out reset*/


#define BOREN 0x3FFF // enable brown out reset
#define BORDIS 0x3FBF // disable brown out reset

/*Low Voltage Programmable*/


#define LVPEN 0x3FFF // low voltage programming enabled
#define LVPDIS 0x3F7F // low voltage programming
disabled

77
/*data code protected*/
#define DP 0x3EFF // protect data code
// alternately
#define DPROT 0x3EFF // use DP
#define DUNPROT 0x3FFF // use UNPROTECT

/* Flash memory write enable/protect */


#define WRTEN 0x3FFF /* flash memory write enabled */
#define WP1 0x3DFF /* protect 0000 - 00FF */
#define WP2 0x3BFF /* protect 0000 - 07FF(76A/77A) /
03FF(73A/74A) */
#define WP3 0x39FF /* protect 0000 - 1FFF(76A/77A) /
0FFF(73A/74A) */

/*debug option*/
#define DEBUGEN 0x37FF // debugger enabled
#define DEBUGDIS 0x3FFF // debugger disabled

/*code protection*/
#define PROTECT 0x1FFF /* protect program code */
#define UNPROTECT 0x3FFF /* do not protect the code */

#endif //#ifndef _16F877A_h

78
D.2 Allocations.h

This file mainly contains pin allocations. If we need to change the purpose of a pin, we
simply change pin allocation in this file. In all the code coming after, we use names declared
in this file

#ifndef Allocations_h
#define Allocations_h

#ifndef _16F877A_h
#include "16F877A_modified.h"
#endif //end #ifndef _16F877A_h

/****************** Resource Allocation


***************************\
*
*Sun Tracking:
*-------------
* ==> Three A/D channels are allocated to 3 sensor
pairs(input)
* ==> Four motor pins are allocated(output)
* ==> One pin provided to control power of related
circuitry(output)
* ==> Three pins for sensing 3 breaks
*
* PINS:
* RA0/AN0,RA1/AN1,RA2/AN2 to measure 3 sensors
* RC0,RC2,RC3,RC4 to control motors
* RC5 to control power of Sun Tracking circuit(ON/OFF)
*
*MPPT:
*-----
* ==> CCP2 Module for PWM/MPPT
* ==> PWM module will use Timer2
* ==> Two A/D channels provided for panel's I and V
measurement
* ==> CCP2 output pin RC1 is utilized
* ==> One pin to control analog switch. To take Ipv
sample at same time when
* taking Vpv sample, we will use external analog mux.
this will be turned
* Off when starting Vpv conversion
*
* PINS:
* RA5/AN4 and RE0/AN5 to measure I and V
* RC1/CCP2 for PWM
*

79
*LCD:
*----
* PINS:
* PORTD for Data
* RB1,RB4 for RS,E pins of LCD
*
*Communication To PC:
*--------------------
* ==> USART used
*
* PINS:
* RC6/Tx,RC7/Rx
*
*Battery:
*--------
* ==> Two A/D pins provided for battery I and V
measurement
*
* PINS:
* RE1/AN6 to measure battery voltage
* RE2/AN7 to measure battery current
*
*Generic:
*--------
* ==> Timer1(16-bit) for global time keeping (if
required)
* ==> CCP1 to to control the period of Timer1 (if
Timr1 used)
*
* PINS:
* RB5 to control power of other interfacing circuitry
*
\*************************************************************
************/

/*********************** Pin Definitions


*****************************/

//SunTracking:
//------------

#define channelSensorAz 0
#define channelSensorAlt 1
#define channelSensor3rd 2

#define pinMotor1a RB1 //Motor Pin Definitions


#define dirMotor1a TRISB1

80
#define pinMotor1b RB2
#define dirMotor1b TRISB2
#define pinMotor2a RB4
#define dirMotor2a TRISB4
#define pinMotor2b RB5
#define dirMotor2b TRISB5
#define pinAzBreak RC0
#define dirAzBreak TRISC0
#define pinAltBreak1 RC4
#define dirAltBreak1 TRISC4
#define pinAltBreak2 RC5
#define dirAltBreak2 TRISC5

//#define pinSunTrackerPower RC5


//#define dirSunTrackerPower TRISC5

//MPPT:
//-----
#define channelVpv 6
#define channelIpv 5
//#define pinIpvSwitch RB0
//#define dirIpvSwitch TRISB0
//#define IpvSwitchOFF 0
//#define IpvSwitchON 1
#define pinPWM RC1
#define dirPWM TRISC1

//LCD:
//----
#define LCDdataPort PORTD
#define LCDdataDir TRISD
//#define pinLCDBusy RD7
//#define dirLCDBusy TRISD7
#define pinRS RC2
#define dirRS TRISC2
//#define pinRW RB2
//#define dirRW TRISB2
#define pinE RC3
#define dirE TRISC3

//RS232 Communication:
//--------------------
#define pinTx RC6
#define dirTx TRISC6 //needs to be set: page 111, col 2 of
DataSheet

81
#define pinRx RC7
#define dirRx TRISC7

//Battery:
//--------
#define pinBatteryVoltage RE1
#define dirBatteryVoltage TRISE1
#define pinBatteryCurrent RE2
#define dirBatteryCurrent TRISE2

#define channelBatteryVoltage 6
#define channelBatteryCurrent 7

//Generic:
//--------

#define pinTestLed RB5


#define dirTestLed TRISB5

#endif //end #ifdef Allocations_h

82
D.3 SpecsAndDefs.h

This file contains the things like oscillator frequency and many other circuit specific
declarations. If we decide to change, for example, the oscillator frequency, we’ll change
declaration here and then there will be no effect on remaining code. For example, the timer1
will overflow after 1ms regardless of oscillator if we duly change #define Fosc 20000000
duely. The file also contains some global definitions

#ifndef SpecsAndDefs_h
#define SpecsAndDefs_h

#ifndef _16F877A_h
#include "16F877A_modified.h"
#endif //end #ifndef _16F877A_h

#fuses
NOLVP,NOWDT,NOPROTECT,NOPUT,NOBROWNOUT,NODEBUG,NOCPD,NOWRT,HSp
eed
//Configuration Bits(word) is defined below
//#rom 0x2007={0x3FB2}
#define Fosc 20000000
#use delay(clock=Fosc)
#use rs232(baud=57600, xmit=PIN_C6,rcv=PIN_C7)

#define MaxTimer1Value (unsigned int16)(1e-3*Fosc/4) //


equals 1ms
#define MaxMilliSeconds (unsigned int16) 60000 //
equals 1min
#define Timer1CountsPer_us (Fosc * 1e-6)/4

#define PWMPeriod 40e-6 //25KHz


#if (((((int16)(PWMPeriod*Fosc))>>2)-1) <= 255)
#define Timer2Prescale T2_DIV_BY_1
#define Timer2Period
(int8)((((int16)(PWMPeriod*Fosc))>>2)-1)
#else
#define Timer2Prescale T2_DIV_BY_4
#define Timer2Period
(int8)(((((int16)(PWMPeriod*Fosc))>>2)-1)>>2)
#endif
#define DefaultDuty (int16)( (Timer2Period << 2) * .5)

#if (Fosc <= 20000000)


#define AdcClock ADC_CLOCK_DIV_32
83
#else
#define AdcClock ADC_CLOCK_DIV_64
#endif

#define IpvSensorOffsetInVolts 1.9


#define IpvSensorGain 22
#define Rsense 0.237
#define IpvSensorOffset
(int16)(1024*(float)IpvSensorOffsetInVolts/5)
#define IpvThatMaps5V (int16) 1000*(float)(5-
IpvSensorOffsetInVolts)/(float)(IpvSensorGain*Rsense)

#define VpvThatMaps5V 28500

#define Pos 0
#define Neg 1

//Global Variables Definitions


int32 t; // Global Variable for keeping global time
//It will be incremented each millisecond
unsigned int16 Vpv, Ipv, Vbat, Ibat;
unsigned int32 Ppv;

// #separate
// void MeasureVpvAndIpv(int16 &Vpv, int16 &Ipv);
#endif //End #ifndef SpecsAndDefs_h

84
D.4 Main.c

This file contains main function and some related global functions. Each needy function is
called in sequence in a loop and the function decides whether to do some function or not
depending upon the time elapsed after previous call to that function. For example, LCD
function will only update LCD after at least 1500 milliseconds. Global variable is used to
keep the global time in milliseconds.

#include "Allocations.h"
#include "SpecsAndDefs.h"
#include "MPPT.c"
#include "SunTrack.c"
#include "LCD.c"
#include "Misc.c"

void initialize(void)
{
//Most of the functions and Variables below are Built-in
ones of CCS C Compiler

enable_interrupts( GLOBAL );

////////////////////////CCP1 and Timer1 Modules


initialization
setup_timer_1( T1_INTERNAL | T1_DIV_BY_1 ); //Built-in
function&variables
disable_interrupts( INT_TIMER1 ); //Built-in
set_timer0(0x0000);
setup_ccp1( CCP_COMPARE_RESET_TIMER ); //built-in
CCP_1 = MaxTimer1Value; //"MaxTimer1Value" defined in
"SpecsAndDefs.h"
enable_interrupts( INT_CCP1 );
t = 0;

////////////////////////CCP2 and Timer2 Modules


initialization
setup_timer_2 ( Timer2Prescale, Timer2Period,
2);//Variables defined in
//"SpecsAndDefs.h",Built-in
function
disable_interrupts( INT_TIMER2 ); //built-in variables
setup_ccp2( CCP_PWM ); //built-in

85
set_pwm2_duty(DefaultDuty); //DefaultDuty defined
in SpecsAndDefs.h
set_timer2(0x00); //Reset Timer2

/////////////////////////Setup ADC
SETUP_ADC_PORTS( ALL_ANALOG );
SETUP_ADC( AdcClock ); //"AdcClock" is defined
in "SpecsAndDefs.h"
ADFM = 1; //Right justify A/D
result,bit7 of ADCON1 Reg
//dirIpvSwitch = 0; //Make the pin output
port_b_pullups(TRUE);

/////////////////////////Setup SunTrack
dirMotor1a = 0;
dirMotor1b = 0;
dirMotor2a = 0;
dirMotor2b = 0;
dirAzBreak = 1;
dirAltBreak1 = 1;
dirAltBreak2 = 1;
////////////////////////Setup LCD
LCDdataDir = 0x00;
dirRS = 0;
//dirRW = 0;
dirE = 0;
lcdcmd(0x38);
lcdcmd(0x0C);
lcdcmd(0x01);
lcdcmd(0x06);

///////////////////////Generic
dirTestLed = 0;
}

// General Idea of the main function below is that it will


call every function
// sequentially and each function, when it is called, will
determine what it
// has to do? Even to do something or not depending on time
elapsed between
// present and previous call. For example, LCD() function will
only do something
86
// when considerable time has been elapsed after previous
update of LCD.

void main(void)
{
initialize();
while(1)
{
// All the functions below are inline functions with
// all parameters as reference parameters (without
pointer)
// Both these are features of C++ but supported by CCS C
compiler
// Howerver syntax of inline function definition is
different from
// standard C++

// Prototypes of all the functions below are defined in


"SpecsAndDefs.h"
//SunTrack();
CalculateVpvIpv();
MPPT();
//CalculateVbatIbat();
LCD();
//RS232();
//TriggerTestLed();
}
}

#int_ccp1
void IncrementMilliSeconds(void)
{
// This is ISR for timer1 overflow, which occurs after 1ms
t++;
if(t > 0x7FFFFFFD)
t = 0;
}

87
D.5 MPPT.c

//------ PROTOTYPES ---------


void CalculateVpvIpv();
void PerturbAndObsVI();
void CalculateIncrement();
void CalculateDuty();

//----- Variables related to this file --------


unsigned int16 Vperturb,Iperturb;
unsigned int32 Pperturb;
unsigned int16 Increment = 5;
unsigned int16 Duty = DefaultDuty; // will be adjusted
automatically

void MPPT()
{

static int32 MPPTtime = 0;

// Ensure enough time has been elapsed after last call to


MPPT function
if(t >= MPPTtime) //t will be less when it will overflow to
0
{
if((t - MPPTtime) < 500)
return;
}
// store Current time for future use
MPPTtime = t; //t is global time

// Calculate Vpv, Ipv. Take care that both are sampled at


same time
CalculateVpvIpv();
// Ppv = Vpv*Ipv
Ppv = _mul(Vpv, Ipv);
// Perturb by turning sw OFF and calculate Vperturb,
Iperturb and Pperturb
PerturbAndObsVI();
// Restore old duty till new duty is calculated
set_pwm2_duty((int16)Duty);
Pperturb = _mul(Vperturb, Iperturb);

88
// calculate increment
//CalculateIncrement();
// calculate new duty
CalculateDuty();
// set new duty
set_pwm2_duty((int16)Duty);
}

/*
void SetDuty8(int8 Duty)
{
CCP2CON &= 0xCF; // Make two LSBits of duty zero
CCPR2L = Duty; // Higher 8bits equal to Duty
}

void SetDuty()
{
int8 a;
a = Make8(Duty,0);
a >>= 2;
a |= (Make8(Duty,1)<<6);
CCPR2L = a;
CCP2CON &= 0xCF;
CCP2CON |= (Make8(Duty,0) << 4) & 0x30;
}
*/

void PerturbAndObsVI()
{
int32 t1;
int1 TimeOut = 0;
// PWM switch OFF
set_pwm2_duty((int16)0x0000);
// select voltage channel as A/D input
set_adc_channel(channelVpv);

t1 = t; //t is global time


// do-while(Vpv >= Vperturb);
do
{
// turn on current sampling switch

89
//pinIpvSwitch = IpvSwitchON;
// wait for sampling time
delay_us(200);
// start A/D conversion
ADGO = 1;
// turn off current sampling switch
//pinIpvSwitch = IpvSwitchOFF;
// check if time elapsed since entry to this function is
within limits
if((t >= t1) && ((t-t1) > 100))
{
TimeOut = 1;
break;
}
// wait for conversion to complete
while(ADGO == 1);
// assign conversion result to Vperturb
Vperturb = Make16(ADRESH,ADRESL);
}while(Vpv >= Vperturb);

//if timeout occured, try by decreasing voltage


if(TimeOut == 1) //Try to decrease Voltage
{
t1 = t;
set_pwm2_duty((int16)0x3FF);
do
{
// turn on current sampling switch
//pinIpvSwitch = IpvSwitchON;
// wait for sampling time
delay_us(200);
// start A/D conversion
ADGO = 1;
// turn off current sampling switch
//pinIpvSwitch = IpvSwitchOFF;
// check if time elapsed since entry to this function
is within limits
if((t >= t1) && ((t-t1) > 100))
{
TimeOut = 1;
set_pwm2_duty(DefaultDuty);
break;

90
}
// wait for conversion to complete
while(ADGO == 1);
// assign conversion result to Vperturb
Vperturb = Make16(ADRESH,ADRESL);
}while(Vperturb >= Vpv );
}
if(TimeOut == 1) //still timeout
{
//Vperturb = Vpv, so that dVpv = 0 later
Vperturb = Vpv;
Iperturb = Ipv;
}
//else
else
{
// select 'panel current' channel as A/D input
set_adc_channel(channelIpv);
// wait for aquisation time
delay_us(20);
// start A/D conversion
ADGO = 1;
// wait for conversion to complete
while(ADGO == 1);
// assign conversion result to Iperturb
Iperturb = Make16(ADRESH,ADRESL);
if(Ipv > IpvSensorOffset)
Ipv -= IpvSensorOffset; //CurrentSensorOffset is
defined in SpecsAndDefs.h
else
Ipv = 0;
// select voltage channel as A/D input
// turn on current sampling switch
//pinIpvSwitch = IpvSwitchON;
}
}

void CalculateIncrement()
{
// This algorithm will work correctly if 6 MSBits of 20bit
dPpv are zero
int32 dPpv;

91
int16 dV;

if(Ppv > Pperturb)


dPpv = Ppv - Pperturb;
else
dPpv = Pperturb - Ppv;

if(Vpv > Vperturb)


dV = Vpv - Vperturb;
else
dV = Vperturb - Vpv;

if(dV == 0) // avoid divide by


zero
{
Increment = 0; // to avoid
change in duty
}
else if(dV == 1) // don't waste time in
division
{
Increment = dP >> 4;
}
else if(dV == 2) // Most of the
times, dV is 1 or 2
{
Increment = dP >> 5;
}
else
{
Increment = dP / ((int32)dV << 4);
}

/** Below are optional lines to adjust Increment**/


Increment >>= 2;
if(dP != 0 && Increment == 0)
Increment = 1;
}

void CalculateDuty()
{
if(Vperturb > Vpv)

92
{
if(Pperturb > Ppv) // +ve
derivative
{
if(Increment > Duty)
Duty = 0; // Min Possible
duty
else
Duty -= Increment; // reduce
duty
}
else
{
#define Period ((int16)(Timer2Period) << 2) +
(int16)0x0003
if((Duty + Increment) > Period) //
preprocessor will calculate Period
// to avoid
calculation in controller
{
Duty = Period; // Max. Possible
duty
}
else
{
Duty += Increment; // increase
duty
}
#undef Period
}
}
else if(Vperturb < Vpv)
{
if(Pperturb < Ppv) // +ve
derivative
{
if(Increment > Duty)
Duty = 0; // Min Possible
duty
else
Duty -= Increment; // reduce
duty
}

93
else
{
#define Period ((int16)(Timer2Period) << 2) +
(int16)0x0003
if((Duty + Increment) > Period) //
preprocessor will calculate Period
// to avoid
calculation in controller
{
Duty = Period; // Max. Possible
duty
}
else
{
Duty += Increment; // increase
duty
}
#undef Period
}
}
}

94
D.6 SunTrack.c

#define MinVal4High (unsigned


int16)((float)((float)2.6/5)*1024)
#define MaxVal4Low (unsigned
int16)((float)((float)2.4/5)*1024)
#define ON 1
#define OFF 0
#define TimeOutInterval 1500 // Max allowed time for this
function in milliseconds

void SunTrack(void)
{
static int1 dir = 0;
static int1 ReverseTheDir = 0;
static int1 BalancedAfterBreak = 0;
//static int1 AzBreakState = 0;
//static int1 PrevAzBreakState = 0;
static int1 Balanced180DegOut = 0;
int16 a;
static int32 SunTrackTime = 0;

if((t >= SunTrackTime) && (t-SUNTRACKtime < 100))


return;
SunTrackTime = t;

// Track Sun Azimuth first


while(1)
{
if( (t >= SunTrackTime) && (t - SunTrackTime) >
TimeOutInterval )
{
break;
}

if(pinAzBreak == 1)
{
ReverseTheDir = 1;
BalancedAfterBreak = 0;
}

// Take reading of Azimuth sensor

95
set_adc_channel(channelSensorAz);
delay_us(20);
ADGO = 1;
while(ADGO == 1);
a = Make16(ADRESH,ADRESL);

if( MaxVal4Low < a && a < MinVal4High)


{
BalancedAfterBreak = 1;
if(ReverseTheDir == 0 && Balanced180DegOut == 0)
{
break; //Azimuth Correctly tracked now
}
}
else if( a <= MaxVal4Low)
{
Balanced180DegOut = 0; // Now panel is unbalanced and
will go to right dir
if(BalancedAfterBreak)
// Az has been balanced once after break, which was
surely wrong balance
// Now After unbalancing again, Panel will tend to
right direction
{
ReverseTheDir = 0;
}
if(ReverseTheDir == 0)
{
dir = 1;
}
else
{
dir = 0;
}
}
else //a >= MinVal4High
{
Balanced180DegOut = 0; // Now panel is unbalanced and
will go to right dir
if(BalancedAfterBreak)
// Az has been balanced once after break, which was
surely wrong balance

96
// Now After unbalancing again, Panel will tend to
right direction
{
ReverseTheDir = 0;
}
if(ReverseTheDir == 0)
{
dir = 0;
}
else
{
dir = 1;
}
}

if(dir == 0)
{
pinMotor1a = ON;
pinMotor1b = OFF;
}
else
{
pinMotor1a = OFF;
pinMotor1b = ON;
}
}
// Azimuth tracking sensors balanced or timeout occured.
Turn Off the motor now
pinMotor1a = OFF;
pinMotor1b = OFF;

// Now Track Sun Altitude


while(1)
{
if( (t >= SunTrackTime) && (t - SunTrackTime) >
TimeOutInterval )
{
break;
}

set_adc_channel(channelSensorAlt);
delay_us(20);

97
ADGO = 1;
while(ADGO == 1);
a = Make16(ADRESH,ADRESL);

if(a > MaxVal4Low && a < MinVal4High) // Alt sensor


balanced
{
break;
}

else if(a >= 512)


{
if(pinAltBreak1)
{
Balanced180DegOut = 1;
break;
}
pinMotor2a = ON;
pinMotor2b = OFF;
}
else
{
if(pinAltBreak2) //Maximum possible downward
tracking done
break;
pinMotor2a = OFF;
pinMotor2b = ON;
}
}
pinMotor2a = OFF;
pinMotor2b = OFF;
}
#undef MinVal4High
#undef MaxVal4Low
#undef ON
#undef OFF
#undef TimeOutInterval

98
D.7 LCD.c

void lcdcmd(unsigned char value){


LCDdataPort = value; //put the value on the pins
pinRS = 0;
pinE = 1; //strobe the enable pin
delay_us(60);
pinE = 0;
return;
}

void lcddata(unsigned char value){


LCDdataPort = value; //put the value on the pins
pinRS = 1;
pinE = 1; //strobe the enable pin
delay_us(60);
pinE = 0;
return;
}

void UpdateMsg1(unsigned char Msg[])


{
//ActualVpv = Vpv*25/1024
unsigned char i;
int32 temp;
temp = _mul(Vpv, VpvThatMaps5V);
temp >>= 10;
for(i = 13; i >= 11; i--)
{
Msg[i] = temp % 10 + 0x30;
temp /= 10;
}
for(i = 9; i >= 8; i--)
{
Msg[i] = temp % 10 + 0x30;
temp /= 10;
}
}

void UpdateMsg2(unsigned char Msg[])


{
//ActualIpv = Ipv*(Current which maps to 5V)/(1024-
CurrentSensorOffset)
unsigned char i;
int32 temp;

99
#define Multiplier
(int16)((float)10*IpvThatMaps5V*(float)1024/(float)(1024 -
IpvSensorOffset))
// IpvSensorOffset and IpvThatMaps5V are defined in
SpecAndDefs.h
// 1024 is multiplied in above #define to make quantity
large. It will be >> by 10 later
// 10 is multiplied to display current upto 1 decimal point
in mA
temp = _mul(Ipv, Multiplier);
#undef Multiplier

temp >>= 10;

Msg[12] = temp % 10 + 0x30;


temp /= 10;

for(i = 10; i >= 8; i--)


{
Msg[i] = temp % 10 + 0x30;
temp /= 10;
}

void UpdateMsg3(unsigned char Msg[])


{
// To calculate Power, find ActualIpv and Actual Ipv
separately and then mult
unsigned char i;
int32 temp, ActualIpv;

// First calculate Actual Current and store it in temp


#define Multiplier
(int16)((float)10*IpvThatMaps5V*(float)1024/(float)(1024 -
IpvSensorOffset))
// IpvThatMaps5V and IpvSensorOffset are defined in
SpecAndDefs.h
// 1024 is multiplied in above #define to make quantity
large. It will be >> by 10 later
// 10 is multiplied to display current upto 1 decimal point
in mA
ActualIpv = _mul(Ipv, Multiplier);
#undef Multiplier
ActualIpv >>= 10;

// Now Calculate ActualVpv

100
temp = _mul(Vpv, VpvThatMaps5V);
temp >>= 10;

// Now temp contains Actual Vpv, Multiply it with ActualIpv


temp *= ActualIpv;

// ActualIpv contained (current in mA)* 10 and ActualVpv is


100 times
temp /= 10000;
for(i = 13; i >= 11; i--)
{
Msg[i] = temp % 10 + 0x30;
temp /= 10;
}
for(i = 9; i >= 8; i--)
{
Msg[i] = temp % 10 + 0x30;
temp /= 10;
}
}

void UpdateMsg4(unsigned char Msg[])


{

void UpdateMsg5(unsigned char Msg[])


{

void UpdateMsg6(unsigned char Msg[])


{
int16 temp = Timer2Period << 2;
int8 i;
for(i = 13; i >= 9; i--)
{
Msg[i] = temp % 10 + 0x30;
temp /= 10;
}

temp = Duty;
for(i = 5; i >= 1; i--)
{
Msg[i] = temp % 10 + 0x30;
temp /= 10;

101
}
}

void LCD(){
static unsigned char Msg1[] =
{'V','p','a','n','e','l','=',' ','0','0','.','0','0','0','
','V'};
static unsigned char Msg2[] =
{'I','p','a','n','e','l','=',' ','0','0','0','.','0','
','m','A'};
static unsigned char Msg3[] =
{'P','p','a','n','e','l','=',' ','0','0','.','0','0','0','
','W'};
static unsigned char Msg4[] = {'V','b','a','t','=','
','0','0','.','0','0','0',' ','V',' ',' '};

unsigned char TotalMsgs = 4;


static unsigned char i,Iteration = 0;
static int32 LCDtime = -1000;

if(t >= LCDtime && (t - LCDtime) < 1500)


return;

LCDtime = t;
switch (Iteration)
{
case(0):
UpdateMsg1(Msg1);
lcdcmd(0x80); //line 1, position 0
for(i = 0; i < 16; i++)
{
lcddata(Msg1[i]);
if ( i==7)
lcdcmd(0xC8);
}
break;
case(1):
UpdateMsg2(Msg2);
lcdcmd(0x80); //line 1, position 0
for(i = 0; i < 16; i++)
{
lcddata(Msg2[i]);
if ( i==7)
lcdcmd(0xC8);
}
break;
case(2):

102
UpdateMsg3(Msg3);
lcdcmd(0x80); //line 1, position 0
for(i = 0; i < 16; i++)
{
lcddata(Msg3[i]);
if ( i==7)
lcdcmd(0xC8);
}
break;
case(3):
UpdateMsg4(Msg4);
lcdcmd(0x80); //line 1, position 0
for(i = 0; i < 16; i++)
{
lcddata(Msg4[i]);
if ( i==7)
lcdcmd(0xC8);
}
break;

default:
break;
}
Iteration ++;
if(Iteration >= (TotalMsgs))
Iteration = 0;
}

103
D.8 Misc.c
void CalculateVpvIpv()
{
// select Voltage channel as adc input channel
set_adc_channel(channelVpv);
// turn on Current sampling switch
//pinIpvSwitch = IpvSwitchON;
// wait for sampling time
delay_us(200);
// start A/D conversion (Voltage will be A/D converted)
ADGO = 1;
// turn off Current sampling switch
//pinIpvSwitch = IpvSwitchOFF;
// wait for conversion to complete
while(ADGO == 1);
// select current channel as A/D input channel
set_adc_channel(channelIpv);
// assign previous A/D result to Vpv
Vpv = Make16(ADRESH,ADRESL);
// wait for sampling time
delay_us(20);
// start A/D conversion
ADGO = 1;
// wait for conversion to complete
while(ADGO == 1);
// Assign new A/D result to Ipv
Ipv = Make16(ADRESH,ADRESL);
// turn on current sampling switch
//pinIpvSwitch = IpvSwitchON;
if(Ipv > IpvSensorOffset)
Ipv -= IpvSensorOffset; //CurrentSensorOffset is defined
in SpecsAndDefs.h
else
Ipv = 0;
// select voltage channel as A/D input
set_adc_channel(channelVpv);
}

void CalculateVbatIbat(void)
{
set_adc_channel(channelBatteryVoltage);

104
delay_us(20);
ADGO = 1;
while(ADGO == 1);
Vbat = Make16(ADRESH,ADRESL);

set_adc_channel(channelBatteryCurrent);
delay_us(20);
ADGO = 1;
while(ADGO == 1);
Ibat = Make16(ADRESH,ADRESL);
}
void RS232(void)
{
static int32 RS232time = 0;
if((t>=RS232time) && (t-RS232time < 1000))
return;
RS232time = t;
printf("%c%c",Make8(Vpv,1),Make8(Vpv,0));
printf("%c%c",Make8(Ipv,1),Make8(Ipv,0));
printf("\r\n");
}

void TriggerTestLed(void)
{
static int32 testTime = 0;
if((t >= testTime) && (t - testTime) < 1000)
return;
testTime = t;
pinTestLed = ~pinTestLed;
}

105
References

[1] Mazidi M.A., McKinlay R.D. and Causey D., “PIC Microcontroller and Embedded, Using
Assembly and C for PIC18”, 1st ed., Prentice-Hall, 2006

[2] Sedra A.S. and Smith K.C., “Microelectronic Circuits”, 5th ed., 2008

[3] M.H. Rashid, “Power Electronics: Circuits, Devices and Applications,” 3rd Edition, 2004.
Pearson Education, Inc

[4] Dorin O. Neacsu, “Power Switching Converters”, 2006 by Taylor & Francis Group, LLC

[5] Simone Buso and Paolo Mattavelli,”Digital Control in Power Electronics”, 2006 by
Morgan & Claypool

[6]Bimal .K. Bose, “Modern Power Electronics and AC Drives,” 2002, Pearson Education

[7] N. Mohan T. M. Undeland and W. P. Robbins, “Power Electronics: Converters,


Applications, and Design”, 3rd Edition

[8] Muhammad H. Rashid, “Power Electronics Handbook: Devices, Circuits and


Applications”, 2nd Edition, Academic Press, New York, 2006.

[9] http://www.howstuffworks.com/solar_panel

[10] http://en.wikipedia.org/wiki/Buck_converter

[11] http://en.wikipedia.org/wiki/battery(electrical)

[12] Proteus VSM official website,

http://www.labcenter.co.uk

[13] CCS Compiler official website,

http://www.ccsinfo.com/

[14] Microchip official website,

http://www.microchip.com/

106

You might also like