You are on page 1of 78

DESIGN & DEVELOPMENT OF A PIC 16F877A BASED FUZZY TEMPERATURE CONTROLLER

THESIS SUBMITTED IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE AWARD OF THE DEGREE OF

MASTER OF TECHNOLOGY IN VLSI DESIGN & MICROELECTRONICS TECHNOLOGY


BY

SEKHAR RANA

Under the Supervision of

Prof. M. K. NASKAR

Department of Electronics & Tele-Communication Engineering Jadavpur University Kolkata-700032 West Bengal, India May 2010

Faculty of Engineering & Technology Jadavpur University

This to certify that the thesis entitled DESIGN & DEVELOPMENT OF A PIC 16F877A BASED FUZZY TEMPERATURE CONTROLLER has been carried out by Sekhar Rana (college Roll No. : 000710703016 of 2007-2008 and Registration No. : 100871 of 2007-08 and Examination Roll no. : M6VLSI10-15) under my guidance and supervision and be accepted in partial fulfillment of the requirement for the degree of Master of Technology in VLSI design & Microelectronics Technology.

_________________________ Prof. M. K. Naskar Professor (Dept. of ETCE) Jadavpur University Kolkata-70032 West Bengal, India

________________________ Prof. Bhaskar Gupta H.O.D (Dept. of ETCE) Jadavpur University Kolkata-70032 West Bengal, India

_____________________________ Prof. N. Chakraborty Dean, Faculty of Engg. & Technology Jadavpur University Kolkata-70032 West Bengal, India

Faculty of Engineering & Technology


Jadavpur University

CERTIFICATE OF APPROVAL *
The forgoing thesis, entitled DESIGN & DEVELOPMENT OF A PIC 16F877A
BASED FUZZY TEMPERATURE CONTROLLER is hereby approved as a

creditable study of an engineering subject carried and presented in a manner satisfactory to warrant its acceptance as prerequisite to the degree for which it has been submitted. It is understood this by this approval the undersigned do not necessarily endorse or accept every statement made, opinion expressed or conclusion drawn therein but approve the thesis only for the purpose for which it has been submitted.

Committee on final Examination for Evaluation of the thesis

.. (ADDITIONAL EXAMINER)

_________________________ (Prof. M. K. NASKAR) (SUPERVISOR) * Only in case the thesis is approved.

Acknowledgement
The satisfaction that accompanies the successful completion of any task would be incomplete without the mention of the people who make it possible and whose constant guidance and encouragement grown all the efforts with success. The acknowledgement transcends the reality of formality when I would like to express deep gratitude and respect to all those people behind the screen who guided, inspired and helped me for the completion of my project work. I would like to acknowledge my sincere appreciation to Prof. Mrinal Kanti Naskar, Department of Electronics and Telecommunication Engineering, Jadavpur University for this immense guidance, valuable advice & constructive suggestions in carrying out this thesis work. He directed me very patiently but with great enthusiasm and concrete interest towards the great efficiency of this work. I was fully allowed to have necessary freedom to exercise thoughtful and scientific approach to the problem. My sincere thanks to Prof. Bhaskar Gupta, Head of the Department, Electronics and Telecommunication Engineering, Jadavpur University who was kind enough to provide me with all the necessary facilities to carry out this project.

I would like to thank Sourav (Sourav Ghosh), Lecturer of CIEM and my other friends for their immense help to develop the project.

I would like to thanks to my beloved parents & all of my family members for their continual encouragement.

Dated:

Regards

Place:

______________________ (Sekhar Rana)

ABSTRACT
Temperature deviation plays a negative impact on sophisticated instruments in hardware industries as well as it shows its importance in different types of commercial applications. An immense temperature difference may cause various difficulties and can damage the various components that use in the particular system, so it is very necessary to take the desire step to solve this problem automatically. To control the temperature automatically, here we make an autonomous system which will measure the temperature of the particular system & shows the deviation of temperature visually and take necessary step to solve the problem. There are several ways to eradicate this problem, but here we choose the particular one that will able to handle it quite easily and more effectively. For this purpose, we introduce PIC (peripheral interface controller) Microcontroller [16f877A] based temperature controller & to control its operation use Fuzzy logic to make it more efficient. A fuzzy logic was used to perform the temperature control. The idea behind the use of the fuzzy logic was from the fact that which can be applied for control of complex systems wherein mathematical model is not available.

Contents
1. Introduction
1.1. 1.2. 1.3. 1.4. 1.5. 1.6. 1.7. 1.8. Background Scope of the project Introduction of PIC 16F877A DC motor driver module Voltage regulator (KA 7805) Potentiometer Module Fuzzy Logic module Organization 2 3 4 5 7 8 10 18

2. System Overview
2.1. 2.2 2.3 Overview of the autonomous system System description Flow Chart of the System 20 21 23

3. Hardware design & Implementation 3.1 3.2 3.3 3.4 3.5 Connection diagram of PIC 16F877A Connection diagram of Sensor (LM 35) Connection diagram of LCD Module Connection diagram of DC motor Short description of the components 25 26 27 28 29

4. Software Design & Implementation 4.1 4.2 4.3 Introduction to MikroC How to Build a Project MikroC Libraries 36 36 41 47 51 52 54

5. Results of Experiment 6. Conclusion and Future Scope Bibliography Appendix

CHAPTER 1
iNTRODUCTiON

Chapter 1 Introduction

1.1 Background:

Since the down of civilization, Temperature change plays a pivotal role on human beings. Now we are living on modern era, we never bothered to tolerate the negative effects due to the deviation of temperature. It not only hampers the living style of mankind but also shows huge negative impact the operation on different types of instruments, it ruins the freshness of vegetables and it may causes different types diseases due to the sudden change of temperature (e.g.-chicken pox). In some occasions it is very essential to maintain the temperature up to some extent otherwise it may take life also (e.g. - In the case of born of pre-mature/term baby, it is very essential to preserve the baby in particular temperature). Today we are living in the generation where we are very much dependent on different type of electronics gadgets; operation of the electronics circuitry, integrated chip is very much effected due to the deviation of temperature. Due to the rise of temperature may reduce the life span or it may damage the gadgets. Every sophisticated electronic instrument can operate safely in a particular temperature range, after knowing the particular temperature range; we have to maintain it.

Chapter 1 Introduction

1.2 Scope of the project:

Since this problem is related to the life and property of the human kind so it is very essential, to build a system to give a possible solution of this threatening problem. Accurate identification of temperature, temperature deviation is very important. Manually we can control it up to some extent, but always it is not possible. It is quite tedious and error inductive. So it is very essential to build an autonomous system which will maintain it automatically and reduce man power.

The system which we have built will measures the temperature deviation (with respect to reference temperature) and take the necessary decision automatically and keep the temperature in a particular level for satisfactory operation. This detection of temperature change will be done automatically to provide more flexibility to that done manually. The system has a temperature sensor which detects the actual and error value of the temperature. The analog voltage value obtained from the sensor is then fed to a controller whose job is to provide a unique digital value for each analog voltage value. After fuzzification & defuzzification we get the desire value at the output. This particular defuzzified value determines the rotation speed of the DC motor.

Chapter 1 Introduction

1.3 Introduction of PIC 16F877A


