auto control design for power factor improvement.pdf
TRANSCRIPT
AUTO CONTROL DESIGN FOR POWER FACTOR
IMPROVEMENT
Supervisor
Prof. Dr. Aftab Ahmad Professor EED
Submitted By
Asad Ali Khan 08-EE-23 Waqas Ali 08-EE-35 Qamar-u-Zaman 08-EE-74
DEPARTMENT OF ELECTRICAL ENGINEERING FACULTY OF ELECTRONICS & ELECTRICAL
ENGINEERING UNIVERSITY OF ENGINEERING AND TECHNOLOGY
TAXILA
July 2012
AUTO CONTROL DESIGN FOR POWER FACTOR IMPROVEMENT
Supervisor
Prof. Dr. Aftab Ahmad Professor EED
Submitted By Asad Ali Khan 08-EE-23 Waqas Ali 08-EE-35 Qamar-u-Zaman 08-EE-74
A Project Report submitted in partial fulfillment of the requirements for the award of Bachelors Degree in Electrical
Engineering
DEPARTMENT OF ELECTRICAL ENGINEERING FACULTY OF ELECTRONICS & ELECTRICAL
ENGINEERING UNIVERSITY OF ENGINEERING AND TECHNOLOGY
TAXILA
July 2012
Undertaking
We certify that project work titled “Auto Control Design for Power Factor Improvement”
is our own work. No portion of the work presented in this project has been submitted in
support of another award or qualification either at this institution or elsewhere. Where
material has been used from other sources it has been properly acknowledged / referred.
___________________________
Asad Ali Khan
08-EE-23
___________________________
Waqas Ali
08-EE-35
___________________________
Qamar-u-Zaman
08-EE-74
Acknowledgements
We would like to thank our supervisor for guiding us in understanding the concepts of our
final year project. We would like to thank all our teachers especially Dr. Aftab Ahmad for
guiding us in solving our problems related to our project, his cooperation and support to
bring this project to completion.
We would also like to thank our families and friends for their continuous encouragement
and moral support.
Abstract
This project describes the implementation of auto control design for power factor
measurement and improvement using PIC microcontroller.
Power factor correction (PFC) is a technique of counteracting the undesirable effects of
electric loads that create a power factor that is less than one. Power factor correction may
be applied either by an electrical power transmission utility to improve the stability and
efficiency of the transmission network or correction may be installed by individual
electrical customers to reduce the costs charged to them by their electricity supplier. In
order to improve transmission efficiency, power factor correction research has become a
hot topic. Many control methods for the Power Factor Correction (PFC) have been
proposed.
This project describes the design and development of a power factor corrector using PIC
(Programmable Interface Controller) microcontroller chip. This involves measuring the
power factor value from the load using PIC and proper algorithm to determine and trigger
sufficient switching capacitors in order to compensate excessive reactive components, thus
bringing power factor near to unity.
In this project we have used two different loads as follows:
370 WATT single phase induction motor as a load, its low power factor was 0.762.
We have used another load 180 WATT Universal motor.Its low power factor was 0.78.
Table of Contents
CHAPTER 1 INTRODUCTION……………………….……….. 1
1.1 BASIC CONCEPT... …………………………………………. 1 1.2 POWER FACTOR …………………………………………....1 1.3 POWER FACTOR IMPROVEMENT ………………………..2 1.4 ADVANTAGES OF POWER FACTOR
IMPROVEMENT……………………………………………….3 1.5 POWER FACTOR IMPROVEMENT
EQUIPMENT……………………………. …………………….4 1.6 LOCATION OF POWER FACTOR CORRECTION
EQUIPMENT……………………………………………….…..5 1.7 CALCULATION OF POWER FACTOR
CORRECTION…………………………………………….…..5 1.8 MOST ECONOMICAL POWER FACTOR………………..…12 1.9 EXAMPLE……………………………………………………..13
2 CHAPTER 2 MICROCONTROLLER……………………………17
3 2.1 INTRODUCTION …………………………………………..…….17 4 2.2 PIC MICROCONTROLLER ……….………………….………..18 5 2.2.1 ADVANTAGES…………………………………..…..19 6 2.2.2 PERIPHERAL HIGHLIGHT…………………………20 7 2.3 SPECIAL MICROCONTROLLER FEATURES…………….... 20 8 2.4 MEMORY ORGANIZATION …………………. ……………...21 9 2.5 INTERRUPTS…………………………………………….. ……24 10 2.6 I/O PORTS………………………………………………………25 11 2.7 TIMER MODULES…………………………………………… 25 12 2.8 CCP MODULES………………………………………..……….28 13 2.9 MSSP MODULE……………………………………………..…..28 14 2.10 EUSART…………………………………………………….…..29 15 2.11 A/D CONVERTOR……………………………………….….....30 16 2.12 CONFIGURATION BITS…………………………………....…31 17 2.13 WATCH DOG TIMMER……………………………….……….31 18 CHAPTER 3 LCD………………………………………………..33 19 3.1 INTRODUCTION ……………………………………………….33
20 3.2 PIN DESCRIPTION……………………………………………. 33 21 3.3 DDRAM-DISPLAY DATA RAM………………………………..36 22 3.4 CGROM – CHARACTER GENRATOR ROM……………...…37 23 3.5 CGRAM – CHARACTER GENRATOR RAM……………........40 24 3.6 COMMANDS AND INSTRUCTION SET……………………...41 25 3.7 LCD INITIALIZATION………………………………………......44 26 CHAPTER 4 SOFTWARES 27 HIGH TECH AND MPLAB……………………....49 28 4.1 MICROCHIP MPLAB IDE……………..…………………...…...49 29 4.2 HIGH TECH……………………………………………………...56 30 4.3 CREATING AND BUILDING PROJECTS IN MPLAB…..…....59 31 CHAPTER 5 PROJECTS AND ALGORITHIM…………………67 32 5.1 ALGORITHIM…………………………………………………..68 33 5.2 BLOCK DIAGRAM……………………………………………..69 34 5.3PROJECT …………………………………………………………70
CONCLUSION _______________________________________________________________72 FUTURE RECOMMENDATIONS ___________________________________________________ 73 REFERENCES ________________________________________________________________74
List of Figures
Figure 1.1 – Power Triangle ............................................................................................................................ 2 Figure 1.2 – Connection Diagram .................................................................................................................... 7 Figure 1.3 – Series Capacitor ........................................................................................................................... 8 Figure 1.4 – Power Factor Improvement using Synchronous Machine .............................................................. 8 Figure 1.5 – Phasor Diagram ..........................................................................................................................12 Figure 2.1 – Pin Diagram ...............................................................................................................................21 Figure 2.2 – Block diagram of Timer 0 Module ..............................................................................................26 Figure 2.3 – Block Diagram of Timer 1 Module..............................................................................................28 Figure 3.1 – Character LCD type HD44780 Pindiagram………………………………………………34 Figure 3.2 – DDRAM Address for 1 Line LCD……………………………………………. 37 Figure 3.3 – DDRAM Address for 2 Line LCD………………………………………………………………37 Figure 3.4 – DDRAM Address for 4 Line LCD...............................................................................................37 Figure 3.5 – Internal Power Supply reset…………………………………………………….46
Figure 3.6 – Flow chart for LCD initialization………………………………………………………………47
Figure 4.1 –Design .........................................................................................................................................50 Figure 4.2 – MPLAB Manager .......................................................................................................................51 Figure 4.3 – Compiler ....................................................................................................................................53 Figure 4.4 – Creating Project ..........................................................................................................................59 Figure 4.5 –Tool Suit .....................................................................................................................................60 Figure 4.6-Windows………………………………………………………………………………………61 Figure 4.7-Code……………………………………………………………………………………………62 Figure 4.8-Libraries…………………………………………………………………………………………63 Figure 4.9-Build……………………………………………………………………………………………64 Figure 4.10-Path……………………………………………………………………………………………..65 Figure 4.11-Results…………………………………………………………………………………………..66 Figure 5.1 – Algorithim ..................................................................................................................................68 Figure 5.2 – Block Diagram ...........................................................................................................................69
List of Tables
Table 1: Power Factors ......................................................................................................................4 Table2: Character LCD pins with controller……………………………………………… 35
Table 3: Character LCD pins with 2 controller……………………………………….36 Table 4: LCD characters code map for 5x8 dots…………………………………………..38
Table 5: Command and Instruction set for LCD type HD44780…………………………42
Table 6: Frequently used commands and instructions for LCD………………………….. 43
Table 7: Power Supply condition for Internal Reset circuit………………………………..45
Table 8: Language Tools……………………………………………………………………56
1
CHAPTER: 1
INTRODUCTION
BASIC CONCEPT A power factor of one or “unity power factor” is the goal of any
electric utility company since if the power factor is less than one, they have to supply more
current to the user for a given amount of power use. In so doing, they incur more line
losses. They also must have larger capacity equipment in place than would be otherwise
necessary. As a result, an industrial facility will be charged a penalty if its power factor is
much different from 1.
Industrial facilities tend to have a “lagging power factor”, where the
current lags the voltage (like an inductor). This is primarily the result of having a lot of
electric induction motors – the windings of motors act as inductors as seen by the power
supply. Capacitors have the opposite effect and can compensate for the inductive motor
windings. Some industrial sites will have large banks of capacitors strictly for the purpose
of correcting the power factor back toward one to save on utility company charges.
1.2 POWER FACTOR
In an a.c. circuit, there is generally a phase difference between voltage
and current. The term cos ф is called power factor of the circuit. Power factor is also
known as the ratio of true power or watts to apparent power or volt amps. If the circuit is
capacitive, the current leads the voltage and power factor is said to be leading. However if
2
it is inductive, the current lags behind the voltage and the power factor is referred to as
lagging.
Fig 1.1 Power Triangle
We generally describe power factor with word ‘lagging’ or ‘leading’
with the numerical value of power factor to signify whether the current lags or
leads the voltage. For example if the circuit has a power factor of 0.5 and the
current lags the voltage. We generally write p.f. as 0.5 lagging. Similarly if
current leads the voltage we write p.f as .5 leading.
1.2.1 DISADVANTAGES OF LOW POWER FACTOR
Disadvantages of low power factor are given below:
(1) For a given power to be supplied, the current is increased.
3
(2) The current thus increased in-return causes increase in copper losses (PL=I2R) and
decrease in the efficiency of both apparatus and the supply system, which results in
overloading and hence burning of the associated equipment.
(3) Copper losses in transformers also increase.
(4) Generators, transformers, switches, transmission lines and other associated
switchgears become over-loaded.
(5) Voltage regulation of generators, transformers and transmission lines increases.
(6) Hence, cost of generation, transmission and distribution increases.
1.2.2 Causes of Low Power Factor
The following are the causes of low power factor. Low power factor
is caused by inductive loads.
(iv) Induction motors are a prime cause of low power factor for many
customers. Poor power factor is an issue especially for customers with large
numbers of small fractional horsepower motors, those who purchase cheap or
poorly made motors, and those having oversized, under-loaded motors.
(ii) AC motors, transformers, fans, welding equipment, extruders and injection
machines, presses and stamping equipment as well as ballasted lighting are some of the
many prevalent inductive loads that contribute to a “lagging power factor” within an
electrical delivery system.
(iii) The power factor, at which motors operate, falls due to improper maintenance and
repairs of motors. In repaired motors, less wire is sometimes used than originally wound
4
motors, therefore, in such motors leakage of magnetic flux increases and power factor of
the motor decreases.
(iv) Industrial heating furnaces such as arc and induction furnaces operate on
very lagging power factor.
Table 1.1 Power Factors
1.3 POWER FACTOR IMPROVEMENT
A consumer has to pay electricity charges for his maximum demand
in KVA plus the units consumed. if the consumer improves the power factor, then there is
reduction in his maximum KVA demand and consequently there will be annual saving due
to maximum demand charges. Although power factor improvement involves extra annual
expenditure on account of power factor correction equipment, yet improvement of power
factor to proper value results in the net annual saving for the consumer. Power factor can
be improved by installing specially-designed PFC capacitors or reactive power generators
into the electrical distribution system. These capacitors will produce and supplement the
reactive power necessary in the operation of all inductive loads and reduce the amount of
kVA drawn from the main transformer and registered on the meter as "peak demand". The
5
capacitor draws a leading current and partly or completely neutralizes the lagging reactive
component of load current. This raises the power factor of load.
1.4 ADVANTAGES OF POWER FACTOR IMPROVEMENT
Automatic Power Factor improvement capacitors or capacitor banks
applied on the load end of circuit, with lagging power factor (more than 95% loads), have
particular effects, one or more of which may be the reason for the application.
(1) Improves the power factor at the source.
(2) Reduces system losses as current in conductors decreases.
(3) Improves voltage level at the load.
(4) Reduces investment in system facilities per KW of load supplied.
(5) Decreases KVA loading on the source.
(6) Eliminates low power factor penalty imposed by WAPDA.
1.5 POWER FACTOR IMPROVEMENT EQUIPMENT
The low power factor is due to the inductive nature of the load i.e. a
device that draws lagging reactive power. If a device drawing leading reactive power is
connected in parallel with the inductive load, then the lagging reactive power of the load
will be partly neutralized, resulting in improvement of the power factor of the system.
Therefore, when such a device is connected across the load, which takes leading reactive
power such as static capacitors, synchronous machines or synchronous condensers, the
leading reactive component of current drawn by power factor correcting device neutralizes
6
the lagging reactive component of current drawn by the load partly or completely. Power
factor of the system will approach unity when lagging reactive component of load current
is completely neutralized by the leading reactive component of current drawn by power
factor correcting device
Mainly there are three methods to improve the power factor an
inductive load.
1. Static capacitors
2. Synchronous condenser
3. Phase advancers
1. STATIC CAPACITOR
Power factor can be improved by connecting the capacitors in parallel
with the equipment operating at lagging power factor such as induction motors, fluorescent
tubes. Static capacitors have the advantages of small losses (less than 1/2% ) or higher
efficiency (say 99.6%); low initial cost; little maintenance and easy installation. Power
factor can also be improved by connecting static capacitors in series with the line.
Capacitors connected in series with the line neutralize the line reactance. The capacitors,
when connected in series with line, are called the series capacitors, and when connected in
parallel with the equipment are called the shunt capacitors. Shunt capacitors are used in
factories, plants and also on transmission lines. Series capacitors are used on long
transmission lines as they provide automatic compensation with the variation in load.
7
ADVANTAGES
(i) Low initial cost
(ii) High efficiency (approximately 99.6%).
(iii) Low maintenance
(iv) Small losses
(v) They can be easily installed
(vi) They can work under ordinary atmospheric conditions.
DISADVANTAGES
(i) They are easily damaged if voltage exceeds the rated value.
(ii) They have short service life ranging from 8 to 10 years.
(iii) Once the capacitors are damaged, their repair is uneconomical.
In case of 3-phase loads capacitors can be connected either in star or delta, as
shown in below Fig. These capacitors remain connected permanently across the equipment
and are across the supply mains, whenever the equipment is switched on.
Fig 1.2 Connection Type
(a) Y- connected capacitors. (b) Δ – connected capacitors.
8
Series capacitors are used on long transmission lines as they provide automatic
compensation with the variations in load.
Fig 1.3 Series Capacitor
2. SYNCHRONOUS CONDENSER
An over-excited synchronous motor running on no load is called the
synchronous condenser or synchronous phase advancer and behaves like a capacitor, the
capacitive reactance of which depends upon the motor excitation. Power factor can be
improved by using synchronous condensers like shunt capacitors connected across the
supply. Synchronous converters are used where dc supply is needed. The pf of induction
motor of rating exceeding 150 kW may be improved by equipping the set with ac exciter or
phase advancer which supplies the exciting current to the rotor circuit at slip frequency
Fig 1.4 Power factor improvement using synchronous machine
9
In phasor diagram given above phasor IL represents the current draw by the industrial load,
lagging behind the applied voltage V by a large angle øL and phasor IM represents the
current drawn by the synchronous condenser leading the applied voltage V by the angle øm,
The resultant current I is the phasor sum of IL and IM and now angle of lag is much smaller
than θL, Thus overall power factor is improved from cosøL to cosø by the use of the
synchronous condenser. In this way the power factor can be made unity even.
ADVANTAGES
(i) By use of synchronous condensers at intermediate stations, the voltage of the
line can be kept constant at various points along its length, thereby, increasing the current
carrying capacity of the line and improvement of power factor.
(ii) A finer control can be obtained by variation of field excitation. Inherent
characteristic of synchronous condensers of stabilizing variations in the line voltage and
thereby automatically aid in regulation.
(iii) Improvement in the system stability and reduction of the effect of sudden
changes in load owing to inertia of synchronous condenser.
DISADVANTAGES
(i) Comparatively lower efficiency (say 97%) due to losses in rotating
parts and heat losses.
(ii) Noise is produced in operation.
10
(iii) The cost is higher than that of static capacitors of the same rating
(iv) Comparatively higher maintenance and operating costs.
(v) Possibility of synchronous condensers falling out of synchronism causing
interruption of supply.
(vi) Auxiliary equipment is required for starting synchronous condenser
3. PHASE ADVANCERS
Phase advancers are used to improve the power factor of induction
motors. The low power factor of induction motor is due to the fact that its stator winding
draws exciting current which lags behind the supply voltage by 90 degree. If the exciting
ampere turns can be provided from some other a.c. source, then stator winding will be
relieved. Of exciting current and the power factor of the motor can be improved. This is
done by phase advancer which is simply an a.c. exciter. The phase is mounted on the same
shaft as the main motor and is connected in the rotor circuit of motor. It provides exciting
ampere turns to rotor circuit at slip frequency. By providing more ampere turns than
required, the induction motor can be made to operate on leading power factor like an over-
excited synchronous motor.
ADVANTAGES
Phase advancers have two principal advantages.
(i) Phase advancer can be conveniently used where the use of synchronous motors is
inadmissible.
11
(ii) Lagging KVAR drawn by the motor is considerably reduced due to supply of
exciting ampere-turns at slip frequency.
DISADVANTAGES
(i) They are not economical for motors below 200 H.P.
1.6 LOCATION OF POWER FACTOR CORRECTION EQUIPMENT
In case of transmission system, if synchronous condensers are to be employed for power
factor improvement then these should be installed at the receiving end so that,
not only the generators but also the transmission lines are relieved of carrying excessive
current due to poor power factor. However, if synchronous condensers are installed near
the generators then only generators will be relieved from the excessive current component
and the transmission lines will have to carry it.
1.7 CALCULATION OF POWER FACTOR CORRECTION
Consider an inductive load taking a lagging current I at a power
factor cos ф1. In order to improve the power factor of this circuit, the remedy is to connect
such equipment in parallel with load which takes a leading reactive component of the
load. Diagram shows capacitor connected across the load. The capacitor takes a current Ic
which leads the supply voltage V by 90 degree. The current Ic partly cancels the lagging
reactive component of the load current shown in phasor diagram. The resultant circuit
current becomes I’ and its angle of lag is ф2. It is clear that ф2 is less than ф1 so that new
p.f. cos ф2 is more than the previous p.f. cos ф1.
12
Fig 1.5 Phasor Diagram
From the phasor diagram, it is clear that after power factor correction, the lagging reactive
component of load is reduced to I’ sin ф2.
I’ sin ф2 = I sin ф1 – Ic
Ic = I sin ф1 – I‘ sin ф2
Capacitance of capacitor to improve power from cos ф1 to cos ф2
= Ic / ωV
1.8 Most Economical Power Factor
The increase in power demand on the generating station can be met
either by increasing the capacity of the generating plant working at the same pf or by
raising the power factor of the system by installation power factor correction devices.
Owing to improvement of power factor in the beginning the saving in
the generating and distributing plant outweighs the extra cost of the pf correction
v
I’
I I sin ф
Ф2 Ф1
Ic
13
equipment in most of the cases but as the power factor is raised further its cost begins to
approximate to the saving and finally any saving over the plant is obtained by incurring a
greater expenditure on the pf correcting equipment. Thus there is a limit beyond which it is
not economical still further to improve the power factor.
The maximum value to which the power factor can be economically
raised entirely depends upon the relative costs of the generating plant and phase advancing
plant.
When the power factor is improved it involves expenditure on
account of the power factor correcting equipment. Improvement of power factor will result
in reduction of maximum demand and thus affect an annual saving over the maximum
demand charge but on the other hand expenditure is to be incurred every year in the shape
of interest and depreciation on account of the investment made over the power factor
correcting equipment.
The limit of the power factor at which the net saving (saving in
annual maximum demand charges less annual expenditure incurred on power factor
correcting equipment) is maximum is known as economical limit of power factor
correcting. It will be seen that the economical limit of power factor correction is governed
by the relative costs of the supply and power factor correcting equipment.
1.9 Example
Let us take an example of a cement industry with initial load condition of 5000 kVA at
60% power factor with a consumption of 19,20,000 units per month, supplied at 33 KV.
14
Taking the Tariff as below:
1. Demand charges Rs. 144/kVA/month
2. Energy Charges Rs. 4.11 / Unit
3. PF surcharge for each 1% below 90% 1% of (Demand charges
+ Energy Charges)
A. Cost saving due to Power Factor improvement
(i) As we already know, by improving the power factor there will be a reduction in the
kVA demand of the load. Thus, in this case the kVA MD will drop from 5000 kVA (at
60%) to 3333.33 kVA (at 90%):
Power Factor= cos φ = kW/ kVA
Cosφ1 = 0.6 = kW/kvA1 = kW/5000
KW=5000*0.6
Cosφ2 = 0.9 = kW/kVA2
KW=kVA2*0.9
For the same value of kW,
5000*0.6=kVA2*0.9
kVA2=(5000*0.6)/0.9 = 3333.33 kVA
Therefore reduction in energy bill due to reduction in maximum demand due to improved
power factor from 0.6 to 0.9 shall be:
15
Rs. 144.00 * (5000-3333.33)= Rs. 240000.48 per month
(ii) In addition, by increasing the power factor from 60% to 90%, there shall be no power
factor penalty/surcharge on account of low power factor. Thus the savings due to
avoidance of the PF surcharge per month would be as below:
Rs. ((5000-3333)*144*(90-60))*1/100= Rs.72014.14
(iii) Thus the total monthly reduction in bill due to P.F improvement from 0.6 to 0.9 would
be:
Rs. 240000.48 + 72014.14 = Rs. 312014.88 per month.
Net reduction per annum = 312014.88*12 = 3744178.56 ~ Rs.37, 44,179/-
B. Cost of investment for Power Factor improvement:
Size of capacitor required to improve the PF from 0.6 to 0.9
= kVA1* Sinφ1 – kVA2* Sinφ2
=5000*sin (53.1) – 3333.33*Sin(25.84)
=5000*0.8 – 3333.33*0.436
=4000-1453=2547 kVAr say 2550 kAVr
If we take the cost of capacitor bank per kVAr as Rs. 200/- ,
the cost of the capacitor bank = 2550*200 = Rs. 5,10,000/-
Cost of switching and associated equipment = Rs. 3, 00,000/-
and installation, etc.
16
Total cost = Rs. 8, 10,000/-
Annual depreciation and interest@ 20% = Rs. 810000*0.2
= Rs. 1, 62,000/-
Net Annual saving = 37, 44,179 - 1, 62,000 = Rs. 35, 82,179/-
Net monthly saving = Rs. 2, 98,515/-
Therefore payback period = 2.7 months
17
CHAPTER: 2
PIC
MICROCONTROLLER
2.1 Introduction
A microcontroller is a single-chip computer. Before microcontrollers some other
devices were used. Hence it was difficult to make complex circuits. Before micro
controllers use of micro processors were common.
There is a little bit difference between a microcomputer and micro controller. If we
combine ram and rom and other things like input port and out port and if we embed all
these things on a single chip then the name of that device is microcontroller. There are two
types of processor
1) Dedicated Microprocessor
2) General purpose Microprocessor
Dedicated Microprocessor is that processor which is dedicated one particular task
which will perform only one action, action only for which it is made. e.g
microprocessor used in microwave oven, Microprocessor used for washing machine. If
we combine Ram and Rom and other things like input port and out port with
microprocessor then it is known as microcomputer. Hence the difference between
18
microcomputer and microcontroller is that microcontroller is embedded in single chip
whereas microcomputer is not. We need some kind of language for microcontroller.
Well known languages C, Basic, Pascal are being used. Microcontroller or any chip
understands only one language that is machine language (binary language).so we need
some kind of translator if we will use any other language than that of machine
language. Like if we are using assembly language then we need assembler and if we are
using any high level language like c then we need compiler or interpreter. Difference
between compiler and interpreter is that, compiler converts whole high level language
file into object file whereas interpreter converts instruction by instruction.
In our case microcontroller is PIC. There are some benefits of PIC over Atmel.
2.2 PIC Microcontroller
PIC is a family of Harvard architecture microcontrollers made by Microchip
Technology, derived from the PIC1640, originally developed by General Instrument's
Microelectronics Division. The name PIC initially referred to "Peripheral Interface
Controller"
PICs are popular with both industrial developers and hobbyists alike due to their
low cost, wide availability, large user base, extensive collection of application notes,
availability of low cost or free development tools, and serial programming (and re-
programming with flash memory) capability.
The PIC architecture is characterized by its multiple attributes:
Separate code and data spaces (Harvard architecture) for devices other than PIC32,
which has Von Neumann architecture.
A small number of fixed length instructions
19
Most instructions are single cycle execution (2 clock cycles, or 4 clock cycles in
8bit models), with one delay cycle on branches and skips
One accumulator (W0), the use of which (as source operand) is implied (i.e. is not
encoded in the opcode)
All RAM locations function as registers as both source and/or destination of math
and other functions.
A hardware stack for storing return addresses
A fairly small amount of addressable data space (typically 256 bytes), extended
through banking
Data space mapped CPU, port, and peripheral registers
The program counter is also mapped into the data space and writable (this is used to
implement indirect jumps).
There is no distinction between memory space and register space because the RAM serves
the job of both memory and registers, and the RAM is usually just referred to as the
register file or simply as the registers.
2.2.1 Advantages
The PIC architectures have these advantages:
Small instruction set to learn
RISC architecture
Built in oscillator with selectable speeds
Easy entry level, in circuit programming plus in circuit debugging PICKit units
available from Microchip.com for less than $50
Inexpensive microcontrollers
20
Wide range of interfaces including I2C, SPI, USB, USART, A/D, programmable
Comparators, PWM, LIN, CAN, PSP, and Ethernet
We have used PIC 18f4620 which has 28/40/44-Pin Enhanced Flash with 10-Bit A/D
and nanoWatt Technology.
2.2.2 Peripheral Highlights:
• Master Synchronous Serial Port (MSSP) module supporting 3-wire SPI (all 4
modes) and I2C Master and Slave modes
• Enhanced Addressable USART module Supports RS-485, RS-232 and LIN1.2, RS-
232 operation using internal oscillator block (no external crystal required) Auto-Wake-
up on Start bit- Auto-Baud Detect
• 10-bit, up to 13-channel Analog-to-Digital Converter module (A/D):- Auto-
acquisition capability- Conversion available during Sleep
• Dual analog comparators with input multiplexing
• Programmable 16-level High/Low-Voltage Detection (HLVD) module:- Supports
interrupt on High/Low-Voltage Detection
2.3 Special Microcontroller Features:
• C compiler optimized architecture:- Optional extended instruction set designed to
optimize re-entrant code
• 100,000 erase/write cycle Enhanced Flash program memory typical
• 1,000,000 erase/write cycle Data EEPROM memory typical
• Flash/Data EEPROM Retention: 100 years typical
• Self-programmable under software control
21
• Priority levels for interrupts
• 8 x 8 Single Cycle Hardware Multiplier
• Extended Watchdog Timer (WDT):- Programmable period from 4 ms to 131s
• Single-supply 5V In-Circuit Serial Programming (ICSP) via two pins
• In-Circuit Debug (ICD) via two pins
• Wide operating voltage range: 2.0V to 5.5V
• Programmable Brown-out Reset (BOR) with software enable option
Fig 2.1 Pin Diagram
2.4 MEMORY ORGANIZATION
There are three types of memory in PIC18 Enhanced microcontroller devices:
• Program Memory
• Data RAM
• Data EEPROM
As Harvard architecture devices, the data and program memories use separate busses;
this allows for concurrent access of the two memory spaces .The data EEPROM, for
22
practical purposes, can be regarded as a peripheral device, since it is addressed and
accessed through a set of control registers.
2.4.1 Program Memory Organization
PIC18 microcontrollers implement a 21-bit program counter, which is capable of
addressing a 2-Mbyte program memory space. Accessing a location between the upper
boundary of the physically implemented memory and the 2-Mbyte address will return
all ‘0’s (a NOP instruction).
The PIC18F2525 and PIC18F4525 each have 48 Kbytes of Flash memory and can store
up to 24,576 single-word instructions. The PIC18F2620 and
PIC18F4620 each have 64 Kbytes of Flash memory and can store up to 32,768 single-
word instructions. PIC18 devices have two interrupt vectors. The Reset vector address
is at 0000h and the interrupt vector addresses are at 0008h and 0018h.
2.4.2 FLASH PROGRAM MEMORY
The Flash program memory is readable, writable and erasable during normal
operation over the entire VDD range. A read from program memory is executed on one
byte at a time. A write to program memory is executed on blocks of 64 bytes at a time.
Program memory is erased in blocks of 64 bytes at a time. A bulk erase operation may
not be issued from user code. Writing or erasing program memory will cease
instruction fetches until the operation is complete. The program memory cannot be
accessed during the write or erase, therefore, code cannot execute. An internal
23
programming time terminates program memory writes and erases. A value written to
program memory does not need to be a valid instruction. Executing a program memory
location that forms an invalid instruction results in a NOP.
2.4.3 DATA EEPROM MEMORY
The data EEPROM is a nonvolatile memory array, separate from the data RAM and
program memory, which is used for long-term storage of program data. It is not directly
mapped in either the register file or program memory space but is indirectly addressed
through the Special Function Registers (SFRs). The EEPROM is readable and writable
during normal operation over the entire VDD range. Five SFRs are used to read and
write to the data EEPROM as well as the program memory. They are:
• EECON1
• EECON2
• EEDATA
• EEADR
• EEADRH
The data EEPROM allows byte read and writes. When interfacing to the data memory
block, EEDATA holds the 8-bit data for read/write and the EEADRH:EEADR register
pair holds the address of the EEPROM location being accessed. The EEPROM data
memory is rated for high erase/write cycle endurance. A byte write automatically
erases the location and writes the new data (erase-before-write). The write time is
controlled by an on-chip timer; it will vary with voltage and temperature as well as
from chip to chip.
24
2.5 INTERRUPTS
The PIC18F2525/2620/4525/4620 devices have multiple interrupt sources and an
interrupt priority feature that allows most interrupt sources to be assigned a high
priority level or a low priority level. The high priority interrupt vector is at 0008h and
the low priority interrupt vector is at 0018h. High priority interrupt events will interrupt
any low priority interrupts that may be in progress. There are ten registers which are
used to control interrupt operation. These registers are:
• RCON
• INTCON
• INTCON2
• INTCON3
• PIR1, PIR2
• PIE1, PIE2
• IPR1, IPR2
It is recommended that the Microchip header files supplied with MPLAB® IDE be
used for the symbolic bit names in these registers. This allows the assembler/ compiler
to automatically take care of the placement of these bits within the specified register. In
general, interrupt sources have three bits to control their operation. They are:
• Flag bit to indicate that an interrupt event occurred
• Enable bit that allows program execution to branch to the interrupt vector address
when the flag bit is set
• Priority bit to select high priority or low priority. The interrupt priority feature is
enabled by setting the IPEN bit (RCON<7>). When interrupt priority is enabled, there
25
are two bits which enable interrupts globally. Setting the GIEH bit (INTCON<7>)
enables all interrupts that have the priority bit set (high priority). Setting the GIEL bit
(INTCON<6>) enables all interrupts that have the priority bit cleared (low priority).
When the interrupt flag, enable bit and appropriate global interrupt enable bit are set,
the interrupt will vector immediately to address 0008h or 0018h, depending on the
priority bit setting. Individual interrupts can be disabled through their corresponding
enable bits.
2.6 I/O PORTS
Depending on the device selected and features enabled, there are up to five ports
available. Some pins of the I/O ports are multiplexed with an alternate function from
the peripheral features on the device. In general, when a peripheral is enabled, that pin
may not be used as a general purpose I/O pin. Each port has three registers for its
operation. These registers are:
• TRIS register (data direction register)
• PORT register (reads the levels on the pins of the device)
• LAT register (output latch) The Data Latch (LAT register) is useful for read modify
write operations on the value that the I/O pins are driving.
2.7 TIMER MODULE
2.7.1 TIMER0 MODULE
The Timer0 module incorporates the following features:
• Software selectable operation as a timer or counter in both 8-bit and 16-bit modes
26
• Readable and writable registers
• Dedicated 8-bit, software programmable prescaler
• Selectable clock source (internal or external)
• Edge select for external clock
• Interrupt-on-overflow
The T0CON register controls all aspects of the module’s operation including the
prescale selection. It is both readable and writable. A simplified block diagram of the
Timer0 module in 8-bit mode is shown in Figure 11-1. Figure below shows a simplified
block diagram of the Timer0 module in 16-bit mode.
Fig 2.2 Block diagram of the Timer0 module in 16-bit mode
2.7.1.2 Prescaler
An 8-bit counter is available as a prescaler for the Timer0 module. The prescaler is
not directly readable or writable its value is set by the PSA and T0PS2:T0PS0 bits
(T0CON<3:0>) which determine the prescaler assignment and prescale ratio. Clearing the
PSA bit assigns the prescaler to the Timer0 module. When it is assigned, prescale values
from 1:2 through 1:256 in power-of-2 increments are selectable. When assigned to the
Timer0 module, all instructions writing to the TMR0 register (e.g., CLRF TMR0,
MOVWF TMR0, BSF TMR0, etc.) clear the prescaler count.
27
2.7.2 TIMER1 MODULE
The Timer1 timer/counter module incorporates these features:
• Software selectable operation as a 16-bit timer or counter
• Readable and writable 8-bit registers (TMR1H and TMR1L)
• Selectable clock source (internal or external) with device clock or Timer1 oscillator
internal options
• Interrupt-on-overflow
• Reset on CCP Special Event Trigger
• Device clock status flag (T1RUN)
A simplified block diagram of the Timer1 module is shown in Figure below. The
module incorporates its own low-power oscillator to provide an additional clocking option.
The Timer1 oscillator can also be used as a low-power clock source for the microcontroller
in power managed operation. Timer1 can also be used to provide Real-Time Clock (RTC)
functionality to applications with only a minimal addition of external components and code
overhead. Timer1 is controlled through the T1CON Control register. It also contains the
Timer1 Oscillator Enable bit (T1OSCEN). Timer1 can be enabled or disabled by setting or
clearing control bit, TMR1ON (T1CON<0>)
28
Fig 2.3 Block diagram of the Timer1 module
2.8 CAPTURE/COMPARE/PWM (CCP) MODULES
PIC18F2525/2620/4525/4620 devices all have two CCP (Capture/ Compare/ PWM)
modules. Each module contains a 16-bit register which can operate as a 16-bit Capture
register, a 16-bit Compare register or a PWM Master/Slave Duty Cycle register. In 28-pin
devices, the two standard CCP modules (CCP1 and CCP2) operate as described in this
chapter. In 40/44-pin devices, CCP1 is implemented as an Enhanced CCP module with
standard Capture and Compare modes and Enhanced PWM modes.
2.9 MASTER SYNCHRONOUS SERIAL PORT (MSSP) MODULE
The Master Synchronous Serial Port (MSSP) module is a serial interface, useful for
communicating with other peripheral or microcontroller devices. These peripheral devices
may be serial EEPROMs, shift registers, display drivers, A/D converters, etc. The MSSP
module can operate in one of two modes:
• Serial Peripheral Interface (SPI)
29
• Inter-Integrated Circuit (I2C) - Full Master mode- Slave mode (with general address call)
The I2C interface supports the following modes in hardware:
• Master mode
• Multi-Master mode
• Slave mode
2.9.1 SPI Mode
The SPI mode allows 8 bits of data to be synchronously transmitted and received
simultaneously. All four SPI modes are supported. To accomplish communication,
typically three pins are used:
• Serial Data Out (SDO) – RC5/SDO
• Serial Data In (SDI) – RC4/SDI/SDA
• Serial Clock (SCK) – RC3/SCK/SCL
Additionally, a fourth pin may be used when in a Slave mode of operation:
• Slave Select (SS) – RA5/AN4/SS/HLVDIN/C2OUT module when operating in SPI
mode.
2.10 ENHANCED UNIVERSAL SYNCHRONOUS RECEIVER
TRANSMITTER (EUSART)
The Enhanced Universal Synchronous Asynchronous Receiver Transmitter
(EUSART) module is one of the two serial I/O modules. (Generically, the USART is also
30
known as a Serial Communications Interface or SCI.) The EUSART can be configured as a
full-duplex asynchronous system that can communicate with peripheral devices, such as
CRT terminals and personal computers. It can also be configured as a half duplex
synchronous system that can communicate with peripheral devices, such as A/D or D/A
integrated
circuits, serial EEPROMs, etc. The Enhanced USART module implements additional
features, including automatic baud rate detection and calibration, automatic wake-up on
Sync Break reception and 12-bit Break character transmit. These make it ideally suited for
use in Local Interconnect Network bus
(LIN bus) systems. The EUSART can be configured in the following modes:
• Asynchronous (full duplex) with:- Auto-wake-up on character reception - Auto-baud
calibration- 12-bit Break character transmission
• Synchronous – Master (half duplex) with selectable clock polarity
• Synchronous – Slave (half duplex) with selectable clock polarity
2.11 10-BIT ANALOG-TO-DIGITAL CONVERTERS (A/D) MODULE
The Analog-to-Digital (A/D) converter module has 10 inputs for the 28-pin devices and 13
for the 40/44-pin devices. This module allows conversion of an analog input signal to a
corresponding 10-bit digital number. The module has five registers:
• A/D Result High Register (ADRESH)
• A/D Result Low Register (ADRESL)
31
• A/D Control Register 0 (ADCON0)
• A/D Control Register 1 (ADCON1)
• A/D Control Register 2 (ADCON2)
2.12 Configuration Bits
The configuration bits can be programmed (read as ‘0’) or left unprogrammed (read
as ‘1’) to select various device configurations. These bits are mapped starting at program
memory location 300000h. The user will note that address 300000h is beyond the user
program memory space. In fact, it belongs to the configuration memory space (300000h-
3FFFFFh), which can only be accessed using table reads and table writes. Programming
the configuration registers is done in a manner similar to programming the Flash memory.
The
WR bit in the EECON1 register starts a self-timed write to the configuration register. In
normal operation mode, a TBLWT instruction with the TBLPTR pointing to the
configuration register sets up the address and the data for the configuration register write.
Setting the WR bit starts a long write to the configuration register. The configuration
registers are written a byte at a time. To write or erase a configuration cell, a TBLWT
instruction can write a ‘1’ or a ‘0’ into the cell
2.13 Watchdog Timer (WDT)
For PIC18F2525/2620/4525/4620 devices, the WDT is driven by the INTRC
source. When the WDT is enabled, the clock source is also enabled. The nominal WDT
period is 4 ms and has the same stability as the INTRC oscillator. The 4 ms period of the
32
WDT is multiplied by a 16-bit postscaler. Any output of the WDT postscaler is selected by
a multiplexer, controlled by bits in Configuration Register 2H. Available periods range
from 4 ms to 131.072 seconds (2.18 minutes). The WDT and postscaler are cleared when
any of the following events occur: a SLEEP or CLRWDT instruction is executed, the IRCF
bits (OSCCON<6:4>) are changed or a clock failure has occurred.
33
CHAPTER: 3
LCD
3.1 Introduction
The most commonly used Character based LCDs are based on Hitachi's
HD44780 controller or other which are compatible with HD44580. In this tutorial, we will
discuss about character based LCDs, their interfacing with various microcontrollers,
various interfaces (8-bit/4-bit), programming, special stuff and tricks you can do with these
simple looking LCDs which can give a new look to your application.
3.2 Pin Description
The most commonly used LCDs found in the market today are 1 Line, 2 Line or 4 Line
LCDs which have only 1 controller and support at most of 80 characters, whereas LCDs
supporting more than 80 characters make use of 2 HD44780 controllers.
Most LCDs with 1 controller has 14 Pins and LCDs with 2 controller has 16 Pins (two pins
are extra in both for back-light LED connections). Pin description is shown in the table
below.
34
Figure 3.1: Character LCD type HD44780 Pin diagram
Pin No. Name Description
Pin no. 1 VSS Power supply (GND)
Pin no. 2 VCC Power supply (+5V)
Pin no. 3 VEE Contrast adjust
Pin no. 4 RS 0 = Instruction input
1 = Data input
Pin no. 5 R/W 0 = Write to LCD module
1 = Read from LCD module
Pin no. 6 EN Enable signal
Pin no. 7 D0 Data bus line 0 (LSB)
Pin no. 8 D1 Data bus line 1
35
Pin no. 9 D2 Data bus line 2
Pin no. 10 D3 Data bus line 3
Pin no. 11 D4 Data bus line 4
Pin no. 12 D5 Data bus line 5
Pin no. 13 D6 Data bus line 6
Pin no. 14 D7 Data bus line 7 (MSB)
Table2: Character LCD pins with 1 Controller
Pin No. Name Description
Pin no. 1 D7 Data bus line 7 (MSB)
Pin no. 2 D6 Data bus line 6
Pin no. 3 D5 Data bus line 5
Pin no. 4 D4 Data bus line 4
Pin no. 5 D3 Data bus line 3
Pin no. 6 D2 Data bus line 2
Pin no. 7 D1 Data bus line 1
Pin no. 8 D0 Data bus line 0 (LSB)
36
Pin no. 9 EN1 Enable signal for row 0 and 1 (1stcontroller)
Pin no. 10 R/W 0 = Write to LCD module
1 = Read from LCD module
Pin no. 11 RS 0 = Instruction input
1 = Data input
Pin no. 12 VEE Contrast adjust
Pin no. 13 VSS Power supply (GND)
Pin no. 14 VCC Power supply (+5V)
Pin no. 15 EN2 Enable signal for row 2 and 3 (2ndcontroller)
Pin no. 16 NC Not Connected
Table3: Character LCD pins with 2 Controller
Usually these days you will find single controller LCD modules are used more in
the market. So in the tutorial we will discuss more about the single controller LCD,
the operation and everything else is same for the double controller too. Let’s take a
look at the basic information which is there in every LCD.
3.3 DDRAM - Display Data RAM
Display data RAM (DDRAM) stores display data represented in 8-bit character codes. Its
extended capacity is 80 X 8 bits, or 80 characters. The area in display data RAM
37
(DDRAM) that is not used for display can be used as general data RAM. So whatever you
send on the DDRAM is actually displayed on the LCD. For LCDs like 1x16, only 16
characters are visible, so whatever you write after 16 chars is written in DDRAM but is not
visible to the user.
Figures below will show you the DDRAM addresses of 1 Line, 2 Line and 4 Line LCDs.
Figure 3.2: DDRAM Address for 1 Line LCD
Figure 3.3: DDRAM Address for 2 Line LCD
Figure 3.4: DDRAM Address for 4 Line LCD
3.4 CGROM - Character Generator ROM
Now you might be thinking that when you send an ascii value to DDRAM, how the
character is displayed on LCD? So the answer is CGROM. The character generator ROM
38
generates 5 x 8 dot or 5 x 10 dot character patterns from 8-bit character codes (see Figure 5
and Figure 6 for more details). It can generate 208 5 x 8 dot character patterns and 32 5 x
10 dot character patterns. User defined character patterns are also available by mask-
programmed ROM.
Table 4: LCD characters code map for 5x8 dots
39
As you can see in both the code maps, the character code from 0x00 to 0x07 is
occupied by the CGRAM characters or the user defined characters. If user wants to
display the fourth custom character then the code to display it is 0x03 i.e. when user
sends 0x03 code to the LCD DDRAM then the fourth user created character or
pattern will be displayed on the LCD.
40
3.5 CGRAM - Character Generator RAM
As clear from the name, CGRAM area is used to create custom characters in LCD.
In the character generator RAM, the user can rewrite character patterns by program. For 5
x 8 dots, eight character patterns can be written, and for 5 x 10 dots, four character patterns
can be written.
3.5.1 BF - Busy Flag
Busy Flag is a status indicator flag for LCD. When we send a command or data
to the LCD for processing, this flag is set (i.e. BF =1) and as soon as the instruction is
executed successfully this flag is cleared (BF = 0). This is helpful in producing and exact
amount of delay. For the LCD processing.
To read Busy Flag, the condition RS = 0 and R/W = 1 must be met and The MSB
of the LCD data bus (D7) act as busy flag. When BF = 1 means LCD is busy and will not
accept next command or data and BF = 0 means LCD is ready for the next command or
data to process.
3.5.2 Instruction Register (IR) and Data Register (DR)
There are two 8-bit registers in HD44780 controller Instruction and Data register.
Instruction register corresponds to the register where you send commands to LCD e.g LCD
shift command, LCD clear, LCD address etc. and Data register is used for storing data
41
which is to be displayed on LCD. When send the enable signal of the LCD is asserted, the
data on the pins is latched in to the data register and data is then moved automatically to
the DDRAM and hence is displayed on the LCD. Data Register is not only used for
sending data to DDRAM but also for CGRAM, the address where you want to send the
data, is decided by the instruction you send to LCD.
3.6 Commands and Instruction set
Only the instruction register (IR) and the data register (DR) of the LCD can be
controlled by the MCU. Before starting the internal operation of the LCD, control
information is temporarily stored into these registers to allow interfacing with various
MCUs, which operate at different speeds, or various peripheral control devices. The
internal operation of the LCD is determined by signals sent from the MCU. These signals,
which include register selection signal (RS), read/write signal (R/W), and the data bus
(DB0 to DB7), make up the LCD instructions (Table 3). There are four categories of
instructions that:
Designate LCD functions, such as display format, data length, etc.
Set internal RAM addresses
Perform data transfer with internal RAM
Perform miscellaneous functions
42
Table 5: Command and Instruction set for LCD type HD44780
Although looking at the table you can make your own commands and test them. Below is a
breif list of useful commands which are used frequently while working on the LCD.
No. Instruction Hex Decimal
43
1 Function Set: 8-bit, 1 Line, 5x7 Dots 0x30 48
2 Function Set: 8-bit, 2 Line, 5x7 Dots 0x38 56
3 Function Set: 4-bit, 1 Line, 5x7 Dots 0x20 32
4 Function Set: 4-bit, 2 Line, 5x7 Dots 0x28 40
5 Entry Mode 0x06 6
6
Display off Cursor off
(clearing display without clearing DDRAM
content)
0x08 8
7 Display on Cursor on 0x0E 14
8 Display on Cursor off 0x0C 12
9 Display on Cursor blinking 0x0F 15
10 Shift entire display left 0x18 24
12 Shift entire display right 0x1C 30
13 Move cursor left by one character 0x10 16
14 Move cursor right by one character 0x14 20
15 Clear Display (also clear DDRAM content) 0x01 1
16 Set DDRAM address or coursor position on
display 0x80+add* 128+add*
17 Set CGRAM address or set pointer to CGRAM
location 0x40+add** 64+add**
Table 6: Frequently used commands and instructions for LCD
44
* DDRAM address given in LCD basics section see Figure 2,3,4
** CGRAM address from 0x00 to 0x3F, 0x00 to 0x07 for char1 and so on..
The table above will help you while writing programs for LCD. But after you are
done testing with the table 4, i recommend you to use table 3 to get more grip on
working with LCD and trying your own commands. In the next section of the
tutorial we will see the initialization with some of the coding examples in C as well
as assembly.
3.7 LCD Initialization
Before using the LCD for display purpose, LCD has to be initialized either by the
internal reset circuit or sending set of commands to initialize the LCD. It is the user who
has to decide whether an LCD has to be initialized by instructions or by internal reset
circuit. We will discuss both ways of initialization one by one.
3.7.1 Initialization by internal Reset Circuit
An internal reset circuit automatically initializes the HD44780U when the power is turned
on. The following instructions are executed during the initialization. The busy flag (BF) is
kept in the busy state until the initialization ends (BF = 1). The busy state lasts for 10 ms
after VCC rises to 4.5 V.
45
Display clear
Function set:
DL = 1; 8-bit interface data
N = 0; 1-line display
F = 0; 5 x 8 dot character font
Display on/off control:
D = 0; Display off
C = 0; Cursor off
B = 0; Blinking off
Entry mode set:
I/D = 1; Increment by 1
S = 0; No shift
As mentioned in the Note, there are certain conditions that has to be met, if user
want to use initialization by internal reset circuit. These conditions are shown in the
Table 5 below.
Table 7: Power Supply condition for Internal Reset circuit
46
Figure 3.5: Internal Power Supply reset
Now the problem with the internal reset circuit is, it is highly dependent on power supply,
to meet this critical power supply conditions is not hard but are difficult to achieve when
you are making a simple application. So usually the second method i.e. Initialization by
instruction is used and is recommended most of the time.
3.7.2 Initialization by instructions
Initializing LCD with instructions is really simple. Given below is a flowchart that
describes the step to follow, to initialize the LCD.
47
Figure 3.6: Flow chart for LCD initialization
As you can see from the flow chart, the LCD is initialized in the following
sequence...
1) Send command 0x30 - Using 8-bit interface
2) Delay 20ms
3) Send command 0x30 - 8-bit interface
48
4) Delay 20ms
5) Send command 0x30 - 8-bit interface
6) Delay 20ms
7) Send Function set - see Table 4 for more information
8) Display Clear command
9) Set entry mode command - explained below
The first 3 commands are usually not required but are recommended when you are
using 4-bit interface. So you can program the LCD starting from step 7 when
working with 8-bit interface. Function set command depends on what kind of LCD
you are using and what kind of interface you are using (see Table 4 in LCD
Command section).
3.7.3 LCD Entry mode
From Table 3 in command section, you can see that the two bits decide
the entry mode for LCD, these bits are:
a) I/D - Increment/Decrement bit
b) S - Display shift.
With these two bits we get four combinations of entry mode which are 0x04, 0x05,
0x06, 0x07 (see table 3 in LCD Command section). So we get different results with
these different entry modes. Normally entry mode 0x06 is used which is No shift
and auto increment.
49
CHAPTER: 4
SOFTWARES:
HIGHTECH AND MPLAB
4.1 Microchip MPLAB IDE
MPLAB IDE is a Windows Operating System (OS) software program that runs on a PC to
develop applications for Microchip microcontrollers and digital signal controllers. It is
called an Integrated Development Environment, or IDE, because it provides a single
integrated "environment" to develop code for embedded microcontrollers.
4.1.1 The Development Cycle
The process for writing an application is often described as a development cycle, since it is
rare that all the steps from design to implementation can be done flawlessly the first time.
More often code is written, tested and then modified in order to produce an application that
performs correctly. The Integrated Development Environment allows the embedded
50
systems design engineer to progress through this cycle without the distraction of switching
among an array of tools. By using MPLAB IDE, all the functions are integrated, allowing
the engineer to concentrate on completing the application without the interruption of
separate tools and different modes of operation.
The Design Cycle
Figure 4.1: Design Cycle
MPLAB IDE is a "wrapper" that coordinates all the tools from a single graphical user
interface, usually automatically. For instance, once code is written, it can be converted to
executable instructions and downloaded into a microcontroller to see how it works. In this
process multiple tools are needed: an editor to write the code, a project manager to
organize files and settings, a compiler or assembler to convert the source code to machine
code and some sort of hardware or software that either connects to a target microcontroller
or simulates the operation of a microcontroller.
51
4.1.2 Project Manager
The project manager organizes the files to be edited and other associated files
so they can be sent to the language tools for assembly or compilation, and ultimately to a
linker. The linker has the task of placing the object code fragments from the assembler,
compiler and libraries into the proper memory areas of the embedded controller, and ensure
that the modules function with each other (or are "linked"). This entire operation from
assembly and compilation through the link process is called a project "build". From the
MPLAB IDE project manager, properties of the language tools can be invoked differently
for each file, if desired, and a build process integrates all of the language tools operations.
MPLAB IDE Project Manager
Fig 4.2: MPLAB Manager
The source files are text files that are written conforming to the rules of the
assembler or compiler. The assembler and compiler convert them into intermediate
52
modules of machine code and placeholders for references to functions and data storage.
The linker resolves these placeholders and combines all the modules into a file of
executable machine code. The linker also produces a debug file which allows MPLAB IDE
to relate the executing machine codes back to the source files.
A text editor is used to write the code. It is not a normal text editor, but an editor
specifically designed for writing code for Microchip MCUs. It recognizes the constructs in
the text and uses color coding to identify various elements, such as instruction mnemonics,
C language constructs and comments. The editor supports operations commonly used in
writing source code, such as finding matching braces in C, commenting and uncommenting
out blocks of code, finding text in multiple files and adding special bookmarks. After the
code is written, the editor works with the other tools to display code execution in the
debugger. Breakpoints (which stop or "break" the execution of code) can be set in the
editor, and the values of variables can be inspected by hovering the mouse pointer over the
variable name. Names of variables can be dragged from source text windows and then
dropped into a Watch window where their changing values can be watched after each
breakpoint or during code execution.
4.1.3 Language Tools
Language tools are programs such as cross-assemblers and cross-compilers.
Most people are familiar with language tools that run on a PC such as Visual Basic or C
compilers. When using language tools for embedded systems, a "cross-assembler" or
"cross-compiler" is used. These tools differ from typical compilers in that they run on a PC
but produce code to run on another microprocessor, hence they "cross-compile" code for a
microcontroller that uses an entirely different set of instructions from the PC.
53
The language tools also produce a debug file that MPLAB IDE uses to correlate the
machine instructions and memory locations with the source code. This bit of integration
allows the MPLAB IDE editor to set breakpoints, allows watch windows to view variable
contents, and lets you single step through the source code, watching the application
execute. Embedded system language tools also differ somewhat for compilers that run and
execute on a PC because they must be very space conscious. The smaller the code
produced, the better, because that allows the smallest possible memory for the target,
which reduces cost. This means that techniques to optimize and enhance the code using
machine specific knowledge are desirable. The size of programs for PCs typically extends
into the megabytes for moderately complex programs. The size of simple embedded
systems programs may be as small as a thousand bytes or less. A medium size embedded
system might need 32K or 64K of code for relatively complex functions. Some embedded
systems use megabytes of storage for large tables, user text messages or data logging.
A Compiler Converts Source Code into Machine Instructions
Fig 4.3: Compiler
54
4.1.4 Target Debugging
In a development environment, the execution of the code is tested on a debugger.
The debugger can be a software program that simulates the operation of the
microcontroller for testing, or it can be special instrumentation to analyze the program as it
executes in the application.
4.2 Software Debuggers
Simulators are built into MPLAB IDE so a program can be tested without any
additional hardware. A simulator is a software debugger, and the debugger functions for
the simulator are almost identical to the hardware debuggers, allowing a new tool to be
learned with ease. Usually a simulator runs somewhat slower than an actual
microcontroller, since the CPU in the PC is being used to simulate the operations of the
microcontroller. In the case of MPLAB IDE, there are many simulators for each of the PIC
MCU and the dsPIC DSC processors.
4.3 Hardware Debuggers
There are two types of hardware that can be used with MPLAB IDE: programmers
and hardware debuggers. A programmer simply burns the machine code from the PC into
the internal memory of the target microcontroller. The microcontroller can then be plugged
into the application and, hopefully, it will run as designed.
Usually, however, the code does not function exactly as anticipated, and the engineer is
tasked with reviewing the code and its operation in the application to determine how to
modify the original source code to make it execute as desired. This process is called
55
debugging. As noted previously, the simulator can be used to test how the code will
operate, but once a microcontroller is programmed with the firmware, many things outside
the scope of the simulator come into play. Using just a programmer, the code could be
changed, reprogrammed into the microcontroller and plugged into the target for retest, but
this could be a long, laborious cycle if the code is complex, and it is difficult to understand
exactly what is going wrong in the hardware.
This is where a hardware debugger is useful. Hardware debuggers can be in-circuit
emulators, which use specialized hardware in place of the actual target microcontroller, or
they can be in-circuit debuggers, which use microcontrollers that have special built-in
debugging features. A hardware debugger, like a simulator, allows the engineer to inspect
variables at various points in the code, and single step to follow instructions as the
hardware interacts with its specialized circuitry.
4.4 Integrated Development Environment
Debugging usually becomes urgent near the end of the project design cycle. As
deadlines loom, getting the application to function as originally designed is the last step
before going into deployment of the product, and often has the most influence on
producing delays in getting a product out. That's where an integrated development
environment is most important. Doing fine "tweaks" to the code, recompiling, downloading
and testing all require time. Using all tools within a single environment will reduce the
time around the "cycle." These last steps, where critical bugs are worked out, are a test for
the embedded systems designer. The right tool can save time. With MPLAB IDE many
tools can be selected, but they all will have a similar interface, and the learning curve from
simulator to low-cost in-circuit debugger to powerful in-circuit emulator is small
56
4.5 Device Programming
After the application has been debugged and is running in the development
environment, it needs to be tested on its own. A device can be programmed with an in-
circuit emulator, an in-circuit debugger, a development programmer, or a device
programmer. MPLAB IDE can be set to the programmer function, and the part can be
"burned". The target application can now be observed in its nearly final state. Engineering
prototype programmers allow quick prototypes to be made and evaluated. Some
applications can be programmed after the device is soldered on the target PC board. Using
In-Circuit Serial Programming (ICSP) programming capability, the firmware can be
programmed into the application at the time of manufacture, allowing updated revisions to
be programmed into an embedded application later in its life cycle. Devices that support in-
circuit debugging can even be plugged back into an in-circuit debugger after manufacturing
for quality tests and development of next generation firmware.
4.5.1 HI-TECH Language Tools by Microchip
MPLAB IDE supports the following HI-TECH language tools:
Table 8: Language Tools
57
4.5.2 Featuring (HI-TECH C Compilers)
HI-TECH C compilers are enabled with Omniscient Code Generation (OCG), a
whole-program compilation technology, to facilitate more intelligent, state-of-the-art code
generation and enhance product usability. Rather than relying completely on the linker to
uncover errors in independently compiled modules, an OCG compiler completes the initial
stages of compilation for each module separately, but defers object code generation until
the point at which a view of the whole program is available. Information gathered from a
global view of the program, can be used to provide better detection of potential errors in
the user’s code, and to better optimize the output. HI-TECH C compilers can deliver denser
code, improve RAM utilization and reduce interrupt latency.
The all-seeing nature of OCG enables the compiler to determine if a variable is
being used in the program. Unused variables are removed, thus saving RAM.
OCG enables a compiler to determine which variables are used in a program.
Those which are not used are removed to save RAM.
The compiler knows exactly which registers are in both interrupt and mainline
context, so it can generate code accordingly, minimizing both the code size and
cycles required to switch contexts.
OCG allows automatic allocation of data into RAM banks eliminating the need for
the programmer to specify the location of the variables.
OCG has the ability to generate a printf function that is customized for the program
at hand. It does this by scanning the user’s code and only includes those features of
printf that were detected. This results in a huge saving in program memory but also
saves you valuable RAM space.
58
By only including the features of printf in the user's code, OCG has the ability to
generate a print function that is customized for the program at hand, saving
significant amounts of program memory and valuable RAM space.
The compiler detects how frequently each variable is used and which are
dependent, enabling it to optimize pointers and position objects in the most efficient
memory spaces, eliminating the need for this to be done manually with non-
standard C language extensions.
Fully ANSI-compliant
Includes Library source – for standard libraries and sample code for I/O drivers
Includes macro assembler, linker, preprocessor and one-step driver
Runs on Windows, Linux and Mac OS X
59
4.6 Creating and Building Projects in MPLAB
Fig 4.4: Creating Project
Go to ‘PROJECT’ menu PROJECT WIZARD
Click next and you will see the following window
60
Click next and select the language tool suit. If you wish to code in C then your
tool suit must be ‘MICROCHIP C18 TOOLSUIT’ as shown below
Fig 4.5: Tool Suit
61
Next create project folder and then click next two times. The following window
appears
Fig 4.6: Windows
62
Write the C code in the editor window. Then save it with .C extension
Fig 4.7: Code
63
Next go to VIEW PROJECT menu. The following window will appear. Right
click on SOURCE FILES and add the .c file which you just saved. The added file
appears
Fig 4.8: Libraries
64
Then go to PROJECTS menu BUILD OPTIONS PROJECT. The following
window appears
Fig 4.9: Build
65
In ‘ SHOW DIRECTORIES FOR: ‘ option, select ‘INCLUDE SEARCH PATH’. Then
click ‘NEW’ and browse for ‘h’ directory.
Fig 4.10: Path
66
Similarly select ‘LIBRARY SEARCH PATH’ in the ‘SHOW DIRECTORIES
FOR’ option. Click ‘NEW’ and browse for ‘lib’ directory. Now the settings are
complete. Build the project and yo should see the following window.
Fig 4.11: Results
67
CHAPTER:5
PROJECT
AND
ALGORITHMS
68
5.1 Algorithm
Fig 5.1: Algorithm
69
5.2 BLOCK DIAGRAM
Fig 5.2: Block Diagram
AC
POWER
CAPACITOR
VOLTAG SENSE
CURRENT SENSE
LOAD
POWER MANAGEMENT IC
CONTROLLER
CAPACITOR
SWITCHES
70
5.4 PROJECT
5.4.1 Goal
The main goal of our project is to automatically improve the power factor of single phase
power system. We have used PIC18 microcontroller along with metering chip, EEPROM,
capacitor banks, Contactors, ct and pt.
Components used in Project
i. PIC 16F877 microcontroller
ii. Relays
iii. Capacitors
iv. Current and potential transformers
v. LCD
vi. OPT PC817
vii. Regulated DC Supply 5V
viii. Load (Motors)
5.4.2 Explanation
7.4.2.1 CT and PT
The job of the CT and PT is to extract sample of high voltage and current from the
load which is connected to the power source and step down to such a value that can
be used for measurement.
71
5.4.2.4 Microcontroller
PIC take measurement data, then separates all the measurements (voltage, current,
power, active, reactive) .
Then PIC calculates PF using KW/KVA..
Then after displaying that PF on LCD it also checks weather it is below 0.98 or not.
If it is below 0.98 then PIC switches capacitors with the help of relays and finds
and applies the best combination of capacitors, so that PF will remain 0.98.
The controller continues to monitor the PF and if the PF is below 0.98 , then the
above steps are repeated
5.4.2.5 Relays
Practically relays cannot be driven by the microcontroller directly due to low output
driving current. We need to use buffer to convert the low current of the controller to
a high value that can drive the relay. Transistors can be used for this purpose.
5.4.2.6 LCD
LCD displays the PF of the single phase system
72
Conclusion
Benefits of increased Power Factor to different consumers can be described as below.
The Consumers whose applicable tariffs do not include MD charges and Power Factor
surcharge shall benefit from reduction in energy consumption due to increased efficiency
of their system, better voltage profiles, reduced I2R losses and release of system capacity.
The consumers whose applicable tariffs include MD charges and the PF surcharge shall be
able to reduce their energy demand as well as consumption and thus shall benefit from both
the reduced cost of energy and reduced consumption of electricity. These consumers can
expect a payback period of under one year when power factor correction is properly
applied.
We started the project with the objectives mentioned in the project statement and achieved
all of them.
We have used two inductive loads.
1: 370 WATT single phase induction motor as a load
Its low power factor was 0.762: we have used another load 180 WATT Universal motor.
Its low power factor was 0.78
73
Future Recommendations
We would like to recommend the following features to be incorporated in our developed
software
1. We have implemented the improvement using capacitor banks. It can be performed
by Synchronous Condensers.
2. GUI interface could be established using MATLAB.
3. Pre-defined power factors could be fed into the system and improved accordingly.
4. Wireless connectivity can be done.
74
References
[1] ABB, T echn ica l App l icat io n Paper s, Power facto r co rrect io n
and har mo n ic f i lt er ing in e lect r ica l p lan t s. Ju ly 2008.
[2] Single Phase Factor Correction Circuit with Wide Output Voltage Range by Yiqing
Zhao.
[3] HADI SADAT, Mc Graw Hills, Power Systems Analysis.
[4] ht tp: //www.envis ionenergy.com/services_pfactorc_bot tom.htm
[5] ht tp: //en.wik ipedia.org/wiki/Power_factor .
[6] ECONOMIC COMPARISION OF POWER FACTOR CORRECTION BY
CAPACITORS AND HIGH POWER FACTOR/HIGH-EFFICIENCY MOTORS BY
K.D. Slack, B.L. Capehart
[7] ADB Final Report, Islamic Republic Of Pakistan, Rental Power Review, January 2010
[8] IEEE TRANSACTIONS ON INDUSTRIAL ELECTRONICS, VOL. 31, NO. I,
FEBRUARY 1990 77, A Microprocessor-Based Adaptive Power Factor Corrector for
Nonlinear Loads, By H. M. EL-BOLOK, M. E. MASOUD, AND M. M. MAHMOUD.
[9] Proceedings of MUCEET2009, Malaysian Technical Universities Conference on
Engineering and Technology, June 20-22, 2009, MS Garden, Kuantan, Pahang, Malaysia
MUCEET2009.
[10] ABB, Application manual, Dry type power factor correction capacitors
75
[11 Industrial Energy Efficiency, Generic Report, on Energy Efficiency in Steel Sector,
NPO Pakistan, May 2008.
[12] www.powerflowtechnologies.com
[13] Sanjiv Arora ,AEE ,MPSEB, Jabalpur Postal address , 45, Satyanand Vihar, Rampur,
Jabalpur, M.P.,
[14] Energy Loss Reduction In WAPDA Power Distribution By Engr. Daud Beg, MD Al-
Technique. Corporation. Islamabad
76