Peripheral interface controller (PIC) is a family of microcontrollers by Microchip Technology. PIC microcontrollers have attractive features and they are suitable for a wide range of application. In this project report emphasis is on 8 bit PIC 16F877A. This is because the Microchip PIC microcontroller are very easy to use and can be run perfectly well by simply plugging them into a prototype board, adding the crystal Oscillator, along with two capacitors. The choice of 16F877A for discussion in this chapter is just to make the reader familiar with the minimum common features in PIC devices. One of the major advantages of the PIC microcontroller is that they are parallel in their architecture and the programming approach for the devices. The PIC microcontroller was designed using Harvard Architecture, with separate address spaces for data (SRAM), Program (FLASH or EPROM) and EEPROM memory. PIC processor with few exception do not allow for direct access to their program memory space.

Fig. 1.1: Pin diagram of the PIC 16F877A

Chapter 1 Introduction

1.4 DC motor driver module


L293D is a dual H-bridge motor Driver, so with one IC we can interface two DC Motors which can be controlled in both clockwise and counter clockwise direction and I have the motor with fix direction of motion. I can make use of all the four I/Os to connect up to four DC motors. L293D has output current of 600mA and peak output current of 1.2A per channel. Moreover for protection of circuit from back E.M.F output diodes are included within the IC. The output supply (VCC2) has a wide range from 4.5V to 36 V, which has made L293d a best choice for DC motor driver.

Fig. 1.2: L293D Dual H-bridge Motor Driver 5

Chapter 1 Introduction

A simple schematic for interfacing a DC motor using L293D is shown below.

Fig. 1.3: schematic for interfacing a DC motor Table 1.1: Truth Table of DC motor operation

A
0 0 1 1

B
0 1 0 1

Description
Motor stops or Breaks. Motor runs Anti-Clockwise Motor runs Clockwise Motor stops or Breaks

Three Pins are needed for interfacing a DC motor (A, B, Enable).Output to be enabled completely then I can connect to VCC and only two pins needed from controller to make the motor work. This truth table is same for both BJT and microcontroller.

Chapter 1 Introduction

1.5 Voltage regulator (KA7805)


The KA78XX/KA78XXA series of three-terminal positive regulator are available in the TO-220/D-PAK package and with several fixed output voltages, making them useful in a wide range of applications. Each type employs internal current limiting, thermal shut down and safe operating area. Protection, make it essentially indestructible. If adequate heat sinking is provided, they can deliver over 1A output current. Although designed primarily as fixed voltage regulators, these devices can be used to obtain adjustable voltages and currents.

Features
Output Current up to 1A. Output Voltages of 5, 6, 8, 9, 10, 12, 15, 18, 24V. Thermal Overload Protection. Short Circuit Protection.

Fig. 1.6: Voltage regulator (KA7805)

Chapter 1 Introduction

1.7 Potentiometer module


A potentiometer (colloquially known as a "pot") is a three-terminal resistor with a sliding contact that forms an adjustable divider. If only two terminals are used (one side and the wiper), it acts as a variable resistor or rheostat. Potentiometers are commonly used to control electrical devices such as volume controls on audio equipment. Potentiometers operated by a mechanism can be used as position transducers, for example, in a joystick. Potentiometers are rarely used to directly control significant power (more than a watt). Instead they are used to adjust the level of analog signals (e.g. volume controls on audio equipment), and as control inputs for electronic circuits. For example, a light dimmer uses a potentiometer to control the switching of a TRIAC and so indirectly control the brightness of lamps. A potentiometer is constructed with a resistive element formed into an arc of a circle, and a sliding contact (wiper) traveling over that arc. The resistive element, with a terminal at one or both ends, is flat or angled, and is commonly made of graphite, although other materials may be used. The zwiper is connected through another sliding contact to another terminal. On panel pots, the wiper is usually the center terminal of three. For single-turn pots, this wiper typically travels just under one revolution around the contact. "Multi-turn" potentiometers also exist, where the resistor element may be helical and the wiper may move 10, 20, or more complete revolutions, though multi-turn pots are usually constructed of a conventional resistive element wiped via a worm gear. Besides graphite, materials used to make the resistive element include resistance wire, carbon particles in plastic, and a ceramic/metal mixture called cermets. In a linear slider pot, a sliding control is provided instead of a dial control. The resistive element is a rectangular strip, not semi-circular as in a rotary potentiometer. Due to the large opening slot or the wiper, this type of pot has a greater potential for getting contaminated.

Fig. 1.7: Potentiometer (Pot)

Chapter 1 Introduction

Fig. 1.8: Inside view of Potentiometer (Pot)

Potentiometers can be obtained with either linear or logarithmic relations between the slider position and the resistance (potentiometer laws or "tapers"). A letter code ("A" taper, "B" taper, etc.) may be used to identify which taper is intended, but the letter code definitions are variable over time and between manufacturers. Manufacturers of conductive track potentiometers use conductive polymer resistor pastes that contain hard wearing resins and polymers, solvents, lubricant and carbon the constituent that provides the conductive/resistive properties. The tracks are made by screen printing the paste onto a paper based phenolic substrate and then curing it in an oven. The curing process removes all solvents and allows the conductive polymer to polymerize and cross link. This produces a durable track with stable electrical resistance throughout its working life.

Applications:
Potentiometers are widely used as user controls, and may control a very wide variety of equipment functions. The widespread use of potentiometers in consumer electronics has declined in the 1990s, with digital controls now more common. However they remain in many applications, such as volume controls and as position sensors.

Chapter 1 Introduction

1.8 Fuzzy Logic Module


Introduction:
It is an advanced area of computation which can be applied for control the complex system wherein mathematical model is not available. Fuzzy logic is a form of multi-valued logic derived from fuzzy set theory to deal with reasoning that is approximate rather than precise. The degree of truth of a statement can range between 0 and 1 and is not constrained to the two truth-values of classic propositional logic. Fuzzy logic is widely used in machine control. The term itself inspires a certain skepticism, sounding equivalent to "half-baked logic" or "bogus logic", but the "fuzzy" part does not refer to a lack of rigorous in the method, rather to the fact that the logic involved can deal with fuzzy conceptsconcepts that cannot be expressed as "true" or "false" but rather as "partially true". Although genetic algorithms and neural networks can perform just as well as fuzzy logic in many cases, fuzzy logic has the advantage that the solution to the problem can be cast in terms that human operators can understand, so that their experience can be used in the design of the controller. This makes it easier to mechanize tasks that are already successfully performed by humans.

Background and Evolution of Fuzzy Logic: -

In the early 1900s,

Lukasiewicz came and proposed a systematic alternative to the bi-valued logic (bivalence) of Aristotle. Knuth, a former student of Lukasiewicz proposed a three-valued logic apparently missed by Lukasiewicz, which is used an integral range [-1, 0 +1] rather than [0, 1, 2]. Nonetheless, this alternative failed to gain acceptance. Lotfi A. Zadeh, a professor of UC Berkeley in California, published his seminal work "Fuzzy Sets" which described the mathematics of fuzzy set logic. This theory proposed making the membership function (or the values False and True) operate over the range of real numbers [0.0, 1.0]. For example, consider an antilock braking system, directed by a microcontroller chip. The microcontroller has to make decisions based on brake temperature, speed, and other variables in the system.

10

Chapter 1 Introduction

Fig. 1.9: Pictorial view of FUZZY controller Fuzzy controllers are very simple conceptually. They consist of an input stage, a processing stage, and an output stage. The input stage maps sensor or other inputs, such as switches, thumbwheels, and so on, to the appropriate membership functions and truth values. The processing stage invokes each appropriate rule and generates a result for each, then combines the results of the rules. Finally, the output stage converts the combined result back into a specific control output value. As discussed earlier, the processing stage is based on a collection of logic rules in the form of IF-THEN statements, where the IF part is called the "antecedent" and the THEN part is called the "consequent". Typical fuzzy control systems have dozens of rules. Consider a rule for a temperature control system:IF (temperature is "cold") THEN (heater is "high") This rule uses the truth value of the "temperature" input, which is some truth value of "cold", to generate a result in the fuzzy set for the "heater" output, which is some value of "high". This result is used with the results of other rules to finally generate the crisp composite output. Obviously, the greater the truth value of "cold", the higher the truth value of "high".

11

Chapter 1 Introduction

These operations may have precise definitions, though the definitions can vary considerably between different implementations. "Very", for one example, squares membership functions; since the membership values are always less than 1, this narrows the membership function. "Extremely" cubes the values to give greater narrowing, while "somewhat" broadens the function by taking the square root.There are several different ways to define the result of a rule, but one of the most common and simplest is the "max-min" inference method, in which the output membership function is given the truth value generated by the premise. Rules can be solved in parallel in hardware, or sequentially in software. The results of all the rules that have fired are "defuzzified" to a crisp value by one of several methods. There are dozens in theory, each with various advantages and drawbacks. The "centroid" method is very popular, in which the "center of mass" of the result provides the crisp value. Another approach is the "height" method, which takes the value of the biggest contributor. The centroid method favors the rule with the output of greatest area, while the height method obviously favors the rule with the greatest output value. The example below demonstrates max-min inference and centroid defuzzification for a system with input variables "x", "y", and "z" and an output variable "n". Note that "mu" is standard fuzzy-logic nomenclature for "truth value":

Fig. 1.10: Centroid Defuzzification method

12

Chapter 1 Introduction

Notice how each rule provides a result as a truth value of a particular membership function for the output variable. In centroid defuzzification the values are OR'ed, that is, the maximum value is used and values are not added, and the results are then combined using a centroid calculation. * Fuzzy control system design is based on empirical methods, basically a methodical approach to trial-and-error. The general process is as follows:

Document the system's operational specifications and inputs and outputs. Document the fuzzy sets for the inputs. Document the rule set. Determine the defuzzification method. Run through test suite to validate system, adjust details as required. Complete document and release to production.

As a general example, consider the design of a fuzzy controller for a steam turbine. The block diagram of this control system appears as follows:

Fig. 1.11: Block diagram of FUZZY control system There are two input variables, temperature and pressure, and a single output variable, the turbine throttle setting. The turbine's operation can be reversed, so the throttle setting can be positive or negative.

13

Fig. 1.12: FUZZY set mapping

The throttle settings are defined as follows:


N3: N2: N1: Z: P1: P2: P3: Large negative. Medium negative. Small negative. Zero. Small positive. Medium positive. Large positive.

The rule set includes such rules as:


Rule 1: IF temperature IS cool AND pressure IS weak, THEN throttle is P3. Rule 2: IF temperature IS cool AND pressure IS low, THEN throttle is P2. Rule 3: IF temperature IS cool AND pressure IS ok, THEN throttle is Z. Rule 4: IF temperature IS cool AND pressure IS strong, THEN throttle is N2.

14

Chapter 1 Introduction

In practice, the controller accepts the inputs and maps them into their membership functions and truth values. These mappings are then fed into the rules. If the rule specifies an AND relationship between the mappings of the two input variables, as the examples above do, the minimum of the two is used as the combined truth value; if an OR is specified, the maximum is used. The appropriate output state is selected and assigned a membership value at the truth level of the premise. The truth values are then defuzzified.

Fig. 1.12: FUZZY evaluation Rule (2)

Fig.1.13: FUZZY evaluation Rule (3)

15

Chapter 1 Introduction The two outputs are then combined:

Fig. 1.14: Centroid Defuzzification

The output value will adjust the throttle and then the control cycle will begin again to generate the next value.

Characteristics of FUZZY Logic:


1. In fuzzy logic, exact reasoning is viewed as a limiting case of approximate 2. In fuzzy logic everything is a matter of degree. 3. Any logical system can be fuzzified. reasoning.

16

Chapter 1 Introduction

Advantages
FL offers several unique features that make it a particularly good choice for many control problems. 1) It is inherently robust since it does not require precise, noise-free inputs and can be programmed to fail safely if a feedback sensor quits or is destroyed. The output control is a smooth control function despite a wide range of input variations. 2) Since the FL controller processes user-defined rules governing the target control system, it can be modified and tweaked easily to improve or drastically alter system performance. 3) FL is not limited to a few feedback inputs and one or two control outputs, nor is it necessary to measure or compute rate-of-change parameters in order for it to be implemented. Any sensor data that provides some indication of a system's actions and reactions is sufficient. 4) FL can control nonlinear systems that would be difficult or impossible to model mathematically. This opens doors for control systems that would normally be deemed unfeasible for automation. 5) Fuzzy logic controller is faster than the conventional PID controller. 6) Fuzzy Logic Controller is useful in reaching the set point faster. 7) Fuzzy Logic Controller much closer in spirit to human thinking and decision making. 8) Fuzzy Logic Controller can be designed even when the understanding of the system is incomplete; when it is difficult to construct the mathematical model of the system. 9) Fuzzy Logic Controller is easier to prototype & implement for most system without any modification.

17

Chapter 1 Introduction

1.9 Organization

This project work consists of seven chapters. The chapter 1 of this project presents an introduction to the system. It includes PIC 16F877A Microcontroller, Voltage Regulator, Potentiometer, Fuzzy Logic modules. The 2nd chapter discusses the system overview. It describes the way in which the autonomous system is designed. It also shows the circuit connection among them. Next chapter deals with Hardware design and Implementation. It describes different hardware module that used to design the autonomous system. It deals with connection between them and their short descriptions. Software also plays a vital role to design the system, so it is in the immediate chapter (chapter 4). Next the obtained results and a discussion are presented in chapter 5.The conclusion and future scope of the project is shown in chapter 6.Appendix section is provided for further details of the topics.

18

CHAPTER 2
SYSTEM OVERViEW

19

Chapter2- System overview

2.1 Overview of the autonomous system:

Fig. 2.1: Block diagram of the autonomous system 20

Chapter2- System overview

2.2 System description:


Figure 2.1, shows the block diagram of a PIC 16F877A based fuzzy temperature control system. It is an autonomous system, no need to handle manually. The block diagram of the system shows different kinds of hardware components, Such as-

Voltage regulator (KA 7805). It provides +5 Volt DC output power supply, which help to operate the total circuitry. It plays a great role in this system because voltage fluctuation may cause harmful to the system. See chapter 1 for the details of Voltage regulator (KA 7805).

Another very important component is Sensor (LM 35) .It may call input of the system. It sense temperature of the environment and fed to the PIC 16F877A microcontroller. For the details of LM 35, see chapter 3.

Most important component of this autonomous system is PIC 16F877A microcontroller. It is called the heart of this system. It almost controls the entire component those use in this system. Firstly it collects analog data from the sensor, then by using its ADC module it converts its equivalent digital data to the respective output port. According to program it transfers data to different system components. For the details of PIC 16F877A microcontroller module see the APPENDIX A.

Another key component of this system is LCD display device. It shows visually the current temperature of the environment. Here we use 16x2 LCD modules, by which we display four data string. For the details of the LCD display see chapter3 and APPENDIX A.

21

Chapter2- System overview

This system also includes another important hardware component which is known as DC motor driver (L293D). If we connect the DC motor directly to the PIC microcontroller then back e.m.f may damage the microcontroller, so it is very essential. For details see chapter1.

Final component or Output component that use in this system is DC motor. Applying desire PWM duty cycle provided by the microcontroller and controlled by the fuzzy logic is applied to the DC motor. So it rotates according to the defuzzification value of the fuzzy controller which controls the rising temperature of the system. For further details see chapter1.

22

Chapter2- System overview

2.3 Flow chart of the system:


BEGIN

Introduce PIC16F877 XT, OSC, WDT OFF

ENTER Constants

PORT A = INPUT RA2 = ANALOG I/P PORT B = OUTPUT

E (t) =0 E (t-1) =0

CALL DELAY

GET ADC

Result of A/D Conversion = y

y = 0?

WRITE ZERO TO PORT B

e (t) e (t-1) = CHANGE OF ERROR

FUZZY CONTROL PROCESS WRITE Y TO PORT B

Fig. 2.2: Flow chart of the system

23

CHAPTER 3
HARDWARE DESiGN & iMPLEMENTATiON

24

Chapter 3- Hardware design & Implementation

3.1 Connection diagram and description of PIC 16F877A

Fig. 3.1: PIC 16F877A

Fig. 3.2: Connection of PIC with other components

Fig 3.2 shows the connection of PIC 16F877A with other circuit components. Pin no (2) of LM35 is connected with the pin no (4) of the PIC 16F877A microcontroller, which is known as RA2 through 1K resistor. (+5) volt DC is connected to the master clear (MCLR) through 10K resistor for the initiation purpose. An 8 MHZ crystal oscillator is also connected with PIC microcontroller by pin no (13) and (14). It also interfaces with DC motor driver. Pin no (17), of the PIC microcontroller which is known as RC2 is connected with the pin no (2) of the DC motor driver (L293D). Connection of PIC 16F877A microcontroller with LCD display as shown in table-

Table 3.1: connection of PIC 16F877A with LCD display

Pin no of PIC 16F877A


35(RB2) 36(RB3) 37(RB4) 38(RB5) 39(RB6) 40(RB7)

Pin no of LCD display


4 6 11 12 13 14

25

Chapter 3- Hardware design & Implementation

3.2 Connection diagram and description of Sensor (LM 35)


The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient Centigrade scaling.

Fig. 3.3: Picture of LM35

Fig. 3.4: Connection of sensor with other components

From the above picture it is clearly shows that 3-terminal LM35 device is connected with the PIC 16F877A microcontroller. First terminal (pin 1) of the LM35 is connected with the +5 volt power supply which is nothing but the terminal 3 of the voltage regulator (KA 7805).second terminal (pin 2) of the sensor is connected with the pin no (4) of the microcontroller, named as RA2 via 1K resistor and terminal 3 of the sensor (LM35) is grounded.

For details see Appendix A.

26

Chapter 3- Hardware design & Implementation

3.3 Connection diagram and description of LCD Module


LCD display (HD44780U) has two display lines. Each line can display 20 characters at a time. A single HD440U can display up to one 8 character line or two 8 character lines. In this project it interfaced to PIC 16F877A to show temperature readings.

Fig. 3.5: Connection of LCD display (2x16) with PIC 16F877A From the above figure, it is clear that some output port (B) pins of the PIC 16F877A is connected with the LCD display. These pin configuration is shown as-----

Table 3.3: Pin connection

Pin no of PIC 16F877A


35(RB2) 36(RB3) 37(RB3) 38(RB4) 39(RB5) 40(RB6) For details see Appendix A.

Pin no of LCD display


3 4 6 12 13 14

27

Chapter 3- Hardware design & Implementation

3.4 Connection diagram of DC motor

Fig. 3.6: Connection of DC motor with DC motor driver (L293D)

From the above picture we can clearly see that DC motor is connected with DC motor driver with particular fashion. Pin (6) of the DC motor driver connected with the negative terminal off the DC motor. On the other hand Pin (3) of the DC motor driver connected with the

positive terminal off the DC motor. If we connect the DC motor directly to the PIC microcontroller then back e.m.f may damage the microcontroller, so it is very essential.

28

Chapter 3- Hardware design & Implementation

3.4 Short description of the components a) PIC 16F877A:Microcontroller is a highly integrated chip that contains all the components comprising a controller. Typically it includes a CPU, RAM, ROM, I/O ports, timers and UARTs.Unlike a general-purpose computer, which also includes all of these components. Typically Microcontroller is called a dedicated processor that is designed for a very specific task-to control a particular system. As a result the parts can be simplified and reduced, which cuts down on production costs. In our project we use the PIC 16F877A microcontroller. It provides several advantages over other microcontrollers. Different series of PIC microcontroller are popular because of high performance, low cost, low power consumption and small in size. It uses high performance RISC architecture, PIC 16F877A uses 35 single word instructions, having 20MHZ operating frequency. The additional flexibility in PIC 16F877A microcontroller is that it has 8K x 14 words of FLASH Program Memory, 368 x 8 bytes of Data Memory (RAM) and 256 x 8 bytes of EEPROM data memory. It also has 8 channel 10 bit ADC, two PWM module, 14 interrupt source, Eight level deep hardware stack, Direct, indirect and relative addressing modes, Power-on Reset (POR), Power-up Timer (PWRT) and Oscillator Start-up Timer (OST), Watchdog Timer (WDT) with its own on-chip RC, oscillator for reliable operation, Programmable code-protection, Power saving SLEEP mode Selectable oscillator options, Low-power, high-speed CMOS FLASH/EEPROM technology.

Fig. 3.7: PIC 16F877A

29

Chapter 3- Hardware design & Implementation

The key features of PIC 16F877A are shown in tabular form-

Table 3.4: Key Features of PIC 16F877A Serial No 1 2 3 4 5 6 7 8 9 10 11 12 Key Features Operating Frequency FLASH Program Memory Data memory (bytes) EEPROM Data Memory Interrupts I/O Ports Timers PWM modules Serial Communications Parallel Communications 10-bit A/D Module Instruction Set PIC 16F877A DC -20 MHZ 8K 368 Bytes 15 14 PORTS(A,B,C,D,E) 3 2 MSSP,USART PSP 8 INPUT CHANNELS 35

For our project purpose some of the features of PIC 16F877A are very important, like Flash program memory, I/O ports, PWM modules and 10-bit ADC module.

i) ii)

Program (.HEX code) downloaded into the flash memory should be less than 8K. We need to define which port is used as the input port and which port is used as output port.

iii)

PWM module mainly used to drive the motor. So it determine the PWM duty cycle, which is mainly use to rotate the motor.

iv)

The conversion of an analog input signal results in a corresponding 10-bit digital number.

30

Chapter 3- Hardware design & Implementation

b) LCD Module:LCD display (HD44780U) has two display lines. Each line can display 20 characters at a time. A single HD440U can display up to one 8 character line or two 8 character lines. In this project it interfaced to PIC 16F877A to show temperature readings. Since all the functions such as display RAM, Character generator and Liquid crystal driver required for driving a dot-matrix liquid crystal display are internally provided on one chip, a minimal system can be interfaced with this controller or driver.

Fig. 3.8: LCD module Key function of the LCD display device (HD44780U) are shown as-

i) ii) iii) iv) v) vi) vii) viii) ix) x)

5x 8 and 5x 10 dot matrix possible. It support low power operation (2.7 to 5.5 V). Wide range of Liquid crystal display driver power range (3.0 to 11 V). Liquid crystal drive waveform: A (One line frequency AC waveform). It comprises high speed MPU bus interface. 4 bit or 8 bit MPU interface enabled. 80x 8 bit displays RAM (80 characters MAX.). Bit character generator ROM for a total of 240 character fonts. 64x 8 bit character generator RAM. It also provides 16 common x 40 segment liquid crystal display driver. (For details see Appendix A) 31

Chapter 3- Hardware design & Implementation

c) Sensor (LM35) Module:The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient Centigrade scaling. The LM35 does not require any external calibration or trimming to provide typical accuracies of 14C at room temperature and 34C over a full 55 to +150C temperature range. Low cost is assured by trimming and calibration at the wafer level. The LM35s low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 A from its supply, it has very low self-heating, less than 0.1C in still air. The LM35 is rated to operate over a 55 to +150C temperature range, while the LM35C is rated for a 40 to +110C range (10with improved accuracy). The LM35 series is available packaged in hermetic TO-46 transistor packages, while the LM35C, LM35CA, and LM35D are also available in the plastic TO-92 transistor package. The LM35D is also available in an 8-lead surface mount small outline package and a plastic TO220 package.

Features:
Calibrated directly in Celsius (Centigrade). Linear 10.0 mV/C scale factor. 0.5C accuracy guarantee able (at +25C). Rated for full 55 to +150C range. Suitable for remote applications. Low cost due to wafer-level trimming. Operates from 4 to 30 volts. Less than 60 A current drain. Low self-heating, 0.08C in still air.

32

Fig. 3.9: Sensor (LM35) module

33

Chapter 3- Hardware design & Implementation

d) DC Motor
Motors come in many sizes and types, but their basic function is the same. Motors of all types serve to convert electrical energy into mechanical energy. They can be found in VCR's, elevators, CD players, toys, robots, watches, automobiles, subway trains, fans, space ships, air conditioners, refrigerators, and many other places. D.C. motors are motors that run on Direct Current from a battery or D.C. power supply. Direct Current is the term used to describe electricity at a constant voltage. A.C. motors run on Alternating Current, which oscillates with a fixed cycle between a positive and negative value. Electrical outlets provide A.C. power. When a battery or D.C. power supply is connected between a D.C. motor's electrical leads, the motor converts electrical energy to mechanical work as the output shaft turns. The electric motor is the most convenient of all sources of motive power. It is clean and silent, starts instantly, and can be built large enough to drive the world's fastest trains or small enough to work a watch.

Fig. 3.10: DC Motor

34

CHAPTER 4
SOFTWARE DESiGN & iMPLEMENTATiON

35

Chapter 4 Software Design & Implementation

4.1 Introduction to MikroC


MikroC is a powerful, feature rich development tool for PICmicros. It is designed to provide easiest possible solution for developing applications for embedded systems, without compromising performance or control. PIC and C fit together well: PIC is the most popular 8-bit chip in the world, used in a wide variety of applications, and C, prized for its efficiency, is the natural choice for developing embedded systems. MikroC provides a successful match featuring highly advanced IDE, ANSI compliant compiler, broad set of hardware libraries, comprehensive documentation, and plenty of ready to run examples.

4.2 How to build a project Step 1:


The software MikroC pro for PIC 2009 is opened and the c code for the program

is then written on the writing window. After writing the code we go to the topmost toolbar Project > Build or press Ctrl+ F9 to build the code as shown in the figure... The following pictures show the above process:

Fig. 4.1: How to build a project

36

Chapter 4 Software Design & Implementation

Step 2: After building the code the compiler starts to compile the program. After checking
the initial errors and rectifying them the entire code was Built by the software to generate the corresponding HEX code of the c program the functions used in the above program are linked together into a subroutine which generates the HEX code from the raw c code.

Fig. 4.2: Compilation of the project

Step 3: After creation of subroutine the compiler generates the HEX code and tells the user
how much space it occupies and how much RAM it has to be used. After the HEX code has been created the code gets ready to be downloaded. After completion it looks like the following figure:-

37

Chapter 4 Software Design & Implementation

Fig. 4.3: Messages of Compilation

Step 4:

The fourth step is to save the created code into the respective destination. The

leftmost toolbar exhibits a Create New Project option. This project is named as temp indicator and saved in the D: / drive. The device name has been given as PIC16F877A and the clock speed is input as 8 MHz.

38

Chapter 4 Software Design & Implementation

Fig. 4.4: Project setting

After final generation of the HEX code it looks like the following.

Fig. 4.5: Generated HEX code

39

Chapter 4 Software Design & Implementation

Step 5: The next software that is used is C which comes along the Universal Debugger
and is used for downloading the code into the debugger. Before loading the previously created HEX code into the microcontroller, it is first erased with the help of this software to remove any previously loaded programs. For this we click on the ERASE option available on the middle of the toolbar as shown in the figure.

Fig. 4.6: HEX code download software

Step 6: The final step is to write the hex code program into the microcontroller. For this
the debugger is interfaced with the computer via RS 232 cable. After successful interfacing the code is downloaded into the chip via the C software. After successful downloading it looks like the following.

Fig. 4.6: HEX code placed in C software 40

Chapter 4 Software Design & Implementation

5.3 MikroC pro for PIC Libraries


There are so many PIC library function provided by the MikroC pro. But among those huge library functions, we find some of are very important for our project purpose. These are as follows1.

ADC library:

- ADC (Analog to Digital Converter) module is available with a

number of PIC micros. Library function ADC_Read is included to provide you comfortable work with the module in single-ended mode.

a) ADC_Read
Table 4.1: ADC read

Prototype Returns

unsigned ADC_Read(unsigned short channel); 10 or 12-bit unsigned value read from the specified channel (MCU dependent). Initializes PICs internal ADC module to work with RC clock. Clock determines the time period necessary for performing AD conversion (min 12TAD).Parameter channel represents the

Description channel from which the analog value is to be acquired. Refer to


the appropriate datasheet for channel-to-pin mapping. Note: This function doesn't work with the external voltage reference source, only with the internal voltage reference.

Requires

Nothing. unsigned temp;

Example

... temp = ADC_Read(2); // Read analog value from channel 2

41

Chapter 4 Software Design & Implementation

2) LCD library: - The MikroC PRO for PIC provides a library for communication
with Lcds (with HD44780 compliant controllers) through the 4-bit interface.

Table 4.2: External dependencies of LCD Library The following variables must be defined in all projects using Lcd Library:
extern sfr sbit LCD_RS: extern sfr sbit LCD_EN: extern sfr sbit LCD_D7; extern sfr sbit LCD_D6; extern sfr sbit LCD_D5; extern sfr sbit LCD_D4; extern sfr sbit LCD_RS_Direction; extern sfr sbit LCD_EN_Direction; extern sfr sbit LCD_D7_Direction; extern sfr sbit LCD_D6_Direction; extern sfr sbit LCD_D5_Direction; extern sfr sbit LCD_D4_Direction;

Description :

Example :

Register Select line. Enable line. Data 7 line. Data 6 line. Data 5 line. Data 4 line. Register Select direction pin. Enable direction pin. Data 7 direction pin. Data 6 direction pin. Data 5 direction pin. Data 4 direction pin.

sbit LCD_RS at RB4_bit; sbit LCD_EN at RB5_bit; sbit LCD_D7 at RB3_bit; sbit LCD_D6 at RB2_bit; sbit LCD_D5 at RB1_bit; sbit LCD_D4 at RB0_bit; sbit LCD_RS_Direction at TRISB4_bit; sbit LCD_EN_Direction at TRISB5_bit; sbit LCD_D7_Direction at TRISB3_bit; sbit LCD_D6_Direction at TRISB2_bit; sbit LCD_D5_Direction at TRISB1_bit; sbit LCD_D4_Direction at TRISB0_bit;

Library Routines

Lcd_Init Lcd_Out Lcd_Out_Cp Lcd_Chr Lcd_Chr_Cp Lcd_Cmd

42

Chapter 4 Software Design & Implementation

3) PWM Library: -

CCP module is available with a number of PIC MCUs.

MikroC PRO for PIC provides library which simplifies using PWM HW Module. Note: Some MCUs have multiple CCP modules. In order to use the desired CCP library routine, simply change the number 1 in the prototype with the appropriate module number, i.e. PWM2_Start ();

Library Routines:

PWM1_Init PWM1_Set_Duty PWM1_Start PWM1_Stop

Table 4.3: PWM Initialization Prototype Returns Description void PWM1_Init(const long freq); Nothing. Initializes the PWM module with duty ratio 0. Parameter freq is a desired PWM frequency in Hz (refer to device data sheet for correct values in respect with Fosc).This routine needs to be called before using other functions from PWM Library. MCU must have CCP module. Note: Calculation of the PWM frequency value is carried out by the compiler, as it would produce a relatively large code if performed on the library level. Therefore, compiler needs to know the value of the parameter in the compile time. That is why this parameter needs to be a constant, and not a variable. Initialize PWM module at 5KHz: PWM1_Init(5000);

Requires

Example

43

Chapter 4 Software Design & Implementation

Table 4.3: PWM1 Duty set Prototype Returns Description void PWM1_Set_Duty(unsigned short duty_ ratio); Nothing. Sets PWM duty ratio. Parameter duty takes values from 0 to 255, where 0 is 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100. Requires MCU must have CCP module. PWM1_Init must be called before using this routine. Example Set duty ratio to 75%: PWM1_Set_Duty(192);

Table 4.4: PWM1 Start Prototype Returns Description void PWM1_Start(void); Nothing. Starts PWM.

Requires

MCU must have CCP module. PWM1_Init must be called before using this routine.

Example

PWM1_Start();

44

Chapter 4 Software Design & Implementation

Table 4.5: PWM1 stop Prototype Returns Description void PWM1_Stop(void); Nothing. Stops PWM.

Requires

MCU must have CCP module. PWM1_Init must be called before using this routine. PWM1_Start should be called before using this routine; otherwise it will have no effect as the PWM module is not running.
PWM1_Stop();

Example

45

CHAPTER 5
RESULTS OF EXPERiMENT

46

Chapter 5 Results of Experiment

The heat of the system is sensed by a sensor and compared with the set value. The error between the actual and set value is called to be set offset. This offset determines the main fuzzy rules of the system. They are as follows:

If the offset is large, then cool the system, more If the offset is very small, then dont change the cooler, much

Fuzzy logic processing runs under these rules and the rules related to the rate of change of the set/actual offset. This allows us very smooth adjustment of cooling rate. Input data of the offset is calculated by means of taking relative heat difference of actual heat to the set value as shown below:-

Error (E) = (Actual Heat of the System)-(Set Value)

Input data for rate of change of error (CE) is the difference between the last value of E, (En) and the previous value of E, (En-1):-

Rate of change of error (CE) = ((En) - (En-1))

The figures shown below represent condition and conclusion membership functions. Condition membership functions represent offset (E).

Fig. 5.1: Membership function for E

47

Chapter 5 Results of Experiment

Fig. 5.2: Membership function for CE

Table 5.1: Fuzzy Rule Base table Error Change of error

ZR (28C) ZERO ZERO ZERO SLOW SLOW

PS (28C-34C) ZERO SLOW SLOW SLOW MEDIUM

PM (34C-40C) SLOW MEDIUM MEDIUM MEDIUM FAST

PB ( 40C-46C) MEDIUM MEDIUM FAST FAST FAST

NB(-6C) NS(-3C) ZR(0C) PS(+3C) PB(+6C)

ZR = ZERO PS = POSITIVE SMALL PM = POSETIVE MEDIUM PB = POSITIVE BIG NB = NEGETIVE BIG NS = NEGETIVE SMALL

LM35 produces 10mV per C. Therefore 35 C is represented by 350 mV. So for 28C it become 280mV.NowEquivalent Analog Value stored in 10-bit A/D converter (X) = VIN * (2^n -1) __________________ VFS

48

Chapter 5 Results of Experiment So for 28C, 34C, 40C, 46C, X = 286.44 X = 347.82 X = 409.20 X = 470.58

Changes of PWM duty ratio, Parameter duty takes values from 0 to 255, where 0 is 0%, 127 is 50%, and 255 is 100% duty ratio. Other specific values for duty ratio can be calculated as (Percent*255)/100. For (0%) duty ratio For (33%) duty ratio For (0%) duty ratio For (0%) duty ratio Duty ratio is (0). Duty ratio is (84.15). Duty ratio is (168.30). Duty ratio is (255).

After Building the desire program by using MikroC pro, we get different file of different extension. Such as ------------

Fig. 5.3: Contents of HEX data Among those files, we choose .HEX file and downloaded its contents into the Microcontroller (PIC 16F877A). HEX file is look like------------040000008A15002835 :100006000F3083120313FC004730FD00FD0B092857 :0A001600FC0B0928000000000800A0 :0E002000213083120313FD00FD0B142808008D :0E002E00F201F101F001F801F30100300800C9 :06003C00000000000800B6 :100042007B15FB1F2B280130F300F201F101F001B7 :08005200FA0DF20CFF3008006A :08005A00FA1FF2130030080048 :10006200FB14FB1F3B28FF30F300F200F100F0000D :08007200FA0DF20CFF3008004A :10007A00A0017208031D52287108F2007008F100ED :10008A00F001A0157208031D52287108F200F1014F :10009A00A01120167208031960282008F302031D14 :1000AA00031C64280310F21B6828F00DF10DF20DF1 :1000BA00F30B582864280130FC0017206B28023003 ..so on

49

CHAPTER 6
CONCLUSiON & FUTURE SCOPE

50

Chapter 6 Conclusion and Future Scope

Conclusion and Future Scope


The PIC 16F877A based embedded temperature sensor system for an automatic Temperature control system is found to perform as expected. The change of temperature is detected by the temperature sensor (LM 35) and data is displayed on the LCD device continuously. The change of temperature corresponding to the sensors output it is evaluated by the use of FUZZY logic. According to the fuzzy rule base table, the analog data is fuzzified. After Defuzzification, which is processed by the microcontroller (PIC 16F877A) send it to A/D converter, for digital output. The DC motor collected output data from the Output port of the microcontroller (PIC 16F877A). The rotation speed depends on the digital data supplied to it. The entire system is automated and requires no manual intervention. As temperature change almost all the time so it is obvious that control the temperature manually is quite difficult. We can use this autonomous system to increase the longevity of the sophisticated instruments and may use for other purpose.

Design modifications
The sensor design must be modified. The resolution of the sensor is not sufficient. It cant measures the small change of temperature, so further we need to use high-resolution temperature sensor. Here we use fuzzy logic to get quicker response, but here we use temperature range, which is not so long. So it is essential to increase the operation range further. The software (MikroC pro version3.2), which we use, is unable to produce .HEX file if the source file size is more than 12KB. In this autonomous system we set a particular temperature (say 280C) and we assume that temperature only increase further but it may not happen. If temperature falls, then we need another component (say Heater) to compensate the temperature.

51

Bibliography
1. Design with PIC Microcontroller by John B. Peatman. http:// WWW.amazon.com 2. Interfacing PIC Microcontrollers: Simulation by Martin P. Bates. Embedded Design by Interactive

3. Fuzzy Fundamentals" by Earl Cox, IEEE SPECTRUM, October 1992, 58:61. Notes from this article constitute the core of this tutorial.

4. Gerla G., Fuzzy Logic Programming and fuzzy control, Studia Logica, 79 (2005) 231-254. 5. Fuzzy Logic Temperature Controller by Yunseop Kim.

6. Ying, H., and B.-G. Hu: "Introduction to Fuzzy Control," International Journal of Fuzzy Systems, Vol 5, (2003) 87-88. 7. "Designing with Fuzzy Logic" by Kevin Self, IEEE SPECTRUM, November 1990, 42:44,105.

8. mikroc_pic_pro_manual_v100. 9. http:// www.microchip.com

10. http:// www.mikroe.com

52

APPENDIX

53

Appendix

/* Project name
PIC 16F877A BASED FUZZY TEMPERATURE CONTROLLER * Copyright: Mikroelectronika, 2009. * Test Configuration: MCU: PIC 16F877A Oscillator: HS, 08.0000 MHZ Ext. Module LCD (16x2) Software MikroC pro v3.2

// Program begin sbit LCD_RS at RB4_bit; sbit LCD_EN at RB5_bit; sbit LCD_D4 at RB0_bit; sbit LCD_D5 at RB1_bit; sbit LCD_D6 at RB2_bit; sbit LCD_D7 at RB3_bit;

sbit LCD_RS_Direction at TRISB4_bit; sbit LCD_EN_Direction at TRISB5_bit; sbit LCD_D4_Direction at TRISB0_bit; sbit LCD_D5_Direction at TRISB1_bit; sbit LCD_D6_Direction at TRISB2_bit; sbit LCD_D7_Direction at TRISB3_bit;

void main() { float tempres;

54

Appendix

// For LCD variable float c,e;

unsigned d,g; unsigned x1,x2;

char c1,c2,c3;

// For PWM variable float error;

float t=0; float cherror;

// For storing previous temp //Change of error rate

ADCON1=0x80;

// Config A/D converter

TRISA=0xFF;

// Set portA as input port

PORTC = 0xFF; TRISC = 0; // Set PORTC as Output

PORTB = 0xFF;

TRISB=0;

// Set PORTB as Output port

PWM1_Init(5000);

// initialize PWM at 5 KHZ

55

Appendix

while(1) {

delay_ms(400);

tempres=Adc_Read(2);

//

Reading of sensor from pin4 (RA2)

tempres=tempres*5;

//Scaling for sensor(0-1V) and ADC(0-5V) adjustment

error=tempres-286.44;

//28C = 286.44, X=(Vin/Vfs)*(2^10-1)

cherror=(error-t)/0.5;

// (present temp-past temp/delay)

// see FUZZY table

if((error==0)&& (cherror==0)) Pwm_Change_Duty(0); if((error==0)&& (cherror<=-61.38)) Pwm_Change_Duty(0); if ((error==0)&& (-61.38<cherror<=-122.76)) Pwm_Change_Duty(0); if((error==0)&& (0<cherror<=61.38)) Pwm_Change_Duty(84.15); if((error<=0)&& (61.38<cherror<=122.76)) Pwm_Change_Duty(84.15);

if((error<=61.38)&& (cherror==0)) Pwm_Change_Duty(84.15);

56

Appendix

if((error<=61.38)&& (cherror<=-61.38)) Pwm_Change_Duty(84.15); if((error<=61.38)&& (-61.38<cherror<=-122.76)) Pwm_Change_Duty(0); if((error<=61.38)&& (0<cherror<=61.38)) Pwm_Change_Duty(84.15); if((error<=61.38)&& (61.38<cherror<=122.76)) Pwm_Change_Duty(168.30);

if((61.38<error<=122.76)&& (cherror==0)) Pwm_Change_Duty(168.30); if((61.38<error<=122.76)&& (cherror<=-61.38)) Pwm_Change_Duty(168.30); if((61.38<error<=122.76)&& (-61.38<cherror<=-122.76)) Pwm_Change_Duty(84.15); if((61.38<error<=122.76)&& (0<cherror<=61.38)) Pwm_Change_Duty(168.30); if((61.38<error<=122.76)&& (61.38<cherror<=122.76)) Pwm_Change_Duty(255);

if((122.76<error<=184.14)&& (cherror==0)) Pwm_Change_Duty(255); if((122.76<error<=184.14)&& (cherror<=-61.38)) Pwm_Change_Duty(168.30); if((122.76<error<=184.14)&& (-61.38<cherror<=-122.76)) Pwm_Change_Duty(168.30); if((122.76<error<=184.14)&& (0<cherror<=61.38)) Pwm_Change_Duty(255); 57

Appendix

if((122.76<error<=184.14)&& (61.38<cherror<=122.76)) Pwm_Change_Duty(255);

t=error;

//for storing past error temp

// LCD Beginning

c=(tempres/1023)*100;

// For conversion from 286.44 to 28C .

d=c; e=(c-d)*10; g=e;

x1=d/10; x2=d%10;

c1=x1+48;c2=x2+48,c3=g+48;

Lcd_Init(); Lcd_Cmd(_LCD_CLEAR); Lcd_Cmd(_LCD_TURN_OFF); delay_ms(100);

58

Appendix

Lcd_Out(2,1,"SET TEMP=28"); Lcd_Chr_Cp('.'); Lcd_Chr_Cp(223);

Lcd_Out(1,1,"REAL TEMP="); Lcd_Chr_Cp(c1); Lcd_Chr_Cp(c2); Lcd_Chr_Cp('.'); Lcd_Chr_Cp(c3); Lcd_Chr_Cp(223); Lcd_Out_Cp("C");

} }

59

Appendix

Architecture of PIC 16F877A Microcontroller


PIC 16F877A microcontroller has Harvard architecture. The program memory and data memory uses separate buses. Instructions pipelining allows instruction to get executed in single cycle of the next instruction. The architecture of PIC 16F877A microcontroller is shown as-------

Architecture of PIC Microcontroller

60

Appendix

Pin Function of PIC 16F877A


Pin No
1

Pin Name
MCLR/VPP/THV

Function of Pin
Master clear (reset) input or programming voltage input or high voltage test mode control.

2 3 4

RA0/AN0 RA1/AN1 RA2/AN2/VREF-

RA0 can also be analog input0. RA1 can also be analog input1. RA2 can also be analog input2 or negative analog ref. voltage.

RA3/AN3/VREF+

RA3 can also be analog input3 or positive analog ref. voltage.

RA4/T0CKI

RA4 can also be the clock input to the Timer0 timer/counter.

RA5/SS/AN4

RA5 can also be analog input4 or the slave select for the synchronous serial port.

RE0/RD/AN5

RE0 can also be read control for the parallel slave port, or analog input5.

RE1/WR/AN6

RE1 can also be write control for the parallel slave port, or analog input6.

10

RE2/CS/AN7

RE2 can also be select control for the parallel slave port, or analog input7.

11 12 13 14

VDD VSS OSC1/CLKIN OSC2/CLKOUT

Positive supply for logic and I/O pins. Ground reference for logic and I/O pins. Oscillator crystal input/external clock source input. Oscillator crystal output. In RC mode, OSC2 pin outputs CLKOUT which has 1/4 the frequency of OSC1

15

RC0/T1OSO/T1CKI

RC0 can also be the Timer1 oscillator output or a Timer1 clock input.

16

RC1/T1OSI/CCP2

RC1 can also be the Timer1 oscillator input or Capture2 input/Compare2 output/PWM2 output.

61

17

RC2/CCP1

RC2 can also be the Capture1 input/Compare1 output/PWM1 output.

18

RC3/SCK/SCL

RC3 can also be the synchronous serial clock input/ output for both SPI and I2C modes.

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 VSS VDD RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC Ground reference for logic and I/O pins Positive supply for logic and I/O pins. RB0 can also be the external interrupt pin. RB1 can also be the external interrupt pin. RB2 can also be the external interrupt pin. RB3 can also be the low voltage programming input. Interrupt-on-change pin. Interrupt-on-change pin. Interrupt-on-change pin or In-Circuit Debugger pin. Serial programming clock. RC4 can also be the SPI Data In (SPI mode). RC5 can also be the SPI Data Out (SPI mode). RC6 can also be the USART Synchronous Clock. RC7 can also be the USART Synchronous Data. Same as Pin No- 19,20,21,22,28,29,30. PORTD is a bi-directional I/O port or parallel slave port when interfacing to a microprocessor bus. PORTD is a bi-directional I/O port or parallel slave port when interfacing to a microprocessor bus.

40

RB7/PGD

Interrupt-on-change pin or In-Circuit Debugger pin. Serial programming data.

62

Appendix

Memory Organization
There are three memory blocks in each of the PIC16F87X MCUs. The Program Memory and Data Memory have separate buses so that concurrent access can occur. The PIC16F87X devices have a 13-bit program counter capable of addressing an 8K x 14 program memory space. The PIC16F877/876 devices have 8K x 14 words of FLASH program memory, and the PIC16F873/874 devices have 4K x 14. Accessing a location above the physically implemented address will cause a wraparound. The RESET vector is at 0000h and the interrupt vector is at 0004h.

PIC16F877 PROGRAM MEMORY MAP AND STACK

63

Appendix

Analog to Digital Conversion Module


Introduction
PIC 16F877A has an in built analog to digital converter module. The analog to digital converter (A/D converter) module has eight inputs for the 40/44 pin devices. The conversion of an analog input signal results in a corresponding 10-bit digital number. The A/D module has high and low voltage reference input that is software selectable to some combination of VDD, VSS, RA2, or RA3. The A/D converter has a unique feature of being able to operate while the device is in SLEEP mode. To operate in SLEEP, the A/D clock must be derived from the A/Ds internal RC oscillator.

Registers of the ADC module


The A/D module has four registers. These registers are:-

1. A/D Result High Register (ADRESH) 2. A/D Result Low Register (ADRESL) 3. A/D Control Register0 (ADCON0) 4. A/D Control Register1 (ADCON1)

Configuration of the ADC module


These steps should be followed for doing an A/D Conversion: 1. Configure the A/D module:

Configure analog pins/voltage reference and digital I/O (ADCON1) Select A/D input channel (ADCON0) Select A/D conversion clock (ADCON0) Turn on A/D module (ADCON0)

64

Appendix

2. Configure A/D interrupt (if desired):

Clear ADIF bit Set ADIE bit Set PEIE bit Set GIE bit

3. Wait the required acquisition time.

4. Start conversion:

Set GO/DONE bit (ADCON0)

5. Wait for A/D conversion to complete, by either:

Polling for the GO/DONE bit to be cleared (with interrupts enabled); Waiting for the A/D interrupt.

OR

6. Read A/D result registers pair :-( ADRESH: ADRESL), clear bit ADIF if required.

7. For the next conversion, go to step 1 or step 2, as required. The A/D conversion time per bit is defined as TAD. A minimum wait of 2TAD is required before the next acquisition starts.

65

Appendix

A/D Block Diagram

66

Appendix

LCD display Pins: - There are in total of 14 pins marked with numbers (16 if
there is a backlight). Their function is described in the table bellow:-

Function

Pin Number

Name

Logic State

Description

GROUND POWER SUPPLY CONTRAST

1 2

VSS VDD

0V +5V

3 4

VEE RS

0 1

0 Vdd D0 D7 are interpreted as commands D0-D7 are interpreted as data

CONTROL OF OPERATING 6 5 RW 0 1 0 1 E 7 8 9 10 11 DATA/ COMMAND S 12 13 14 D0 D1 D2 D3 D4 D5 D6 D7

Write data (from controller to LCD) read data (from LCD to controller) Access to LCD disabled Normal operating Data/commands

From 1 to 0 are transferred to LCD 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 Bit 0 LSB Bit 1 Bit 2 Bit 3 Bit 4 Bit 5 Bit 6 Bit 7 MSB

67

Appendix

Instruction Description of LCD Module


Clear display: Clear Display writes space codes 20H (character pattern for

character code 20H must be a blank pattern) into all DDRAM addresses. It then sets DDRAM address 0 into the address counter and return the display to its original status if it was shifted. In other words, the display disappears and the cursor or blinking goes to the left edge of the display (in the first line if 2 lines are displayed). It also sets I/D to 1 (Increment mode) in entry mode.

RS

R/W

DB7

DB6

DB5

DB4

DB3

DB2

DB1

DB0

Clear Display

Return Home: - Return home sets DDRAM address 0 into the address counter,
and returns the display to its original status if it was shifted. The DDRAM contents do not change. The cursor or blinking goes to the left edge of the display (in the first line if two lines are displayed). RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0

Return Home

Entry Mode Set:i) I/D: - Increments (I/D = 1) or decrements (I/D = 0) the DDRAM address by 1
when a character code is written into or read from DDRAM. The cursor or blinking moves to the right when incremented by 1 and to the left when decremented by 1. The same applies to writing and reading of CGRAM.

68

Appendix

ii)

S: - Shifts the entire display either to the right (I/D = 0) or to the left (I/D = 1)
when S= 1. The display does not shift if S is 0. If S=1, it will seem as if the cursor does not move but the display does. The display does not shift when reading from DDRAM.

RS

R/W

DB7

DB6

DB5

DB4

DB3

DB2

DB1

DB0

I/D

Entry Mode Set

Display On/Off Control:i) D: - The display is on when D = 1 and off when D = 0. When off, the display data

remains in DDRAM, but can be displayed instantly by setting D = 1.

ii) C: - The Cursor is displayed when C = 1 and not displayed when C is equal
to zero. Even if the cursor disappears, the function of I/D or other specifications will not change during display data write.

iii)

B: -

The character indicated by the cursor blinks when B = 1. The

blinking is displayed as switching between all blank dots and displayed characters at a speed of 409.6 ms intervals when fcp or fosc is 250 KHZ. The cursor and blinking can be set to display simultaneously (The blinking frequency changes according to fosc or the reciprocal of fcp). RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0

Display On/Off Control

Appendix

69

Cursor or Display Shift: - Cursor or display shift shifts the cursor position
or display to the right or left without writing or reading display data. This function is used to correct or search the display. In a two line display the cursor moves to the second line when it passes the 40th digit of the first line. Note that the first and second line displays will shift at the same time. RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0

S/C R/L

Cursor or Display Shift

Function Set:i) DL: - Sets the interface data length. Data is send or received in 8 bit lengths
(DB7 to DB0) when DL is equal to one and in 4 bit lengths (DB7 to DB4) when DL is equal to zero. When 4 bit length is selected, data must be sent or received twice.

ii) N: - Sets the number of display lines. iii) F: - Sets the character font.
Note: - Perform the function at the head of the program before executing any instructions (except for the read busy flag and address instruction). From this point, the function set instruction can not be executed unless the interface data length is changed. RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0

DL

Function Set

Appendix

70

Set CGRAM Address: from the MPU for CGRAM. RS R/W DB7 DB6

Set CGRAM address the CGRAM address

binary AAAAAA into the address counter. Data is then written to or read

DB5

DB4

DB3

DB2

DB1

DB0

Set CGRAM address

71

You might also like