Issuu on Google+

REAL TIME ECG & BODY TEMPERATURE MONITORING DEVICE

MINI PROJECT REPORT Submitted by DILEEP DINESH ELDHO JOSE LADVINE D ALMEIDA NIDHISH

ROY

VIVEK K HARIDAS

In partial fulfillment for the award of degree of BACHELOR OF TECHNOLOGY IN ELECTRONICS AND BIOMEDICAL ENGINEERING

MODEL ENGINEERING COLLEGE Thrikkakara Cochin University of Science and Technology


GOVERNMENT MODEL ENGINEERING COLLEGE THRIKKAKARA KOCHI

DEPARTMENT OF ELECTRONICS AND BIOMEDICAL ENGINEERING Cochin University of Science and Technology

BONAFIDE CERTIFICATE This is to certify that the Mini Project entitled

…………………………………………………………………. Submitted by ………………………………………………………………………………………… ………………………………………………………………………………………… ………………………………………………………………………………………… ………………………………………………………………………………………… is a bonafide work done by him/her under our supervision

Dr.Jessy John

Mrs.Vijayalakshmi k

HEAD OF THE DEPARTMENT

CO-ORDINATOR

Ms.Nisha Krishnan

GUIDE


ACKNOWLEDGEMENT

At this moment of accomplishment, we are presenting our work with great pride and pleasure, we would like to express our sincere gratitude to all those who helped us in the successful completion of our venture. First of all, we would like to thank our Principal Prof. Dr.TK MANI who provided us with all facilities and amenities for the development of our project. We would like to thank Dr. Jessy John, Head of Department of Electronics and Biomedical Engineering for helping us in the successful accomplishment of our project. We are exceedingly grateful to our project coordinator, Mrs. Vijayalakshmi K, Asst. Professor, Dept. of Electronics and Biomedical Engineering for her timely and valuable suggestions. We would also like to thank our project guide Ms. Nisha Krishnan, Faculty staff who gave us constant guidance and support throughout this journey of turbulence.

We also sincerely thank Mrs. Bella, Medical electronics lab-in-charge and Mrs. Geethu and Mrs.Vidhya, Lab Technicians, Department of Electronics and Biomedical for their constant support and encouragement for our project. Above all we thank God almighty for constantly motivating us with His love, and giving us courage at each stride to step forward with confidence and self – belief.

I


ABSTRACT

Our project aims at ECG Acquisition and temperature monitoring in medical field.

An ECG is a test that records the activity of the heart over time. Each portion of the ECG waveform can hint whether the patient is in good health or else. ECG signal are usually very small(approximately1mV) and therefore prone to interferences The problem within the ECG among the existing processes for patients ECG monitoring requires a great deal of effort to collect and analyze information introducing a latency that prevents real-time analysis and use by a common person.

We propose a solution to automate this process by acquiring the ECG and temperature, analyzing the information based on PR, QRS,ST intervals and amplitude and providing different information to person based on it such as health status, measurements etc. on a LCD screen.

The device is aimed at a common person to get current heart condition and temperature .Moreover, the device is portable.

II


TABLE OF CONTENTS

SL NO

TOPIC

PAGE NO

1.

INTRODUCTION

1

2.

LITERATURE REVIEW

2

3.

RELATEDTHEORIES 3.1

CARDIAC CONDUCTION PROCESS

3

3.2

ECG

4

3.3

WAVEFORM

5

3.4

ECG LEADS

6

3.4.1 ECG STANDARD LIMB LEADS

7

3.4.2 EINTHOVANS TRIANGLE

8

3.5

CARDIAC ARRHYTHMIAS

3.6

DURATION AND DISEASES ASSOCIATED WITH ECG

3.7 4.

BODY TEMPERATURE

9

10 11

DESIGN OF THE WORK 4.1

BLOCK DIAGRAM OF CIRCUIT

12

4.2

BLOCK LEVEL TREATMENT

13

III


4.2.1 ECG ACQUISITION BLOCK

13

4.2.2 TEMPERATURE SENSING

13

4.3 CIRCUIT LEVEL DESCRIPTION 4.3.1 INSTRUMENTATION AMPLIFIER

14

4.3.2 LOW PASS FILTER

17

4.3.3 HIGH PASS FILTER

18

4.3.4 RL DRIVE CIRCUIT

20

4.3.5 MICROCONTROLLER

20

4.4 5.

FLOWCHARTS AND CIRCUITS

22

IMPLEMENTATION 5.1 SYSTEM REQUIREMENTS

26

5.2 HARDWARE REQUIREMENTS

26

5.3 SOFTWARE REQUIREMENTS

26

5.4 FULL CIRCUIT DIAGRAM

27

6.

RESULT AND CONCLUSION

28

7.

FUTURE WORKS

29

APPENDIX A

PROGRAMS

REFERENCES APPENDIX B

30 53

DATA SHEETS III

54


LIST OF FIGURES

SL NO:

TOPIC

PAGE NO

Fig 3.1

ECG Waveform

4

Fig 3.2

ECG Waveform Showing Various Segments

Fig 3.3

Fig3.4

5

Waveform Of Standard Limb Leads

7

Standard Limb Leads

7

Of ECG Fig 3.5

Einthoven’s Triangle

8

Fig 4.1

Full Block Diagram

12

Fig 4.2

ECG Acquisition Block

13

Fig 4.3

Temperature Sensing Block

13

Fig 4.4

ECG Acquisition Block

14

Fig 4.5

Instrumentation Amplifier

15

Fig 4.6

Graphics LCD Circuit

23

Fig 4.7

Temperature Sensing Circuit

25

III


LIST OF ABBREVATIONS ECG- Electrocardiogram Rl-Right Leg LCD- Liquid Crystal Display GLCD- Graphical Liquid Crystal Display

III


CHAPTER 1

Introduction An ECG (electrocardiogram) is a test that measures the electrical activity of the heart. The heart is a muscular organ that beats in rhythm to pump the blood through the body. The signals that make the heart's muscle fibers contract come from the Sino atrial node, which is the natural pacemaker of the heart. In an ECG test, the electrical impulses made while the heart is beating are recorded and usually shown on a piece of paper. This is known as an electrocardiogram, and records any problems with the heart's rhythm, and the conduction of the heart beat through the heart which may be affected by underlying heart disease.ECG signals are usually small, approximately 1mV and therefore, it is prone to corruption by various noises; power line interference, electrode contact noise, motion artifacts. Also, it is necessary to design a good filter system that can filter out the noises from the ECG signal in order to get better result. Therefore, measuring an ECG signal is not an easy task to achieve. The ECG signals are captured by the electrode sensors, and then it is amplified by the instrumentation amplifier and precision amplifier. The gain achieved by cascading the amplifiers must be equal or greater than1000 in order to achieve the desired signal output. However, the noises may still interfere with the signal. Therefore, it is necessary to design a band-pass filter (BPF) circuit where the low-pass circuit (LPF) will eliminate the high-frequency noises and the high-pass circuit (HPF) will eliminate the direct current (DC) noise components. An operational amplifier will be used to invert the common noise voltage and drive it back to the right leg of the patient which is considered the ground, in order to cancel the interference.

1


CHAPTER 2

Literature Review Initial research was conducted to determine the types of vital signs of heart and arrhythmias and also body temperature that are routinely measured during a visit to a doctor. As part of the project, it is necessary to find, design and build suitable electrodes and temperature sensors. Then, the market demand for this type of device was determined and research on similar monitoring devices that are currently sold was performed. Major disadvantages with these devices are that they are not very easy to use, somewhat intrusive, and, of course, very expensive. The main problem facing on GLCD plotting and analysis ECG signal without MAT lab. To measure the electrocardiogram (ECG), this project uses three Unipolar leads, placed in Einthoven’s triangle configuration. Lead I, Lead II, and Lead III are used. This method works accurately for the scope of this project as it is geared towards older individuals who are less active. Next, different types of temperature sensors were compared. It was determined that the most effective way of measuring body temperature is by using a LM35. The advantages and disadvantages of the temperature sensor is provided in block level description of temperature sensing circuit.

2


CHAPTER 3

Related Theories The heart is a four-chambered organ consisting of right and left halves. Two of the chambers, the left and right atria, are entry-points into the heart, while the other two chambers, the left and right ventricles, are responsible for contractions that send the blood

through

the

circulation.

The

circulation

is

split

into

the pulmonary and systemic circulation. The role of the right ventricle is to pump deoxygenated blood to the lungs through the pulmonary trunk and pulmonary arteries. The role of the left ventricle is to pump newly oxygenated blood to the body through the aorta. 3.1 Four Steps Of Cardiac Conduction: Step 1: Pacemaker Impulse Generation: The sinoatrial (SA) node (also referred to as the pacemaker of the heart) contracts generating nerve impulses that travel throughout the heart wall. This causes both atria to contract. The SA node is located in the upper wall of the right atrium. It is composed of nodal tissue that has characteristics of both muscle and nervous tissue. Step 2: AV node Impulse Conduction: The atrioventricular (AV) node lies on the right side of the partition that divides the atria, near the bottom of the right atrium. When the impulses from the SA node reach the AV node they are delayed for about a tenth of a second. This delay allows the atria to contract and empty their contents first. Step 3: AV Bundle Impulse Conduction: The impulses are then sent down the atrioventricular bundle. This bundle of fibres branches off into two bundles and the impulses are carried down the centre of the heart to the left and right ventricles. Step 4: Purkinje fibres impulse conduction: At the base of the heart the atrioventricular bundles starts to divide further into purkinje fibers. When the impulse reaches these fibers they trigger the muscle fibers in the ventricles to contract. 3


3.2 ECG The electrocardiogram (ECG) is a diagnostic tool that measures and records the electrical activity of the heart in detail. Being able to interpretate these details allows diagnosis of a wide range of heart problems. The ECG records the electrical activity and depicts it as a series of graph-like tracings, or waves. The shapes and frequencies of these tracings reveal abnormalities in the heart's anatomy or function.

Fig 3.1 ECG waveform The EKG can provide important information about the patient's heart rhythm, a previous heart attack, increased thickness of heart muscle, signs of decreased oxygen delivery to the heart, and problems with conduction of the electrical current from one portion of the heart to another. There are no risks. No electricity is sent through the body, so there is no risk of shock. The accuracy of the ECG depends on the condition being tested. A heart problem may not always show up on the ECG. Some heart conditions never produce any specific ECG changes.

4


3.3 Waveforms: The ECG records the electrical activity that results when the heart muscle cells in the atria and ventricles contract. 

Atrial contractions show up as the P wave.

Ventricular contractions show as a series known as the QRS complex.

The third and last common wave in an ECG is the T wave. This is the electrical activity produced when the ventricles are recharging for the next contraction (repolarizing).

Interestingly, the letters P, Q, R, S, and T are not abbreviations for any actual words but were chosen many years ago for their position in the middle of the alphabet.

The electrical activity results in P, QRS, and T waves that are of different sizes and shapes. When viewed from different leads, these waves can show a wide range of abnormalities of both the electrical conduction system and the muscle tissue of the hearts 4 pumping chambers.

Fig 3.2 ECG waveform showing various segments P Wave: represents atrial depolarization -the time necessary for an electrical impulse from the sinoatrial (SA) node to spread throughout the atrial musculature. Under normal conditions, electrical activity is spontaneously generated by the SA node, the physiological pacemaker. This electrical impulse is propagated throughout the 5


right atrium, and through Bachmann's bundle to the left atrium, stimulating the myocardium of both atria to contract. The conduction of the electrical impulse throughout the left and right atria is seen on the ECG as the P wave. 

Location: Precedes QRS complex. Amplitude: Should not exceed 2 to 2.5 mm in height.

Duration: 0.06 to 0.11 seconds.

P-R Interval: represents the time it takes an impulse to travel from the atria through the AV node, bundle of His, and bundle branches to the Purkinje fibres. 

Location: Extends from the beginning of the P wave to the beginning of the QRS complex.

Duration: 0.12 to 0.20 seconds.

QRS Complex: represents ventricular depolarisation. The QRS complex consists of 3 waves: the Q wave, the R wave, and the S wave. 

The Q wave is always located at the beginning of the QRS complex. It may or may not always be present.

The R wave is always the first positive deflection.

The S wave, the negative deflection, follows the R wave 2.

Amplitude: Normal values vary with age and sex Duration: No longer than 0.10 seconds Q-T Interval: represents the time necessary for ventricular depolarization and repolarisation. 

Location: Extends from the beginning of the QRS complex to the end of the T wave (includes the QRS complex, S-T segment, and the T wave)

Duration: Varies according to age, sex, and heart rate. T Wave: represents the repolarisation of the ventricles. On rare occasions, a U wave can be seen following the T wave. The U wave reflects the repolarisation of the His-Purkinje fibres. 

Location: Follows the S wave and the S-T segment.

3.4 ECG leads: The three types of ECG leads are : 6


Limb Leads (Bipolar)

Augmented Limb Leads (Unipolar)

Chest Leads (Unipolar)

Some of the ECG leads are bipolar leads(e.g., standard limb leads) that utilize a single positive and a single negative electrode between which electrical potentials are measured. Unipolar leads (augmented leads and chest leads) have a single positive recording electrode and utilize a combination of the other electrodes to serve as a composite negative electrode. Normally, when an ECG is recorded, all leads are recorded simultaneously, giving rise to what is called a 12-lead ECG.

Fig 3.3 waveform of standard limb leads 3.4.1 Electrocardiogram Standard Limb Leads (Bipolar): There are three of these leads, I, II and III. Lead I: is between the right arm and left arm electrodes, the left arm being positive. Lead II: is between the right arm and left leg electrodes, the left leg being positive. Lead III: is between the left arm and left leg electrodes, the left leg again being positive.

Fig 3.4 standard limb leads of ECG 7


Lead I has the positive electrode on the left arm, and the negative electrode on the right arm, and therefore measures the potential difference between the two arms. In this and the other two limb leads, an electrode on the right leg serves as a reference electrode for recording purposes. Lead II configuration, the positive electrode is on the left leg and the negative electrode is on the right arm. Lead III has the positive electrode on the left leg and the negative electrode on the left arm. These three bipolar limb leads roughly form an equilateral triangle (with the heart at the centre) that is called Einthoven's triangle in honour of Willem Einthoven who developed the electrocardiogram in 1901. Whether the limb leads are attached to the end of the limb (wrists and ankles) or at the origin of the limb (shoulder or upper thigh) makes no difference in the recording because the limb can simply be viewed as a long wire conductor originating from a point on the trunk of the body. 3.4.2Einthovan’s Triangle

Fig 3.5 Einthoven triangle

8


An equilateral triangle whose vertices lie at the left and right shoulders and the pubic region and whose center corresponds to the vector sum of all electric activity occurring in the heart at any given moment, allowing for the determination of the electrical axis. Einthoven's triangle is approximated by the triangle formed by the axes of the bipolar electrocardiographic (ECG) limb leads I, II, and III. The centre of the triangle offers a reference point for the Unipolar ECG leads. 3.5 Cardiac Arrhythmias: Arrhythmia is a irregular rhythm of heart. Bradycardia: A slow rhythm, (less than 60 beats/min), is labelled Bradycardia. This may be caused by a slowed signal from the sinus node (termed sinus Bradycardia), a pause in the normal activity of the sinus node (termed sinus arrest), or by blocking of the electrical impulse on its way from the atria to the ventricles (termed AV block or heart block). Heart block comes in varying degrees and severity. It may be caused by reversible poisoning of the AV node (with drugs that impair conduction) or by irreversible damage to the node. Bradycardias may also be present in the normally functioning heart of endurance athletes or other well-conditioned persons. Tachycardia: In adults and children over 15, resting heart rate faster than 100 beats/minute is labelled tachycardia. Tachycardia may result in palpitation, however, tachycardia is not necessarily an arrhythmia. Increased heart rate is a normal response to physical exercise or emotional stress. This is mediated by the sympathetic nervous system on the sinus node, and is called sinus tachycardia. Other things that increase sympathetic nervous system activity in the heart include ingested or injected substances such as caffeine or amphetamines, and an overactive thyroid gland (hyperthyroidism). Tachycardia that is not sinus tachycardia usually results from the addition of abnormal impulses to the normal cardiac cycle. Abnormal impulses can begin by one of three mechanisms: automaticity, re-entry or triggered activity. A specialised form of reentry problem is termed fibrillation.

9


3.6 Duration And Diseases Associated With Ecg PR Interval (Measured from beginning of P to beginning of QRS in the frontal plane) Normal: 0.12 - 0.20s Short PR: < 0.12s  Preexcitation syndromes: 

WPW (Wolff-Parkinson-White) Syndrome: An accessory pathway (called the "Kent" bundle) connects the right atrium to the right ventricle (see diagram below)

 LGL (Lown-Ganong-Levine): An AV nodal bypass track into the His bundle exists, and this permits early activation of the ventricles without a delta-wave because the ventricular activation sequence is normal. Prolonged PR: >0.20s  First degree AV block (PR interval usually constant) 

Intra-atrial conduction delay (uncommon)

Slowed conduction in AV node (most common site)

Slowed conduction in His bundle (rare)

Slowed conduction in bundle branch (when contra lateral bundle is blocked)

 Second degree AV block (PR interval may be normal or prolonged; some P waves do not conduct) 

Type I (Wenckebach): Increasing PR until nonconductor P wave occurs

Type II (Mobitz): Fixed PR intervals plus nonconductor P waves

 AV dissociation: Some PR's may appear prolonged, but the P waves and QRS complexes are dissociated (i.e., not married, but strangers passing in the night). QRS Duration (Duration of QRS complex in frontal plane): Normal: 0.06 - 0.10s  Prolonged QRS Duration (>0.10s): 10


QRS duration 0.10 - 0.12s 

Incomplete right or left bundle branch block

Nonspecific intraventricular conduction delay (IVCD)

Some cases of left anterior or posterior fascicular block

 QRS duration > 0.12s 

Complete RBBB or LBBB

Nonspecific IVCD

Ectopic rhythms originating in the ventricles (e.g., ventricular tachycardia, pacemaker rhythm)

QT Interval (Measured from beginning of QRS to end of T wave in the frontal plane) Normal: heart rate dependent  Long QT Syndrome - "LQTS" (based on upper limits for heart rate; QT> 0.47 sec for males and > 0.48 sec in females. 3.7 Body Temperature Different

parts

of

the

body

have

different

body

temperatures.

Rectal and vaginal measurements, or measurements taken directly inside the body cavity, are typically slightly higher than oral measurements, and oral measurements are somewhat higher than skin temperature. The commonly accepted average core body temperature (taken internally) is 37.5 °C (99.5 °F). The typical oral (under the tongue) measurement is slightly cooler, at 36.8° ± 0.4°C (98.2° ± 0.7°F), Although some people think of these numbers as representing the normal temperature, a wide range of temperatures has been found in healthy people. The normal human body temperature can fluctuate about one degree (F) throughout the day, with lower temperatures in the morning and higher temperatures in the late afternoon and evening. The accepted range of "normal" temperature is from 97F (36.1C) to 99F (37.2C).

11


CHAPTER 4

Design Of The Work 4.1 Block Diagram Of Circuit It consists of mainly two blocks: ECG acquisition block & temperature sensing block. ECG ACQUISITION BLOCK

GLCD

TEMPERATURE SENSING BLOCK Fig 4.1Block diagram 12


4.2 Block Level Treatment 4.2.1 ECG Acquisition Block

Fig 4.2 ECG acquisition block This stage is used to acquire the ECG signal from the body using electrodes. It consist of an instrumentation amplifier stage used to provide an initial gain to the signal & is made using IC LM324. it is followed by a band pass filter which is used to remove 50hz power line interference & other unwanted noise from the signal. This stage is followed by a differential amplifier stage made from IC LM324 which provides the final amplification required for the signal. This signal is given to PIC & is then displayed using a graphical display. 4.2.2 Temperature Sensing Block

Fig 4.3Temperature sensing block 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 13


Centigrade scaling. The LM35 does not require any external calibration or trimming to provide typical accuracies of ±¼°C at room temperature and ±¾°C over a full -55 to +150°C temperature range. Low cost is assured by trimming and calibration at the wafer level. The LM35's 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.1°C in still air. The LM35 is rated to operate over a -55° to +150°C temperature range, while the LM35C is rated for a -40° to +110°C range (-10° with 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 TO-220 package. 4.3 Circuit Level Description

Fig 4.4 ECG acquisition circuit 4.3.1 Instrumentation Amplifier As suggested before, it is beneficial to be able to adjust the gain of the amplifier circuit without having to change more than one resistor value, as is necessary

with

the

previous

design

14

of

differential amplifier.

The

so-


called instrumentation builds on the last version of differential amplifier to give us that capability:

Fig 4.5 Instrumentation amplifier This intimidating circuit is constructed from a buffered differential amplifier stage with three new resistors linking the two buffer circuits together. Consider all resistors to be of equal value except for Rgain. The negative feedback of the upper-left op-amp causes the voltage at point 1 (top of Rgain) to be equal to V1. Likewise, the voltage at point 2 (bottom of Rgain) is held to a value equal to V2. This establishes a voltage drop across Rgain equal to the voltage difference between V1 and V2. That voltage drop causes a current through Rgain, and since the feedback loops of the two input op-amps draw no current, that same amount of current through Rgain must be going through the two "R" resistors above and below it. This produces a voltage drop between points 3 and 4 equal to:

15


The regular differential amplifier on the right-hand side of the circuit then takes this voltage drop between points 3 and 4, and amplifies it by a gain of 1 (assuming again that all "R" resistors are of equal value). Though this looks like a cumbersome way to build a differential amplifier, it has the distinct advantages of possessing extremely high input impedances on the V1 and V2 inputs (because they connect straight into the noninverting inputs of their respective op-amps), and adjustable gain that can be set by a single resistor. Manipulating the above formula a bit, we have a general expression for overall voltage gain in the instrumentation amplifier: (4.2) Though it may not be obvious by looking at the schematic, we can change the differential gain of the instrumentation amplifier simply by changing the value of one resistor: Rgain. Yes, we could still change the overall gain by changing the values of some of the other resistors, but this would necessitate balanced resistor value changes for the circuit to remain symmetrical. Please note that the lowest gain possible with the above circuit is obtained with Rgain completely open (infinite resistance), and that gain value is 1.Now use instrumentation amplifier with LM324.the advantage is that working on single supply such as 5V.

Design Instrumentation Amplifier Stage Total Gain= 110 Gain of first stage, A1= 11 Gain of second stage, A2= 10 Atotal= (1+2R4/R5)(-Rf/R1) Let R4= 100k therefore R5= 20k Let R1= 100k we get Rf= 1M

16


4.3.1. a Features of Lm324 LM324 is a low power quad operational amplifier, it has these features: 1.

Internally frequency compensated for unity gain

2.

Large DC voltage gain 100 dB

3.

Wide bandwidth (unity gain) 1 MHz (temperature compensated)

4.

Wide power supply range: Single supply 3V to 32V .

5.

Very low supply current drain (700 ÂľA)-essentially independent of supply voltage

6.

Low input biasing current 45 nA (temperature compensated)

7.

Low input offset voltage 2 mV and offset current: 5 nA

8.

Input common-mode voltage range includes ground

9.

Differential input voltage range equal to the power supply voltage

10.

Large output voltage swing 0V to V+ â&#x20AC;&#x201C; 1.5)

4.3.2 Lowpass Filter A low pass filter is an electronic circuit that passes low frequency signals but attenuates (reduces the amplitude of) signals with frequencies higher than the cutoff frequency. The actual amount of attenuation for each frequency varies from filter to filter. It is sometimes called a high-cut filter, or treble cut filter when used in audio applications. Normally we using second order low pass filter for eliminating noise from the ECG signal. second order Butterworth design follows the circuit design. As with low-pass filters, high-pass filters have a rated cutoff frequency, above which the output voltage increases above 70.7% of the input voltage. Just as in the case of the capacitive low-pass filter circuit, the capacitive high-pass filter's cutoff frequency can be foun with the same formula.

fcut off = 1/2đ?&#x203A;&#x2018;RC

(4.3)

Design SECOND ORDER LOW PASS FILTER\ 1) F= 1/(2Ď&#x20AC;RC) Let f= 25 HZ, C= 0.1 ÂľF 17


R=1/(2πfC)= 1(2*3.14*25*0.1*10-6)= 63.69k= 68k Let gain= 2 1+Rf/R1= 2 Rf/R1= 1 Let Rf= R1= 100k Therefore cut off frequency become 23.4 HZ 2) F= 1/(2πRC) Let f= 25 HZ, C= 1 µF R=1/(2πfC)= 1(2*3.14*25*1*10-6)= 6.3 kΩ==6.8 kΩ AMPLIFIER Rf/R1= 10 Let R1= 100k Rf= 1MΩ 4.3.3 High Pass Filter The High Pass Filter is the exact opposite to the low pass filter. This filter has no output voltage from DC (0Hz), up to a specified cut-off frequency (ƒc) point. This lower cut-off frequency point is 70.7% or -3dB (dB = -20log Vout/Vin) of the voltage gain allowed to pass. The frequency range "below" this cut-off point is generally known as the Stop Band while the frequency range "above" this cut-off point is generally known as the Pass Band. The cut-off frequency or -3dB point, can be found using the formula, ƒc = 1/(2πRC). The phase angle of the output signal at ƒc is +45o. Generally, the high pass filter is less distorting than its equivalent low pass filter. Here using second order highpass filter with LM358.Because of the better operating capabilities of IC and elimination of DC drift from ECG signal due to noise, motion artifacts etc.

18


Design SECOND ORDER HIGH PASS FILTER F= 1/2π (R2R3C2C3)1/2 Let C2= C3= 47µF F= .5 HZ R2= R3= R 0.5= ½*3.14*(R2*(47*10-6)2)1/2 R= 6.761 kΩ= 6.8kΩ Features Of Lm358 LM358 is a low power dual operational amplifier, it has 12 features as: 

Available in 8-Bump micro SMD chip sized package, (See AN-1112)

Internally frequency compensated for unity gain

Large dc voltage gain: 100 dB

Wide bandwidth (unity gain): 1 MHz (temperature compensated)

Wide power supply range:

Single supply: 3V to 32V

or dual supplies: ±1.5V to ±16V

Very low supply current drain (500 µA)-essentially independent of supply voltage

Low input offset voltage: 2 mV

Input common-mode voltage range includes ground

Differential input voltage range equal to the power supply voltage

Large output voltage swing

19


4.3.4 RL Drive Circuit A Driven Right Leg Circuit or “DRL” circuit is an electric circuit that is often added to biological signal amplifiers to reduce Common noise. Biological signal amplifiers such as EKG (Electrocardiogram) EEG (Electroencephalogram) or EMG circuits measure very small electrical signals emitted by the body, often as small as several micro-volts (millionths of a volt). Unfortunately, the patient's body can also act as an antenna which picks up electromagnetic interference, especially 50/60 Hz noise from electrical power lines. This interference can obscure the biological signals, making them very hard to measure. Right Leg Driver circuitry is used to eliminate interference noise by actively canceling the interference. Electrocardiography (ECG) is the science of converting the ionic depolarization of the heart to a measurable electrical signal for analysis. One of the most common challenges in the design of the analog electronics interface to the electrodes/patient is in the optimization of the right leg drive (RLD) for common mode performance and stability. 4.3.5 Microcontroller Microcontroller are used in automatically controlled products and devices, such as automobile engine control systems, implantable medical devices, remote controls, office machines, appliances, power tools, toys and other embedded systems. By reducing the size and cost compared to a design that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to digitally control even more devices and processes. Mixed signal microcontrollers are common, integrating analog components

needed to control

non-digital

electronic systems.

Mostly using

microcontroller for interfacing signal to display system by PIC. 4.3.5. a Features • High performance RISC CPU • Only 35 single word instructions to learn • All single cycle instructions except for program branches which are two cycle • Operating speed: DC - 20 MHz clock input DC - 200 ns instruction cycle

20


• Up to 8K x 14 words of FLASH Program Memory, Up to 368 x 8 bytes of Data Memory (RAM),Up to 256 x 8 bytes of EEPROM Data Memory

Peripheral Features: • Timer0: 8-bit timer/counter with 8-bit prescaler • Timer1: 16-bit timer/counter with prescaler can be incremented during SLEEP via external crystal/clock. • Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler • Two Capture, Compare, PWM modules - Capture is 16-bit, max. resolution is 12.5 ns - Compare is 16-bit, max. resolution is 200 ns - PWM max. Resolution is 10-bit Timer Features: • 8-bit timer/counter • Readable and writable • 8-bit software programmable prescaler • Internal or external clock select • Interrupt on overflow from FFh to 00h • Edge select for external clock 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 PIC it units available from Microchip.com for less than $50

Inexpensive microcontrollers

Wide

range

of

interfaces

including I²C, SPI, USB, USART, A/D,

comparators, PWM, LIN, CAN, PSP, and Ethernet

21

programmable


4.4 Flow Chart Of Graphical Display start

Graphical lcd either writes or erases the point from the screen and thereby plotting the points

PIC acquires the analog values (ECG) and converts them into digital values.

If x COR > 63 chip 2 is selected using chip select, else chip 1 is selected.

Y COR is divided into 8 pages of 1 bytes each. Command words are produced by performing operations of b=y/8 & d=y%8.

Reading and writing is done through separate functions implemented in the program.

Writing is done by reading the present data, writing the new data is done by ORing with the previous data

Erasing is performed by providing a zero instead of one. The whole ECG is displayed real time.

22


4.5 Graphical LCD: Character based LCDâ&#x20AC;&#x2122;s are great for presenting the user with textual information. However there are times you need a bit morefreedom when presenting data. In this application note I will presenta interface between the Dios chips and a Crystal fonts 128x64Graphic LCD.

Fig 4.6 Graphical LCD connection 23


4.6 Flow chart of temperature sensing: start

LM35 acquires Body temperature and provides precision output volts

PIC accepts this volts in RA0/AN0 and provides ASCII out “BODY TEMP=”

Code pattern from PIC (1) is analyzed and given displayed as arrhythmia and heart block.

The next page wil display “RISK LEVEL=”

24


Fig 4.7 Temperature sensing circuit This circuit uses LM35 to detect the body temperature. This is then displayed on the LCD display through PIC.

25


CHAPTER 5

Implementation 5.1 System Requirements: 

3 disposable surface electrodes

It is battery powered

Switches are provided for changing the lcd display

5.2 Hardware Requirements: 

Supply is provided by 9v battery.

Lead wire should be insulated.

Filters are provided for removing the artefacts.

Floating ground is provided to remove baseline wandering.

Power supply is also regulated to 5v using 7805 so as to provide it for PIC & display system

5.3 Software Requirements: 

2 PIC’s are used.

PIC 1 contains the program for ECG display & also contains arrhythmia detection logic.

ECG display program is used to plot real time ECG signal on GLCD.

Arrhythmia detection logic uses timer to calculate the time period of R-R interval & QRS complex which is used to detect arrhythmia & syndrome related to variation in QRS complex respectively.

LM 35 measure voltage corresponding to the body temperature which is send to PIC 2 where it converts this voltage signals to corresponding readings in degree Celsius.

26


27


CHAPTER 6

Results & Conclusion In short, we were successfully able acquire ECG signal and display the body temperature. ECG signal was displayed using graphical LCD and body temperature was displayed using another alpha numeric LCD display. In short, our solution delivers an integrated Device that automates the process from data collecting (EKG and temperature) to Data monitoring and RESULT display. There are several practical advantages in this implementation, such as: it provides always-on, real-time data collecting; it eliminates manual collecting work and signal analysis. This project contributes to scientific and social fields. On the scientific field, the project generates new knowledge and applications for ECG monitoring. These areas are being extensively explored by the academic community and the developments from this project will address some of the outstanding questions. In addition, there is a contribution to the social field, as the proposed system helps to improve the quality of medical assistance delivery, especially in needy communities. It is difficult to gather medical staff always for patient monitoring especially coma patients discharged from a hospital. In addition, expert medical staff has restricted time and cannot monitor patients or collect additional data from patients at bedside.

28


CHAPTER 8

Future Works As future works, we intend to validate the proposal in a real world setup to assess the benefits of cloud computing and updating the data on a web server real-time using GSM services. In addition, we propose several services enhancements of security and management with interaction of thirty-party infrastructure service provider.

29


Appendix A Programs A) Graphical Lcd Display Program #include<pic.h> #include "delay.h" #include "glcd.h" #define GLCD_CS1 RC5 // Chip Selection 1 #define GLCD_CS2 RC4

// Chip Selection 2

#define GLCD_DI

RD7 // Data or Instruction input

#define GLCD_RW

RD6 // Read/Write

#define GLCD_E

RD5 // Enable

#define GLCD_RST RD3 // Reset #define GLCD_BUS PORTB #define GLCD_LEFT

1

#define GLCD_RIGHT 0 #define ON

1

#define OFF

0

void glcd_init(char mode) { GLCD_RST=1; // Instruction input 30


GLCD_E=0; GLCD_CS1=0; GLCD_CS2=0; GLCD_DI=0;

// Set for instruction

glcd_writeByte(GLCD_LEFT, 0xC0);

// Specify first RAM line at the top

glcd_writeByte(GLCD_RIGHT, 0xC0); glcd_writeByte(GLCD_LEFT, 0x40);

// of the screen // Set the column address to 0

glcd_writeByte(GLCD_RIGHT, 0x40); glcd_writeByte(GLCD_LEFT, 0xB8);

// Set the page address to 0

glcd_writeByte(GLCD_RIGHT, 0xB8); if(mode == ON) { glcd_writeByte(GLCD_LEFT, 0x3F); // Turn the display on glcd_writeByte(GLCD_RIGHT, 0x3F); } else{ glcd_writeByte(GLCD_LEFT, 0x3E); // Turn the display off glcd_writeByte(GLCD_RIGHT, 0x3E); } glcd_fillScreen(1);

// Clear the display */

}

31


/*********************************************************************** *****/ void glcd_fillScreen(char color) { char i, j; // Loop through the vertical pages for(i = 0; i < 8; ++i) { GLCD_DI=0;

// Set for instruction

glcd_writeByte(GLCD_LEFT, 0x40);

// Set horizontal address to 0

glcd_writeByte(GLCD_RIGHT, 0x40); glcd_writeByte(GLCD_LEFT, (i | 0xb8));// Set page address glcd_writeByte(GLCD_RIGHT, (i | 0xb8)); GLCD_DI=1;

// Set for data

// Loop through the horizontal sections for(j = 0; j < 64; ++j) { glcd_writeByte(GLCD_LEFT, (0xFF*color)); // Turn pixels on or off glcd_writeByte(GLCD_RIGHT, (0xFF*color)); // Turn pixels on or off } }

32


} /*********************************************************************** *****/ extern void glcd_pixel(char x,char y,char color) { char data=0; char side = GLCD_LEFT;

// Stores which chip to

use on the LCD x=127-x; y=63-y; if(x > 63){

// Check for first or second display area

x -= 64; side = GLCD_RIGHT; } GLCD_DI=0;

// Set for instruction

data=(0x01<<(y%8)); glcd_writeByte(side, (0x40|x));

// Set the horizontal address

glcd_writeByte(side, (0xB8|(y/8))); // Set the vertical page address GLCD_DI=1; glcd_readByte(side); data |= glcd_readByte(side);

// Set for data // Need two reads to get data // at new address

33


if(color)data|=(0x01<<(y%8));

// Clear the MSB. Part of an instruction

code else data&=~(0x01<<(y%8)); GLCD_DI=0;

// Set for instruction

glcd_writeByte(side, (0x40|x)); GLCD_DI=1;

// Set bit 6. Also part of an instruction code

// Set the horizontal address

// Set for data

glcd_writeByte(side, data); // Write the pixel data } /*********************************************************************** *****/ void glcd_writeByte(char side, char data) { if(side){

// Choose which side to write to

GLCD_CS1=1; } Else { GLCD_CS2=1; }

GLCD_BUS=0; GLCD_RW=0;

// Set for writing 34


PORTB=data;

// Put the data on the port

NOP(); NOP(); NOP(); NOP(); NOP(); RD5=1;

// Pulse the enable pin

NOP(); NOP(); NOP(); NOP(); RD5=0; GLCD_CS1=0;

// Reset the chip select lines

GLCD_CS2=0; } /*********************************************************************** *****/ char glcd_readByte(char side) { char data;

// Stores the data read from the LCD

35


TRISB=0xFF; GLCD_RW=1; if(side){

// Set for reading // Choose which side to write to

GLCD_CS1=1; GLCD_CS2=0; } else{ GLCD_CS1=0; GLCD_CS2=1; }

NOP(); NOP(); NOP(); NOP(); RD5=1;

// Pulse the enable pin

NOP(); NOP(); NOP(); NOP(); NOP();

36


data = PORTB;

// Get the data from the display's output register

RD5=0; GLCD_CS1=0;

// Reset the chip select lines

GLCD_CS2=0; TRISB=0; return data;

// Return the read dat}

#include<pic.h> #include "delay.h" #include "glcd.h"

#define GLCD_CS1

RC5 // Chip Selection 1

#define GLCD_CS2

RC4

#define GLCD_DI

RE0 // Data or Instruction input

#define GLCD_RW #define GLCD_E

// Chip Selection 2

RE1 // Read/Write RE2 // Enable

#define GLCD_RST

RD3 // Reset

#define GLCD_BUS

PORTB

#define GLCD_LEFT

1

#define GLCD_RIGHT 0 #define ON

1

37


#define OFF

0

void glcd_init(char mode){ GLCD_RST=1; // Instruction input GLCD_E=0; GLCD_CS1=0; GLCD_CS2=0; GLCD_DI=0; glcd_writeByte(GLCD_LEFT, 0xC0); glcd_writeByte(GLCD_RIGHT, 0xC0); glcd_writeByte(GLCD_LEFT, 0x40);

// Set for instruction // Specify first RAM line at the top // of the screen // Set the column address to 0

glcd_writeByte(GLCD_RIGHT, 0x40); glcd_writeByte(GLCD_LEFT, 0xB8);

// Set the page address to 0

glcd_writeByte(GLCD_RIGHT, 0xB8);

if(mode == ON){

38


glcd_writeByte(GLCD_LEFT, 0x3F); // Turn the display on glcd_writeByte(GLCD_RIGHT, 0x3F); } else{ glcd_writeByte(GLCD_LEFT, 0x3E); // Turn the display off glcd_writeByte(GLCD_RIGHT, 0x3E); } glcd_fillScreen(1);

// Clear the display */

}

void glcd_fillScreen(char color) { char i, j;

// Loop through the vertical pages for(i = 0; i < 8; ++i) { GLCD_DI=0;

// Set for instruction

glcd_writeByte(GLCD_LEFT, 0x40);

// Set horizontal address to 0

39


glcd_writeByte(GLCD_RIGHT, 0x40); glcd_writeByte(GLCD_LEFT, (i | 0xb8));// Set page address glcd_writeByte(GLCD_RIGHT, (i | 0xb8)); GLCD_DI=1;

// Set for data

// Loop through the horizontal sections for(j = 0; j < 64; ++j) { glcd_writeByte(GLCD_LEFT, (0xFF*color)); // Turn pixels on or off glcd_writeByte(GLCD_RIGHT, (0xFF*color)); // Turn pixels on or off } } } extern void glcd_pixel(char x,char y,char color){ char data=0; char side = GLCD_LEFT;

// Stores which chip to

use on the LCD

if(x > 63){

// Check for first or second display area

x -= 64; side = GLCD_RIGHT;

40


} GLCD_DI=0;

// Set for instruction

data=(0x01<<(y%8));

glcd_writeByte(side, (0x40|x));

// Set the horizontal address

glcd_writeByte(side, (0xB8|(y/8))); // Set the vertical page address GLCD_DI=1;

// Set for data

glcd_readByte(side); data |= glcd_readByte(side);

// Need two reads to get data // at new address

if(color)data|=(0x01<<(y%8));

// Clear the MSB. Part of an instruction

code else data&=~(0x01<<(y%8));

GLCD_DI=0;

// Set for instruction

glcd_writeByte(side, (0x40|x)); GLCD_DI=1;

// Set bit 6. Also part of an instruction code

// Set the horizontal address

// Set for data

glcd_writeByte(side, data); // Write the pixel data }

void glcd_block(char x,char y,char color){

41


char data=0; char side = GLCD_LEFT;

// Stores which

chip to use on the LCD if(x > 63){

// Check for first or second display area

x -= 64; side = GLCD_RIGHT; } GLCD_DI=0;

// Set for instruction

data=(0x01<<(y%8));

glcd_writeByte(side, (0x40|x));

// Set the horizontal address

glcd_writeByte(side, (0xB8|(y/8))); // Set the vertical page address //IO1SET =GLCD_DI;

// Set for data

// glcd_readByte(side);

// Need two reads to get data

// data |= glcd_readByte(side);

if(color)data=0xff; else data = 0;

//IO1CLR =GLCD_DI;

// at new address

// Clear the MSB. Part of an instruction code // Set bit 6. Also part of an instruction code

// Set for instruction

glcd_writeByte(side, (0x40|x));

// Set the horizontal address

42


GLCD_DI=1;

// Set for data

glcd_writeByte(side, data); // Write the pixel data }

void glcd_writeByte(char side, char data) { if(side){

// Choose which side to write to

GLCD_CS1=1; } else{ GLCD_CS2=1; }

GLCD_BUS=0; GLCD_RW=0; GLCD_BUS=data;

// Set for writing // Put the data on the port

NOP(); NOP(); NOP();

43


NOP(); NOP(); NOP(); NOP(); NOP(); GLCD_E=1;

// Pulse the enable pin

NOP(); NOP(); NOP(); NOP(); NOP(); NOP(); NOP(); NOP(); GLCD_E=0;

GLCD_CS1=0;

// Reset the chip select lines

GLCD_CS2=0; }

44


char glcd_readByte(char side) { char data;

// Stores the data read from the LCD

TRISB=0xFF;

GLCD_RW=1;

if(side){

// Set for reading

// Choose which side to write to

GLCD_CS1=1; GLCD_CS2=0; } else{ GLCD_CS1=0; GLCD_CS2=1; }

NOP(); NOP(); NOP();

45


NOP(); NOP(); NOP(); NOP(); NOP(); GLCD_E=1;

// Pulse the enable pin

NOP(); NOP(); NOP(); NOP(); NOP(); NOP(); NOP(); NOP(); data = GLCD_BUS;

// Get the data from the display's output register

GLCD_E=0;

GLCD_CS1=0;

// Reset the chip select lines

GLCD_CS2=0; TRISB=0;

46


return data;

// Return the read data

}

B) Temperature Sensing Program #include<pic.h> Void command(char); void data(char); void lcd_print(char*); void delay(long); void main() { Int c,a[8],b; TRISC0=0; TRISC1=0; TRISC5=0;

//TRIS=0 MEANS OUTPUT PORT AND VICEVERSA

TRISD=0;

//B,C,D ARE PORTS

TRISA0=1;

//for adc input 47


TRISB0=1; TRISB4=1; TRISB5=1; TRISB6=1; TRISB2=1; int count=0; delay(25); command(0x30); delay(15); command(0x30); //LCD INITIALIZATION delay(5); command(0x30); delay(1); command(0X38); command(0x0C); command(0x06);

//LCD CHARACTER MAPPING

command(0x01); command(0x01);delay(6);command(0x83);delay(2); lcd_print("SMART CARDIOLOGIST"); delay(500); command(0x01); delay(10); loop: ADCON0=0x81; ADCON1=0xC0;

//PRESET ADC CONFIG

48


while(!RB0) {if(RB2){goto credits;} command(0x01);delay(1); lcd_print("BODY TEMPERTATURE ="); GO=1;

//Initialize the ADC

while(GO); b=ADRESH; b=b<<8; b=b|ADRESL; b=((b/2)-1);

for(int i=0;i<2;i++) { a[i]=b%10; b=b/10; } for(int i=1;i>=0;i--) { data(a[i]+'0'); } delay(50);

49


}

command(0x01);delay(50);if(RB2){goto credits;} if((RB4==0)&&(RB5==0)&&(RB6==0)){c=0;lcd_print("1st

degree

arrhythmia

degree

arrhythmia

degree

arrhythmia

detected");} if((RB4==0)&&(RB5==0)&&(RB6==1)){c=1;lcd_print("2nd detected");} if((RB4==0)&&(RB5==1)&&(RB6==0)){c=2;lcd_print("3rd detected");

while(!RB0);

if(RB2){goto credits;} Command (0x01);delay(50); If(c==0){command(0x83);lcd_print("RISK LEVEL: LOW");} If(c==1){command(0x83);lcd_print("RISK LEVEL: MEDIUM");} If(c==2){command(0x83);lcd_print("RISK LEVEL: CRITICAL");} delay(1000); Goto loop; Credits: Command (0x07);delay(3); lcd_print("developed by dileep nidhish eldho vivek and ladvine ");delay(100); Goto loop; }

50


/*********************************************************************** ****/ Void command (char a) { RC0=0; RC1=0; PORTD=a; RC5=1; delay(1); RC5=0; } /*********************************************************************** *****/ void data(char m) { RC0=1; RC1=0; PORTD=m; RC5=1; delay(1); RC5=0; } 51


/*********************************************************************** *****/ Void lcd_print(char* n) { While (*n!='\0') { Data (*n); n++; } } /*********************************************************************** *****/ Void delay(long g) { int i,j; for(i=0;i<=g;i++)

for(j=0;j<255;j++); }

52


53


54


55


56


57


58


59


60


61


62


63


64


REFERENCE 

wikipedia.org › Health science › Medicine › Emergency medicine

wikipedia.org/wiki/Cardiac_arrhythmia

wikipedia.org/wiki/Human_body_temperature

firstaid.webmd.com/body-temperature\

http://203.217.146.76/projects/MAIN/BME/M2-DOCecg%20acquisition%20and%20arrythmia%20detection.pdf

http://www.ti.com/lit/ds/symlink/lm35.pdf

http://www.ti.com/lit/ds/symlink/lm124-n.pdf

Guyton AC: An author’s philosophy of physiology textbook writing. Adv Physiol Ed 19: s1–s5, 1998.

53


Appendix B

PIC16F87X Data Sheet 28/40-Pin 8-Bit CMOS FLASH Microcontrollers

2001 Microchip Technology Inc.

DS30292C


“All rights reserved. Copyright © 2001, Microchip Technology Incorporated, USA. Information contained in this publication regarding device applications and the like is intended through suggestion only and may be superseded by updates. No representation or warranty is given and no liability is assumed by Microchip Technology Incorporated with respect to the accuracy or use of such information, or infringement of patents or other intellectual property rights arising from such use or otherwise. Use of Microchip‟s products as critical components in life support systems is not authorized except with express written approval by Microchip. No licenses are conveyed, implicitly or otherwise, under any intellectual property rights. The Microchip logo and name are registered trademarks of Microchip Technology Inc. in the U.S.A. and other countries. All rights reserved. All other trademarks mentioned herein are the property of their respective companies. No licenses are conveyed, implicitly or otherwise, under any intellectual property rights.”

Trademarks The Microchip name, logo, PIC, PICmicro, PICMASTER, PICSTART, PRO MATE, KEELOQ, SEEVAL, MPLAB and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. Total Endurance, ICSP, In-Circuit Serial Programming, FilterLab, MXDEV, microID, FlexROM, fuzzyLAB, MPASM, MPLINK, MPLIB, PICDEM, ICEPIC, Migratable Memory, FanSense, ECONOMONITOR and SelectMode are trademarks of Microchip Technology Incorporated in the U.S.A. Serialized Quick Term Programming (SQTP) is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. © 2001, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved.

Microchip received QS-9000 quality system certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona in July 1999. The Company’s quality system processes and procedures are QS-9000 compliant for its PICmicro® 8-bit MCUs, KEELOQ® code hopping devices, Serial EEPROMs and microperipheral products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001 certified.

DS30292C - page ii

2001 Microchip Technology Inc.


PIC16F87X 28/40-Pin 8-Bit CMOS FLASH Microcontrollers

• PIC16F873 • PIC16F874

• PIC16F876 • PIC16F877

Microcontroller Core Features: • High performance RISC CPU • Only 35 single word instructions to learn • All single cycle instructions except for program branches which are two cycle • Operating speed: DC - 20 MHz clock input DC - 200 ns instruction cycle • Up to 8K x 14 words of FLASH Program Memory, Up to 368 x 8 bytes of Data Memory (RAM) Up to 256 x 8 bytes of EEPROM Data Memory • Pinout compatible to the PIC16C73B/74B/76/77 • Interrupt capability (up to 14 sources) • 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 • Fully static design • In-Circuit Serial Programming (ICSP) via two pins • Single 5V In-Circuit Serial Programming capability • In-Circuit Debugging via two pins • Processor read/write access to program memory • Wide operating voltage range: 2.0V to 5.5V • High Sink/Source Current: 25 mA • Commercial, Industrial and Extended temperature ranges • Low-power consumption: -< 0.6 mA typical @ 3V, 4 MHz - 20 µA typical @ 3V, 32 kHz - <1µA typical standby current

2001 Microchip Technology Inc.

Pin Diagram PDIP MCLR/VPP RA0/AN0

1

40

RB7/PGD

2

39

RB6/PGC

RA1/AN1 RA2/AN2/VREF-

3 4

38 37

RB5 RB4

RA3/AN3/VREF+ RA5/AN4/SS

5 6 7

36 35 34

RB3/PGM RB2 RB1

RE0/RD/AN5

8

33

RB0/INT

RE1/WR/AN6 RE2/CS/AN7 VDD

9 10

32 31

VDD VSS

30 29 28

RD7/PSP7 RD6/PSP6 RD5/PSP5

27

RD4/PSP4

26 25 24

RC7/RX/DT RC6/TX/CK RC5/SDO

18

23

RC4/SDI/SDA

19 20

22 21

RD3/PSP3 RD2/PSP2

RA4/T0CKI

VSS OSC1/CLKIN

11 12 13

OSC2/CLKOUT

14

RC0/T1OSO/T1CKI

15 16 17

RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RD0/PSP0 RD1/PSP1

PIC16F877/874

Devices Included in this Data Sheet:

Peripheral Features: • Timer0: 8-bit timer/counter with 8-bit prescaler • Timer1: 16-bit timer/counter with prescaler, can be incremented during SLEEP via external crystal/clock • Timer2: 8-bit timer/counter with 8-bit period register, prescaler and postscaler • Two Capture, Compare, PWM modules - Capture is 16-bit, max. resolution is 12.5 ns - Compare is 16-bit, max. resolution is 200 ns - PWM max. resolution is 10-bit • 10-bit multi-channel Analog-to-Digital converter • Synchronous Serial Port (SSP) with SPI (Master 2 mode) and I C (Master/Slave) • Universal Synchronous Asynchronous Receiver Transmitter (USART/SCI) with 9-bit address detection • Parallel Slave Port (PSP) 8-bits wide, with external RD, WR and CS controls (40/44-pin only) • Brown-out detection circuitry for Brown-out Reset (BOR)

DS30292C-page 1


PIC16F87X Pin Diagrams PDIP, SOIC RB7/PGD RB6/PGC RB5 RB4 RB3/PGM RB2 RB1 RB0/INT VDD VSS RC7/RX/DT RC6/TX/CK RC5/SDO RC4/SDI/SDA

22

18 19 20

16

PIC16F877 PIC16F874

14

12

1 2 3 4 5 6 7 8 9 10 11

33 32 31 30 29

41

RB3/PGM RB2 RB1 RB0/INT VDD VSS RD7/PSP7 RD6/PSP6 RD5/PSP5 RD4/PSP4 RC7/RX/DT

RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RC4/SDI/SDA RC5/SDO RC6/TX/CK NC

26 27

39 38 37 36 35 34

33 32 31 30 29 28 27 26 25 24 23

NC RC0/T1OSO/T1CKI OSC2/CLKOUT OSC1/CLKIN VSS VDD RE2/AN7/CS RE1/AN6/WR RE0/AN5/RD RA5/AN4/SS RA4/T0CKI

NC NC RB4 RB5 RB6/PGC RB7/PGD MCLR/VPP RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+

RC7/RX/DT RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 VSS VDD RB0/INT RB1 RB2 RB3/PGM

38 37 36 35

RC6/TX/CK RC5/SDO RC4/SDI/SDA RD3/PSP3 RD2/PSP2 RD1/PSP1 RD0/PSP0 RC3/SCK/SCL RC2/CCP1 RC1/T1OSI/CCP2 NC 44 43 42 41 40

QFP

PIC16F877 PIC16F874

22 23 24

7 8 9 10 11 12 13 14 15 16 17

18

RA4/T0CKI RA5/AN4/SS RE0/RD/AN5 RE1/WR/AN6 RE2/CS/AN7 VDD VSS OSC1/CLKIN OSC2/CLKOUT RC0/T1OSO/T1CK1 NC

20

PLCC

RA3/AN3/VREF+ RA2/AN2/VREFRA1/AN1 RA0/AN0 MCLR/VPP NC RB7/PGD RB6/PGC RB5 RB4 NC

28 27 26 25 24 23 22 21 20 19 18 17 16 15

6 5 4 3 2 1 44 43

1 2 3 4 5 6 7 8 9 10 11 12 13 14

PIC16F876/873

MCLR/VPP RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS VSS OSC1/CLKIN OSC2/CLKOUT RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL

DS30292C-page 2

2001 Microchip Technology Inc.


PIC16F87X Key Features PICmicro™ Mid-Range Reference Manual (DS33023)

PIC16F873

PIC16F874

PIC16F876

PIC16F877

Operating Frequency

DC - 20 MHz

DC - 20 MHz

DC - 20 MHz

DC - 20 MHz

RESETS (and Delays)

POR, BOR (PWRT, OST)

POR, BOR (PWRT, OST)

POR, BOR (PWRT, OST)

POR, BOR (PWRT, OST)

4K

4K

8K

8K

192

192

368

368

EEPROM Data Memory

128

128

256

256

Interrupts

13

14

13

14

I/O Ports

Ports A,B,C

Ports A,B,C,D,E

Ports A,B,C

Ports A,B,C,D,E

Timers

3

3

3

3

FLASH Program Memory (14-bit words) Data Memory (bytes)

Capture/Compare/PWM Modules

2

2

2

2

Serial Communications

MSSP, USART

MSSP, USART

MSSP, USART

MSSP, USART

PSP

Parallel Communications

10-bit Analog-to-Digital Module

5 input channels

Instruction Set

35 instructions

2001 Microchip Technology Inc.

PSP

8 input channels 5 input channels

8 input channels

35 instructions

35 instructions

35 instructions

DS30292C-page 3


PIC16F87X Table of Contents 1.0 Device Overview .................................................................................................................................................. 5 2.0 Memory Organization ......................................................................................................................................... 11 3.0 I/O Ports ............................................................................................................................................................. 29 4.0 Data EEPROM and FLASH Program Memory .................................................................................................... 41 5.0 Timer0 Module ................................................................................................................................................... 47 6.0 Timer1 Module ................................................................................................................................................... 51 7.0 Timer2 Module ................................................................................................................................................... 55 8.0 Capture/Compare/PWM Modules ....................................................................................................................... 57 9.0 Master Synchronous Serial Port (MSSP) Module................................................................................................ 65 10.0 Addressable Universal Synchronous Asynchronous Receiver Transmitter (USART) ......................................... 95 11.0 Analog-to-Digital Converter (A/D) Module ......................................................................................................... 111 12.0 Special Features of the CPU............................................................................................................................. 119 13.0 Instruction Set Summary................................................................................................................................... 135 14.0 Development Support ....................................................................................................................................... 143 15.0 Electrical Characteristics ................................................................................................................................... 149 16.0 DC and AC Characteristics Graphs and Tables................................................................................................. 177 17.0 Packaging Information ...................................................................................................................................... 189 Appendix A: Revision History..................................................................................................................................... 197 Appendix B: Device Differences ................................................................................................................................ 197 Appendix C: Conversion Considerations.................................................................................................................... 198 Index ......................................................................................................................................................................... 199 On-Line Support ........................................................................................................................................................ 207 Reader Response ..................................................................................................................................................... 208 PIC16F87X Product Identification System ................................................................................................................. 209

TO OUR VALUED CUSTOMERS It is our intention to provide our valued customers with the best documentation possible to ensure successful use of your Microchip products. To this end, we will continue to improve our publications to better suit your needs. Our publications will be refined and enhanced as new volumes and updates are introduced. If you have any questions or comments regarding this publication, please contact the Marketing Communications Department via E-mail at docerrors@mail.microchip.com or fax the Reader Response Form in the back of this data sheet to (480) 792-4150. We welcome your feedback.

Most Current Data Sheet To obtain the most up-to-date version of this data sheet, please register at our Worldwide Web site at: http://www.microchip.com You can determine the version of a data sheet by examining its literature number found on the bottom outside corner of any page. The last character of the literature number is the version number, (e.g., DS30000A is version A of document DS30000).

Errata An errata sheet, describing minor operational differences from the data sheet and recommended workarounds, may exist for current devices. As device/documentation issues become known to us, we will publish an errata sheet. The errata will specify the revision of silicon and revision of document to which it applies. To determine if an errata sheet exists for a particular device, please check with one of the following: • Microchip‟s Worldwide Web site; http://www.microchip.com • Your local Microchip sales office (see last page) • The Microchip Corporate Literature Center; U.S. FAX: (480) 792-7277 When contacting a sales office or the literature center, please specify which device, revision of silicon and data sheet (include literature number) you are using.

Customer Notification System Register on our web site at www.microchip.com/cn to receive the most current information on all of our products.

DS30292C-page 4

2001 Microchip Technology Inc.


PIC16F87X FIGURE 1-2:

PIC16F874 AND PIC16F877 BLOCK DIAGRAM Data

Device

Program FLASH

Data Memory

PIC16F874

4K

192 Bytes

128 Bytes

PIC16F877

8K

368 Bytes

256 Bytes

EEPROM

13

Program Memory

14

RA0/AN0 RA1/AN1 RA2/AN2/VREFRA3/AN3/VREF+ RA4/T0CKI RA5/AN4/SS PORTB

(1)

Bus

RAM Addr Instruction reg Direct Addr

PORTA

RAM File Registers

8 Level Stack (13-bit) Program

8

Data Bus

Program Counter

FLASH

9 Addr MUX

7 8

RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD

Indirect Addr

FSR reg STATUS reg

8

PORTC 3

Power-up Timer Instruction Decode & Control Timing Generation OSC1/CLKIN OSC2/CLKOUT

Oscillator Start-up Timer Power-on Reset Watchdog Timer Brown-out Reset

RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RC2/CCP1 RC3/SCK/SCL RC4/SDI/SDA RC5/SDO RC6/TX/CK RC7/RX/DT

MUX

ALU 8 W reg

PORTD RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7

In-Circuit Debugger Low-Voltage Programming

Parallel Slave Port

PORTE RE0/AN5/RD

MCLR VDD, VSS

RE1/AN6/WR RE2/AN7/CS Timer0

Timer1

Data EEPROM

CCP1,2

Timer 2

Synchronous Serial Port

10-bit A/D

USART

Note 1: Higher order bits are from the STATUS register.

DS30292C-page 6

2001 Microchip Technology Inc.


PIC16F87X TABLE 1-2:

PIC16F874 AND PIC16F877 PINOUT DESCRIPTION DIP Pin#

PLCC Pin#

QFP Pin#

I/O/P Type

OSC1/CLKIN

13

14

30

I

OSC2/CLKOUT

14

15

31

O

Oscillator crystal output. Connects to crystal or resonator in crystal oscillator mode. In RC mode, OSC2 pin outputs CLKOUT which has 1/4 the frequency of OSC1, and denotes the instruction cycle rate.

MCLR/VPP

1

2

18

I/P

ST

Master Clear (Reset) input or programming voltage input. This pin is an active low RESET to the device.

RA0/AN0

2

3

19

I/O

TTL

RA1/AN1

3

4

20

I/O

TTL

RA1 can also be analog input1.

RA2/AN2/VREF-

4

5

21

I/O

TTL

RA2 can also be analog input2 or negative analog reference voltage.

RA3/AN3/VREF+

5

6

22

I/O

TTL

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

RA4/T0CKI

6

7

23

I/O

ST

RA4 can also be the clock input to the Timer0 timer/ counter. Output is open drain type.

RA5/SS/AN4

7

8

24

I/O

TTL

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

Pin Name

Buffer Type

Description (4)

ST/CMOS

Oscillator crystal input/external clock source input.

PORTA is a bi-directional I/O port. RA0 can also be analog input0.

PORTB is a bi-directional I/O port. PORTB can be software programmed for internal weak pull-up on all inputs. (1)

RB0/INT

33

36

8

I/O

TTL/ST

RB1

34

37

9

I/O

TTL

RB2

35

38

10

I/O

TTL

RB3/PGM

36

39

11

I/O

TTL

RB3 can also be the low voltage programming input.

RB4

37

41

14

I/O

TTL

Interrupt-on-change pin.

RB5

38

42

15

I/O

TTL

RB6/PGC

39

43

16

I/O

TTL/ST

RB7/PGD

40

44

17

I/O

TTL/ST

Legend: I = input

O = output — = Not used

Interrupt-on-change pin. (2)

I/O = input/output TTL = TTL input

RB0 can also be the external interrupt pin.

(2)

Interrupt-on-change pin or In-Circuit Debugger pin. Serial programming clock. Interrupt-on-change pin or In-Circuit Debugger pin. Serial programming data. P = power ST = Schmitt Trigger input

Note 1: This buffer is a Schmitt Trigger input when configured as an external interrupt. 2: This buffer is a Schmitt Trigger input when used in Serial Programming mode. 3: This buffer is a Schmitt Trigger input when configured as general purpose I/O and a TTL input when used in the Parallel Slave Port mode (for interfacing to a microprocessor bus). 4: This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise.

DS30292C-page 8

2001 Microchip Technology Inc.


PIC16F87X TABLE 1-2:

PIC16F874 AND PIC16F877 PINOUT DESCRIPTION (CONTINUED)

Pin Name

DIP Pin#

PLCC Pin#

QFP Pin#

I/O/P Type

Buffer Type

RC0/T1OSO/T1CKI

15

16

32

I/O

ST

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

RC1/T1OSI/CCP2

16

18

35

I/O

ST

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

RC2/CCP1

17

19

36

I/O

ST

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

RC3/SCK/SCL

18

20

37

I/O

ST

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

RC4/SDI/SDA

23

25

42

I/O

ST

RC4 can also be the SPI Data In (SPI mode) or 2 data I/O (I C mode).

RC5/SDO

24

26

43

I/O

ST

RC5 can also be the SPI Data Out (SPI mode).

RC6/TX/CK

25

27

44

I/O

ST

RC6 can also be the USART Asynchronous Transmit or Synchronous Clock.

RC7/RX/DT

26

29

1

I/O

ST

RC7 can also be the USART Asynchronous Receive or Synchronous Data.

Description PORTC is a bi-directional I/O port.

PORTD is a bi-directional I/O port or parallel slave port when interfacing to a microprocessor bus. (3)

RD0/PSP0

19

21

38

I/O

ST/TTL

RD1/PSP1

20

22

39

I/O

ST/TTL

RD2/PSP2

21

23

40

I/O

ST/TTL

RD3/PSP3

22

24

41

I/O

ST/TTL

RD4/PSP4

27

30

2

I/O

ST/TTL

RD5/PSP5

28

31

3

I/O

ST/TTL

RD6/PSP6

29

32

4

I/O

ST/TTL

RD7/PSP7

30

33

5

I/O

ST/TTL

(3) (3) (3) (3) (3) (3) (3)

PORTE is a bi-directional I/O port. (3)

RE0/RD/AN5

8

9

25

I/O

ST/TTL

RE1/WR/AN6

9

10

26

I/O

ST/TTL

RE2/CS/AN7

10

11

27

I/O

ST/TTL

VSS

12,31

13,34

6,29

P

Ground reference for logic and I/O pins.

VDD

11,32

12,35

7,28

P

Positive supply for logic and I/O pins.

NC

1,17,28, 40

12,13, 33,34

These pins are not internally connected. These pins should be left unconnected.

Legend: I = input

O = output — = Not used

(3)

(3)

I/O = input/output TTL = TTL input

RE0 can also be read control for the parallel slave port, or analog input5. RE1 can also be write control for the parallel slave port, or analog input6. RE2 can also be select control for the parallel slave port, or analog input7.

P = power ST = Schmitt Trigger input

Note 1: This buffer is a Schmitt Trigger input when configured as an external interrupt. 2: This buffer is a Schmitt Trigger input when used in Serial Programming mode. 3: This buffer is a Schmitt Trigger input when configured as general purpose I/O and a TTL input when used in the Parallel Slave Port mode (for interfacing to a microprocessor bus). 4: This buffer is a Schmitt Trigger input when configured in RC oscillator mode and a CMOS input otherwise.

2001 Microchip Technology Inc.

DS30292C-page 9


2.0

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 and is detailed in this section. The EEPROM data memory block is detailed in Section 4.0. Additional information on device memory may be found in the PICmicro Mid-Range Reference Manual, (DS33023).

FIGURE 2-1:

PIC16F877/876 PROGRAM MEMORY MAP AND STACK

2.1

Program Memory Organization

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.

FIGURE 2-2:

PIC16F874/873 PROGRAM MEMORY MAP AND STACK

PC<12:0>

PC<12:0> 13

CALL, RETURN RETFIE, RETLW

13

CALL, RETURN RETFIE, RETLW

Stack Level 1

Stack Level 1

Stack Level 2

Stack Level 2

Stack Level 8

Stack Level 8

RESET Vector

0000h

RESET Vector

0000h

Interrupt Vector

0004h

Interrupt Vector

0004h

0005h

0005h

Page 0

Page 0 07FFh 0800h

On-Chip Program Memory

Page 1 0FFFh 1000h Page 2

On-Chip Program Memory

07FFh 0800h Page 1 0FFFh 1000h

17FFh Page 3

1800h 1FFFh

2001 Microchip Technology Inc.

1FFFh

DS30292C-page 11


PIC16F87X 2.2.2

SPECIAL FUNCTION REGISTERS

The Special Function Registers are registers used by the CPU and peripheral modules for controlling the desired operation of the device. These registers are implemented as static RAM. A list of these registers is given in Table 2-1.

TABLE 2-1: Address

The Special Function Registers can be classified into two sets: core (CPU) and peripheral. Those registers associated with the core functions are described in detail in this section. Those related to the operation of the peripheral features are described in detail in the peripheral features section.

SPECIAL FUNCTION REGISTER SUMMARY

Name

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Details on page:

Bank 0 (3)

00h

INDF

Addressing this location uses contents of FSR to address data memory (not a physical register)

0000 0000

27

01h

TMR0

Timer0 Module Register

xxxx xxxx

47

(3)

PCL

Program Counter (PC) Least Significant Byte

0000 0000

26

(3)

STATUS

0001 1xxx

18

04h

(3)

FSR

xxxx xxxx

27

05h

PORTA

--0x 0000

29

06h

PORTB

PORTB Data Latch when written: PORTB pins when read

xxxx xxxx

31

07h

PORTC

PORTC Data Latch when written: PORTC pins when read

xxxx xxxx

33

(4)

PORTD

PORTD Data Latch when written: PORTD pins when read

xxxx xxxx

35

(4)

PORTE

---- -xxx

36

(1,3)

PCLATH

---0 0000

26

0Bh

(3)

INTCON

GIE

PEIE

T0IE

INTE

RBIE

T0IF

INTF

RBIF

0000 000x

20

0Ch

PIR1

ADIF

RCIF

TXIF

SSPIF

CCP1IF

TMR2IF

TMR1IF

0000 0000

22

0Dh

PIR2

(5)

EEIF

BCLIF

CCP2IF

-r-0 0--0

24

0Eh

TMR1L

Holding register for the Least Significant Byte of the 16-bit TMR1 Register

xxxx xxxx

52

0Fh

TMR1H

Holding register for the Most Significant Byte of the 16-bit TMR1 Register

xxxx xxxx

52

10h

T1CON

--00 0000

51

11h

TMR2

0000 0000

55

12h

T2CON

13h

SSPBUF

14h

SSPCON

15h

CCPR1L

Capture/Compare/PWM Register1 (LSB)

16h

CCPR1H

Capture/Compare/PWM Register1 (MSB)

17h

CCP1CON

18h

RCSTA

19h

TXREG

USART Transmit Data Register

0000 0000

99

1Ah

RCREG

USART Receive Data Register

0000 0000

101

1Bh

CCPR2L

Capture/Compare/PWM Register2 (LSB)

xxxx xxxx

57

1Ch

CCPR2H

Capture/Compare/PWM Register2 (MSB)

xxxx xxxx

57

1Dh

CCP2CON

1Eh

ADRESH

02h 03h

08h 09h

0Ah

1Fh

ADCON0

Legend: Note 1: 2: 3: 4: 5:

IRP

RP1

RP0

TO

PD

Z

DC

C

Indirect Data Memory Address Pointer —

(3)

PSPIF —

PORTA Data Latch when written: PORTA pins when read

T1CKPS1

RE2

RE1

RE0

Write Buffer for the upper 5 bits of the Program Counter

T1CKPS0

T1OSCEN

T1SYNC

TMR1CS

TMR1ON

Timer2 Module Register —

TOUTPS3

TOUTPS2

TOUTPS1

TOUTPS0

TMR2ON

T2CKPS1

T2CKPS0 -000 0000

Synchronous Serial Port Receive Buffer/Transmit Register WCOL

SSPOV

SSPEN

CKP

SSPM3

SSPM2

SSPM1

SSPM0

55

xxxx xxxx

70, 73

0000 0000

67

xxxx xxxx

57

xxxx xxxx

57

CCP1X

CCP1Y

CCP1M3

CCP1M2

CCP1M1

CCP1M0

--00 0000

58

SPEN

RX9

SREN

CREN

ADDEN

FERR

OERR

RX9D

0000 000x

96

CCP2X

CCP2Y

CCP2M3

CCP2M2

CCP2M1

CCP2M0

A/D Result Register High Byte ADCS1

ADCS0

CHS2

CHS1

CHS0

GO/DONE

ADON

--00 0000

58

xxxx xxxx

116

0000 00-0

111

x = unknown, u = unchanged, q = value depends on condition, - = unimplemented, read as '0', r = reserved. Shaded locations are unimplemented, read as „0‟. The upper byte of the program counter is not directly accessible. PCLATH is a holding register for the PC<12:8> whose contents are transferred to the upper byte of the program counter. Bits PSPIE and PSPIF are reserved on PIC16F873/876 devices; always maintain these bits clear. These registers can be addressed from any bank. PORTD, PORTE, TRISD, and TRISE are not physically implemented on PIC16F873/876 devices; read as „0‟. PIR2<6> and PIE2<6> are reserved on these devices; always maintain these bits clear.

2001 Microchip Technology Inc.

DS30292C-page 15


PIC16F87X TABLE 2-1: Address

SPECIAL FUNCTION REGISTER SUMMARY

Name

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

(CONTINUED) Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Details on page:

0000 0000

27

1111 1111

19

0000 0000

26

0001 1xxx

18

xxxx xxxx

27

--11 1111

29

Bank 1 (3)

80h

INDF

81h

OPTION_REG

Addressing this location uses contents of FSR to address data memory (not a physical register) RBPU

INTEDG

T0CS

T0SE

PSA

PS2

PS1

PS0

(3)

PCL

(3)

STATUS

84h

(3)

FSR

85h

TRISA

86h

TRISB

PORTB Data Direction Register

1111 1111

31

87h

TRISC

PORTC Data Direction Register

1111 1111

33

(4)

TRISD

PORTD Data Direction Register

1111 1111

35

(4)

TRISE

IBF

OBF

IBOV

0000 -111

37

(1,3)

PCLATH

---0 0000

26

8Bh

(3)

INTCON

GIE

PEIE

T0IE

INTE

RBIE

T0IF

INTF

RBIF

0000 000x

20

8Ch

PIE1

ADIE

RCIE

TXIE

SSPIE

CCP1IE

TMR2IE

TMR1IE

0000 0000

21

8Dh

PIE2

(5)

EEIE

BCLIE

CCP2IE

-r-0 0--0

23

8Eh

PCON

POR

BOR

---- --qq

25

8Fh

Unimplemented

90h

Unimplemented

91h

SSPCON2

0000 0000

68

92h

PR2

Timer2 Period Register

93h

SSPADD

Synchronous Serial Port (I C mode) Address Register

94h

SSPSTAT

95h

Unimplemented

96h

97h

98h

TXSTA

99h

SPBRG

Baud Rate Generator Register

9Ah

Unimplemented

9Bh

9Ch

82h 83h

88h 89h

8Ah

Program Counter (PC) Least Significant Byte IRP

RP1

RP0

TO

PD

Z

DC

C

Indirect Data Memory Address Pointer —

PSPIE

(2)

GCEN

ACKSTAT

PORTA Data Direction Register

ACKDT

PSPMODE

PORTE Data Direction Bits

Write Buffer for the upper 5 bits of the Program Counter

ACKEN

RCEN

PEN

RSEN

SEN

1111 1111

55

0000 0000

73, 74

0000 0000

66

Unimplemented

Unimplemented

0000 -010

95

0000 0000

97

Unimplemented

Unimplemented

9Dh

Unimplemented

9Eh

ADRESL

A/D Result Register Low Byte

xxxx xxxx

116

0--- 0000

112

9Fh

ADCON1

Legend: Note 1: 2: 3: 4: 5:

2

SMP

CSRC

ADFM

CKE

TX9

D/A

TXEN

P

SYNC

S

PCFG3

R/W

BRGH

PCFG2

UA

TRMT

PCFG1

BF

TX9D

PCFG0

x = unknown, u = unchanged, q = value depends on condition, - = unimplemented, read as '0', r = reserved. Shaded locations are unimplemented, read as „0‟. The upper byte of the program counter is not directly accessible. PCLATH is a holding register for the PC<12:8> whose contents are transferred to the upper byte of the program counter. Bits PSPIE and PSPIF are reserved on PIC16F873/876 devices; always maintain these bits clear. These registers can be addressed from any bank. PORTD, PORTE, TRISD, and TRISE are not physically implemented on PIC16F873/876 devices; read as „0‟. PIR2<6> and PIE2<6> are reserved on these devices; always maintain these bits clear.

DS30292C-page 16

2001 Microchip Technology Inc.


PIC16F87X TABLE 2-1: Address

SPECIAL FUNCTION REGISTER SUMMARY

Name

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

(CONTINUED) Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Details on page:

Bank 2 (3)

100h

INDF

Addressing this location uses contents of FSR to address data memory (not a physical register)

0000 0000

27

101h

TMR0

Timer0 Module Register

xxxx xxxx

47

(3)

PCL

Program Counter‟s (PC) Least Significant Byte

0000 0000

26

(3)

STATUS

0001 1xxx

18

104h

(3)

FSR

Indirect Data Memory Address Pointer

xxxx xxxx

27

105h

Unimplemented

106h

PORTB

PORTB Data Latch when written: PORTB pins when read

107h

108h

109h

102h 103h

IRP

RP1

RP0

TO

PD

Z

DC

C

xxxx xxxx

31

Unimplemented

Unimplemented

Unimplemented

---0 0000

26

(1,3)

PCLATH

10Bh

(3)

INTCON

0000 000x

20

10Ch

EEDATA

EEPROM Data Register Low Byte

xxxx xxxx

41

10Dh

EEADR

EEPROM Address Register Low Byte

xxxx xxxx

41

10Eh

EEDATH

xxxx xxxx

41

10Fh

EEADRH

xxxx xxxx

41

0000 0000

27

1111 1111

19

0000 0000

26

0001 1xxx

18

xxxx xxxx

27

10Ah

GIE

PEIE

T0IE

Write Buffer for the upper 5 bits of the Program Counter INTE

RBIE

T0IF

INTF

RBIF

EEPROM Data Register High Byte —

EEPROM Address Register High Byte

Bank 3 (3)

180h

INDF

181h

OPTION_REG

Addressing this location uses contents of FSR to address data memory (not a physical register) RBPU

INTEDG

T0CS

T0SE

(3)

PCL

(3)

STATUS

184h

(3)

FSR

Indirect Data Memory Address Pointer

185h

Unimplemented

186h

TRISB

PORTB Data Direction Register

187h

188h

189h

182h 183h

(1,3)

PCLATH

18Bh

(3)

18Ch 18Dh

EECON2

18Eh

18Fh

18Ah

Legend: Note 1: 2: 3: 4: 5:

PSA

PS2

PS1

PS0

Program Counter (PC) Least Significant Byte IRP

RP1

RP0

TO

PD

Z

DC

C

1111 1111

31

Unimplemented

Unimplemented

Unimplemented

---0 0000

26

Write Buffer for the upper 5 bits of the Program Counter

INTCON

GIE

PEIE

T0IE

INTE

RBIE

T0IF

INTF

RBIF

0000 000x

20

EECON1

EEPGD

WRERR

WREN

WR

RD

x--- x000

41, 42

EEPROM Control Register2 (not a physical register)

---- ----

41

Reserved maintain clear

0000 0000

Reserved maintain clear

0000 0000

x = unknown, u = unchanged, q = value depends on condition, - = unimplemented, read as '0', r = reserved. Shaded locations are unimplemented, read as „0‟. The upper byte of the program counter is not directly accessible. PCLATH is a holding register for the PC<12:8> whose contents are transferred to the upper byte of the program counter. Bits PSPIE and PSPIF are reserved on PIC16F873/876 devices; always maintain these bits clear. These registers can be addressed from any bank. PORTD, PORTE, TRISD, and TRISE are not physically implemented on PIC16F873/876 devices; read as „0‟. PIR2<6> and PIE2<6> are reserved on these devices; always maintain these bits clear.

2001 Microchip Technology Inc.

DS30292C-page 17


PIC16F87X 2.2.2.2

OPTION_REG Register Note:

The OPTION_REG Register is a readable and writable register, which contains various control bits to configure the TMR0 prescaler/WDT postscaler (single assignable register known also as the prescaler), the External INT Interrupt, TMR0 and the weak pull-ups on PORTB.

REGISTER 2-2:

To achieve a 1:1 prescaler assignment for the TMR0 register, assign the prescaler to the Watchdog Timer.

OPTION_REG REGISTER (ADDRESS 81h, 181h) R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

RBPU

INTEDG

T0CS

T0SE

PSA

PS2

PS1

PS0

bit 7

bit 0

bit 7

RBPU: PORTB Pull-up Enable bit 1 = PORTB pull-ups are disabled 0 = PORTB pull-ups are enabled by individual port latch values

bit 6

INTEDG: Interrupt Edge Select bit 1 = Interrupt on rising edge of RB0/INT pin 0 = Interrupt on falling edge of RB0/INT pin

bit 5

T0CS: TMR0 Clock Source Select bit 1 = Transition on RA4/T0CKI pin 0 = Internal instruction cycle clock (CLKOUT)

bit 4

T0SE: TMR0 Source Edge Select bit 1 = Increment on high-to-low transition on RA4/T0CKI pin 0 = Increment on low-to-high transition on RA4/T0CKI pin

bit 3

PSA: Prescaler Assignment bit 1 = Prescaler is assigned to the WDT 0 = Prescaler is assigned to the Timer0 module

bit 2-0

PS2:PS0: Prescaler Rate Select bits Bit Value TMR0 Rate WDT Rate 000 001 010 011 100 101 110 111

1:2 1:4 1:8 1 : 16 1 : 32 1 : 64 1 : 128 1 : 256

1:1 1:2 1:4 1:8 1 : 16 1 : 32 1 : 64 1 : 128

Legend:

Note:

R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

x = Bit is unknown

When using low voltage ICSP programming (LVP) and the pull-ups on PORTB are enabled, bit 3 in the TRISB register must be cleared to disable the pull-up on RB3 and ensure the proper operation of the device

2001 Microchip Technology Inc.

DS30292C-page 19


PIC16F87X 2.2.2.3

INTCON Register Note:

The INTCON Register is a readable and writable register, which contains various enable and flag bits for the TMR0 register overflow, RB Port change and External RB0/INT pin interrupts.

REGISTER 2-3:

Interrupt flag bits are set when an interrupt condition occurs, regardless of the state of its corresponding enable bit or the global enable bit, GIE (INTCON<7>). User software should ensure the appropriate interrupt flag bits are clear prior to enabling an interrupt.

INTCON REGISTER (ADDRESS 0Bh, 8Bh, 10Bh, 18Bh) R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

R/W-x

GIE

PEIE

T0IE

INTE

RBIE

T0IF

INTF

RBIF

bit 7

bit 0

bit 7

GIE: Global Interrupt Enable bit 1 = Enables all unmasked interrupts 0 = Disables all interrupts

bit 6

PEIE: Peripheral Interrupt Enable bit 1 = Enables all unmasked peripheral interrupts 0 = Disables all peripheral interrupts

bit 5

T0IE: TMR0 Overflow Interrupt Enable bit 1 = Enables the TMR0 interrupt 0 = Disables the TMR0 interrupt

bit 4

INTE: RB0/INT External Interrupt Enable bit 1 = Enables the RB0/INT external interrupt 0 = Disables the RB0/INT external interrupt

bit 3

RBIE: RB Port Change Interrupt Enable bit 1 = Enables the RB port change interrupt 0 = Disables the RB port change interrupt

bit 2

T0IF: TMR0 Overflow Interrupt Flag bit 1 = TMR0 register has overflowed (must be cleared in software) 0 = TMR0 register did not overflow

bit 1

INTF: RB0/INT External Interrupt Flag bit 1 = The RB0/INT external interrupt occurred (must be cleared in software) 0 = The RB0/INT external interrupt did not occur

bit 0

RBIF: RB Port Change Interrupt Flag bit 1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared (must be cleared in software). 0 = None of the RB7:RB4 pins have changed state Legend:

DS30292C-page 20

R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

x = Bit is unknown

2001 Microchip Technology Inc.


PIC16F87X 2.2.2.4

PIE1 Register

The PIE1 register contains the individual enable bits for the peripheral interrupts.

REGISTER 2-4:

Note: Bit PEIE (INTCON<6>) must be set to enable any peripheral interrupt.

PIE1 REGISTER (ADDRESS 8Ch) R/W-0 (1)

PSPIE

R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

ADIE

RCIE

TXIE

SSPIE

CCP1IE

TMR2IE

TMR1IE

bit 7

bit 0 (1)

bit 7

PSPIE : Parallel Slave Port Read/Write Interrupt Enable bit 1 = Enables the PSP read/write interrupt 0 = Disables the PSP read/write interrupt

bit 6

ADIE: A/D Converter Interrupt Enable bit 1 = Enables the A/D converter interrupt 0 = Disables the A/D converter interrupt

bit 5

RCIE: USART Receive Interrupt Enable bit 1 = Enables the USART receive interrupt 0 = Disables the USART receive interrupt

bit 4

TXIE: USART Transmit Interrupt Enable bit 1 = Enables the USART transmit interrupt 0 = Disables the USART transmit interrupt

bit 3

SSPIE: Synchronous Serial Port Interrupt Enable bit 1 = Enables the SSP interrupt 0 = Disables the SSP interrupt

bit 2

CCP1IE: CCP1 Interrupt Enable bit 1 = Enables the CCP1 interrupt 0 = Disables the CCP1 interrupt

bit 1

TMR2IE: TMR2 to PR2 Match Interrupt Enable bit 1 = Enables the TMR2 to PR2 match interrupt 0 = Disables the TMR2 to PR2 match interrupt

bit 0

TMR1IE: TMR1 Overflow Interrupt Enable bit 1 = Enables the TMR1 overflow interrupt 0 = Disables the TMR1 overflow interrupt Note 1: PSPIE is reserved on PIC16F873/876 devices; always maintain this bit clear. Legend: R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

2001 Microchip Technology Inc.

x = Bit is unknown

DS30292C-page 21


PIC16F87X 3.0

I/O PORTS

FIGURE 3-1:

Some pins for these I/O ports are multiplexed with an alternate function for 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. Additional information on I/O ports may be found in the PICmicro™ Mid-Range Reference Manual, (DS33023).

3.1

Pin RA4 is multiplexed with the Timer0 module clock input to become the RA4/T0CKI pin. The RA4/T0CKI pin is a Schmitt Trigger input and an open drain output. All other PORTA pins have TTL input levels and full CMOS output drivers. Other PORTA pins are multiplexed with analog inputs and analog VREF input. The operation of each pin is selected by clearing/setting the control bits in the ADCON1 register (A/D Control Register1). On a Power-on Reset, these pins are configured as analog inputs and read as '0'.

The TRISA register controls the direction of the RA pins, even when they are being used as analog inputs. The user must ensure the bits in the TRISA register are maintained set when using them as analog inputs.

EXAMPLE 3-1: BCF BCF CLRF

WR Port

PORTA and the TRISA Register

PORTA is a 6-bit wide, bi-directional port. The corresponding data direction register is TRISA. Setting a TRISA bit (= 1) will make the corresponding PORTA pin an input (i.e., put the corresponding output driver in a Hi-Impedance mode). Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output (i.e., put the contents of the output latch on the selected pin). Reading the PORTA register reads the status of the pins, whereas writing to it will write to the port latch. All write operations are read-modify-write operations. Therefore, a write to a port implies that the port pins are read, the value is modified and then written to the port data latch.

Note:

Data Bus

INITIALIZING PORTA

STATUS, RP0 STATUS, RP1 PORTA

BSF MOVLW MOVWF MOVLW

STATUS, RP0 0x06 ADCON1 0xCF

MOVWF

TRISA

; ; Bank0 ; Initialize PORTA by ; clearing output ; data latches ; Select Bank 1 ; Configure all pins ; as digital inputs ; Value used to ; initialize data ; direction ; Set RA<3:0> as inputs ; RA<5:4> as outputs ; TRISA<7:6>are always ; read as ’0’.

BLOCK DIAGRAM OF RA3:RA0 AND RA5 PINS

Data

Latch

D

Q VDD

CK

Q

P

(1)

I/O pin

TRIS Latch D WR TRIS

N

Q

CK

Q

VSS Analog Input Mode

RD TRIS

TTL Input Buffer D

Q

EN RD Port

To A/D Converter Note 1: I/O pins have protection diodes to VDD and VSS.

FIGURE 3-2: Data Bus WR Port

BLOCK DIAGRAM OF RA4/T0CKI PIN Data Latch D

Q

CK Q N

(1)

I/O pin

TRIS Latch D

Q

VSS

WR TRIS

Schmitt

CK Q

Trigger Input Buffer

RD TRIS

Q

D EN

RD Port

TMR0 Clock Input Note 1: I/O pin has protection diodes to VSS only.

2001 Microchip Technology Inc.

DS30292C-page 29


PIC16F87X TABLE 3-1:

PORTA FUNCTIONS

Name

Bit#

Buffer

Function

RA0/AN0

bit0

TTL

Input/output or analog input.

RA1/AN1

bit1

TTL

Input/output or analog input.

RA2/AN2

bit2

TTL

Input/output or analog input.

RA3/AN3/VREF

bit3

TTL

Input/output or analog input or VREF.

RA4/T0CKI

bit4

ST

Input/output or external clock input for Timer0. Output is open drain type.

RA5/SS/AN4

bit5

TTL

Input/output or slave select input for synchronous serial port or analog input.

Legend: TTL = TTL input, ST = Schmitt Trigger input

TABLE 3-2:

SUMMARY OF REGISTERS ASSOCIATED WITH PORTA Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Value on all other RESETS

RA5

RA4

RA3

RA2

RA1

RA0

--0x 0000

--0u 0000

--11 1111 85h TRISA — — PORTA Data Direction Register 9Fh ADCON1 ADFM — — — PCFG3 PCFG2 PCFG1 PCFG0 --0- 0000 Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by PORTA.

--11 1111

Address 05h

Note:

Name PORTA

--0- 0000

When using the SSP module in SPI Slave mode and SS enabled, the A/D converter must be set to one of the following modes, where PCFG3:PCFG0 = 0100,0101, 011x, 1101, 1110, 1111.

DS30292C-page 30

2001 Microchip Technology Inc.


PIC16F87X 3.2

PORTB and the TRISB Register

PORTB is an 8-bit wide, bi-directional port. The corresponding data direction register is TRISB. Setting a TRISB bit (= 1) will make the corresponding PORTB pin an input (i.e., put the corresponding output driver in a Hi-Impedance mode). Clearing a TRISB bit (= 0) will make the corresponding PORTB pin an output (i.e., put the contents of the output latch on the selected pin). Three pins of PORTB are multiplexed with the Low Voltage Programming function: RB3/PGM, RB6/PGC and RB7/PGD. The alternate functions of these pins are described in the Special Features Section. Each of the PORTB pins has a weak internal pull-up. A single control bit can turn on all the pull-ups. This is performed by clearing bit RBPU (OPTION_REG<7>). The weak pull-up is automatically turned off when the port pin is configured as an output. The pull-ups are disabled on a Power-on Reset.

FIGURE 3-3:

BLOCK DIAGRAM OF RB3:RB0 PINS

(2)

Data Bus WR Port

Weak P Pull-up Data D

a) Any read or write of PORTB. This will end the mismatch condition. b) Clear flag bit RBIF. A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end the mismatch condition and allow flag bit RBIF to be cleared. The interrupt-on-change feature is recommended for wake-up on key depression operation and operations where PORTB is only used for the interrupt-on-change feature. Polling of PORTB is not recommended while using the interrupt-on-change feature. This interrupt-on-mismatch feature, together with software configureable pull-ups on these four pins, allow easy interface to a keypad and make it possible for wake-up on key depression. Refer to the Embedded Control Handbook, “Implementing Wake-up on Key Strokes” (AN552). RB0/INT is an external interrupt input pin and is configured using the INTEDG bit (OPTION_REG<6>).

VDD RBPU

This interrupt can wake the device from SLEEP. The user, in the Interrupt Service Routine, can clear the interrupt in the following manner:

Latch Q

RB0/INT is discussed in detail in Section 12.10.1.

FIGURE 3-4:

CK

VDD

TRIS Latch D WR TRIS

BLOCK DIAGRAM OF RB7:RB4 PINS

I/O(1) pin RBPU

Q

TTL Input Buffer

CK

(2)

Data Bus

P Data Latch D Q

(1)

CK

pin

TRIS Latch D Q

D

RD Port

WR TRIS

EN RB0/INT RB3/PGM

CK

TTL Input Buffer

RD TRIS Schmitt Trigger Buffer

Pull-up I/O

WR Port RD TRIS Q

Weak

RD Port

ST Buffer

Latch Q

D

RD Port Note 1: I/O pins have diode protection to VDD and VSS. 2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>).

Four of the PORTB pins, RB7:RB4, have an interrupton-change feature. Only pins configured as inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is excluded from the interrupton-change comparison). The input pins (of RB7:RB4) are compared with the old value latched on the last read of PORTB. The “mismatch” outputs of RB7:RB4 are OR‟ed together to generate the RB Port Change Interrupt with flag bit RBIF (INTCON<0>).

2001 Microchip Technology Inc.

EN

Set RBIF

Q From other RB7:RB4 pins

Q1

D EN

RD Port Q3

RB7:RB6 In Serial Programming Mode Note 1: I/O pins have diode protection to VDD and VSS. 2: To enable weak pull-ups, set the appropriate TRIS bit(s) and clear the RBPU bit (OPTION_REG<7>).

DS30292C-page 31


PIC16F87X TABLE 3-3:

PORTB FUNCTIONS

Name

Bit#

Buffer (1)

Function

RB0/INT

bit0

TTL/ST

RB1

bit1

TTL

Input/output pin. Internal software programmable weak pull-up.

RB2

Input/output pin or external interrupt input. Internal software programmable weak pull-up.

bit2

TTL

Input/output pin. Internal software programmable weak pull-up.

RB3/PGM

bit3

TTL

Input/output pin or programming pin in LVP mode. Internal software programmable weak pull-up.

RB4

bit4

TTL

Input/output pin (with interrupt-on-change). Internal software programmable weak pull-up.

RB5

bit5

TTL

Input/output pin (with interrupt-on-change). Internal software programmable weak pull-up.

RB6/PGC

bit6

TTL/ST

RB7/PGD

bit7

TTL/ST

(3)

Legend: Note 1: 2: 3:

(2)

Input/output pin (with interrupt-on-change) or In-Circuit Debugger pin. Internal software programmable weak pull-up. Serial programming clock.

(2)

Input/output pin (with interrupt-on-change) or In-Circuit Debugger pin. Internal software programmable weak pull-up. Serial programming data.

TTL = TTL input, ST = Schmitt Trigger input This buffer is a Schmitt Trigger input when configured as the external interrupt. This buffer is a Schmitt Trigger input when used in Serial Programming mode. Low Voltage ICSP Programming (LVP) is enabled by default, which disables the RB3 I/O function. LVP must be disabled to enable RB3 as an I/O pin and allow maximum compatibility to the other 28-pin and 40-pin mid-range devices.

TABLE 3-4:

SUMMARY OF REGISTERS ASSOCIATED WITH PORTB

Address

Name

06h, 106h

PORTB

86h, 186h

TRISB

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Value on all other RESETS

RB7

RB6

RB5

RB4

RB3

RB2

RB1

RB0

xxxx xxxx

uuuu uuuu

1111 1111

1111 1111

1111 1111

1111 1111

PORTB Data Direction Register

81h, 181h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS2 Legend: x = unknown, u = unchanged. Shaded cells are not used by PORTB.

DS30292C-page 32

PS1

PS0

2001 Microchip Technology Inc.


PIC16F87X 3.3

FIGURE 3-6:

PORTC and the TRISC Register

PORTC is an 8-bit wide, bi-directional port. The corresponding data direction register is TRISC. Setting a TRISC bit (= 1) will make the corresponding PORTC pin an input (i.e., put the corresponding output driver in a Hi-Impedance mode). Clearing a TRISC bit (= 0) will make the corresponding PORTC pin an output (i.e., put the contents of the output latch on the selected pin). PORTC is multiplexed with several peripheral functions (Table 3-5). PORTC pins have Schmitt Trigger input buffers. 2

When the I C module is enabled, the PORTC<4:3> 2 pins can be configured with normal I C levels, or with SMBus levels by using the CKE bit (SSPSTAT<6>). When enabling peripheral functions, care should be taken in defining TRIS bits for each PORTC pin. Some peripherals override the TRIS bit to make a pin an output, while other peripherals override the TRIS bit to make a pin an input. Since the TRIS bit override is in effect while the peripheral is enabled, read-modifywrite instructions (BSF, BCF, XORWF) with TRISC as destination, should be avoided. The user should refer to the corresponding peripheral section for the correct TRIS bit settings.

PORTC BLOCK DIAGRAM (PERIPHERAL OUTPUT OVERRIDE) RC<4:3> (2)

Port/Peripheral Select Peripheral Data Out

0 VDD

Data Bus WR Port

D

Q

CK Q

P

I/O (1)

1

pin

Data Latch D

WR TRIS

Q

CK Q

N

TRIS Latch

RD TRIS

Vss Schmitt Trigger

Peripheral (3) OE Q RD Port

D EN

SSPl Input

0

Schmitt Trigger with SMBus levels

1

FIGURE 3-5:

PORTC BLOCK DIAGRAM (PERIPHERAL OUTPUT OVERRIDE) RC<2:0>, RC<7:5> (2)

Port/Peripheral Select

Peripheral Data Out Data Bus D Q WR Port CK Q

0

Note 1: 2:

CKE SSPSTAT<6>

I/O pins have diode protection to VDD and VSS. 3: Port/Peripheral select signal selects between port data and peripheral output. Peripheral OE (output enable) is only activated if peripheral select is active.

VDD P

1

I/O (1) pin

Data Latch D

WR TRIS

Q

CK Q

N

TRIS Latch VSS

RD TRIS

Schmitt Trigger

Peripheral (3) OE

Q

D EN

RD Port Peripheral Input

Note 1: I/O pins have diode protection to VDD and VSS. 2: Port/Peripheral select signal selects between port data and peripheral output. 3: Peripheral OE (output enable) is only activated if peripheral select is active.

2001 Microchip Technology Inc.

DS30292C-page 33


PIC16F87X TABLE 3-5:

PORTC FUNCTIONS

Name

Bit#

Buffer Type

Function

RC0/T1OSO/T1CKI

bit0

ST

Input/output port pin or Timer1 oscillator output/Timer1 clock input.

RC1/T1OSI/CCP2

bit1

ST

Input/output port pin or Timer1 oscillator input or Capture2 input/ Compare2 output/PWM2 output.

RC2/CCP1

bit2

ST

Input/output port pin or Capture1 input/Compare1 output/ PWM1 output.

RC3/SCK/SCL

bit3

ST

RC3 can also be the synchronous serial clock for both SPI 2 and I C modes.

RC4/SDI/SDA

bit4

ST

RC4 can also be the SPI Data In (SPI mode) or data I/O (I C mode).

RC5/SDO

bit5

ST

Input/output port pin or Synchronous Serial Port data output.

RC6/TX/CK

bit6

ST

Input/output port pin or USART Asynchronous Transmit or Synchronous Clock.

RC7/RX/DT

bit7

ST

Input/output port pin or USART Asynchronous Receive or Synchronous Data.

2

Legend: ST = Schmitt Trigger input

TABLE 3-6: Address 07h

SUMMARY OF REGISTERS ASSOCIATED WITH PORTC

Name

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Value on all other RESETS

PORTC

RC7

RC6

RC5

RC4

RC3

RC2

RC1

RC0

xxxx xxxx

uuuu uuuu

1111 1111

1111 1111

87h TRISC PORTC Data Direction Register Legend: x = unknown, u = unchanged

DS30292C-page 34

2001 Microchip Technology Inc.


PIC16F87X 3.4

FIGURE 3-7:

PORTD and TRISD Registers

PORTD and TRISD are not implemented on the PIC16F873 or PIC16F876.

PORTD BLOCK DIAGRAM (IN I/O PORT MODE) (1)

I/O pin Data Bus

PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configureable as an input or output.

WR Port

PORTD can be configured as an 8-bit wide microprocessor port (parallel slave port) by setting control bit PSPMODE (TRISE<4>). In this mode, the input buffers are TTL.

Data Latch D Q CK TRIS Latch D

WR TRIS

Q Schmitt Trigger Input Buffer

CK

RD TRIS

Q

D EN

RD Port

Note 1: I/O pins have protection diodes to VDD and VSS.

TABLE 3-7: Name

PORTD FUNCTIONS Bit#

RD0/PSP0

Buffer Type

bit0

Function

ST/TTL

(1)

Input/output port pin or parallel slave port bit0. Input/output port pin or parallel slave port bit1.

RD1/PSP1

bit1

ST/TTL

(1)

RD2/PSP2

bit2

ST/TTL

(1)

Input/output port pin or parallel slave port bit2.

RD3/PSP3

bit3

ST/TTL

(1)

Input/output port pin or parallel slave port bit3.

ST/TTL

(1)

Input/output port pin or parallel slave port bit4. Input/output port pin or parallel slave port bit5.

RD4/PSP4

bit4

RD5/PSP5

bit5

ST/TTL

(1)

RD6/PSP6

bit6

ST/TTL

(1)

Input/output port pin or parallel slave port bit6.

ST/TTL

(1)

Input/output port pin or parallel slave port bit7.

RD7/PSP7

bit7

Legend: ST = Schmitt Trigger input, TTL = TTL input Note 1: Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode.

TABLE 3-8: Address

SUMMARY OF REGISTERS ASSOCIATED WITH PORTD

Name

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

Bit 2

Bit 1

Bit 0

Value on: POR, BOR

Value on all other RESETS

RD6

RD5

RD4

RD3

RD2

RD1

RD0

xxxx xxxx

uuuu uuuu

1111 1111

1111 1111

0000 -111

0000 -111

08h

PORTD

RD7

88h

TRISD

PORTD Data Direction Register

89h

TRISE

IBF

OBF

IBOV PSPMODE

â&#x20AC;&#x201D;

PORTE Data Direction Bits

Legend: x = unknown, u = unchanged, - = unimplemented, read as '0'. Shaded cells are not used by PORTD.

2001 Microchip Technology Inc.

DS30292C-page 35


PIC16F87X 3.5

FIGURE 3-8:

PORTE and TRISE Register

PORTE and TRISE are not implemented on the PIC16F873 or PIC16F876.

Data Bus

PORTE has three pins (RE0/RD/AN5, RE1/WR/AN6, and RE2/CS/AN7) which are individually configureable as inputs or outputs. These pins have Schmitt Trigger input buffers.

I/O pin

CK TRIS Latch D

WR TRIS

Q

CK

Schmitt Trigger Input Buffer

RD TRIS

PORTE pins are multiplexed with analog inputs. When selected for analog input, these pins will read as ‟0‟s. TRISE controls the direction of the RE pins, even when they are being used as analog inputs. The user must make sure to keep the pins configured as inputs when using them as analog inputs.

Q

D EN

RD Port

Note 1: I/O pins have protection diodes to VDD and VSS.

On a Power-on Reset, these pins are configured as analog inputs, and read as „0‟.

TABLE 3-9:

(1)

Data Latch D Q

WR Port

The PORTE pins become the I/O control inputs for the microprocessor port when bit PSPMODE (TRISE<4>) is set. In this mode, the user must make certain that the TRISE<2:0> bits are set, and that the pins are configured as digital inputs. Also ensure that ADCON1 is configured for digital I/O. In this mode, the input buffers are TTL. Register 3-1 shows the TRISE register, which also controls the parallel slave port operation.

Note:

PORTE BLOCK DIAGRAM (IN I/O PORT MODE)

PORTE FUNCTIONS

Name

Bit#

RE0/RD/AN5

RE1/WR/AN6

RE2/CS/AN7

Buffer Type

bit0

ST/TTL

bit1

(1)

ST/TTL

bit2

ST/TTL

(1)

(1)

Function I/O port pin or read control input in Parallel Slave Port mode or analog input: RD 1 = Idle 0 = Read operation. Contents of PORTD register are output to PORTD I/O pins (if chip selected) I/O port pin or write control input in Parallel Slave Port mode or analog input: WR 1= Idle 0 = Write operation. Value of PORTD I/O pins is latched into PORTD register (if chip selected) I/O port pin or chip select control input in Parallel Slave Port mode or analog input: CS 1 = Device is not selected 0 = Device is selected

Legend: ST = Schmitt Trigger input, TTL = TTL input Note 1: Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode.

TABLE 3-10: SUMMARY OF REGISTERS ASSOCIATED WITH PORTE Address

Name

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

09h

PORTE

89h

TRISE

IBF

OBF

IBOV

PSPMODE

9Fh

ADCON1

ADFM

PCFG3

Bit 2

Bit 1

Bit 0

RE2

RE1

RE0

Value on: POR, BOR

Value on all other RESETS

---- -xxx

---- -uuu

PORTE Data Direction Bits

0000 -111

0000 -111

PCFG2

--0- 0000

--0- 0000

PCFG1

PCFG0

Legend: x = unknown, u = unchanged, - = unimplemented, read as ‟0‟. Shaded cells are not used by PORTE.

DS30292C-page 36

2001 Microchip Technology Inc.


PIC16F87X REGISTER 3-1:

TRISE REGISTER (ADDRESS 89h) R-0

R-0

R/W-0

R/W-0

U-0

R/W-1

R/W-1

R/W-1

IBF

OBF

IBOV

PSPMODE

Bit2

Bit1

Bit0

bit 7

bit 0

Parallel Slave Port Status/Control Bits: bit 7

IBF: Input Buffer Full Status bit 1 = A word has been received and is waiting to be read by the CPU 0 = No word has been received

bit 6

OBF: Output Buffer Full Status bit 1 = The output buffer still holds a previously written word 0 = The output buffer has been read

bit 5

IBOV: Input Buffer Overflow Detect bit (in Microprocessor mode) 1 = A write occurred when a previously input word has not been read (must be cleared in software) 0 = No overflow occurred

bit 4

PSPMODE: Parallel Slave Port Mode Select bit 1 = PORTD functions in Parallel Slave Port mode 0 = PORTD functions in general purpose I/O mode

bit 3

Unimplemented: Read as '0' PORTE Data Direction Bits:

bit 2

Bit2: Direction Control bit for pin RE2/CS/AN7 1 = Input 0 = Output

bit 1

Bit1: Direction Control bit for pin RE1/WR/AN6 1 = Input 0 = Output

bit 0

Bit0: Direction Control bit for pin RE0/RD/AN5 1 = Input 0 = Output Legend: R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

2001 Microchip Technology Inc.

x = Bit is unknown

DS30292C-page 37


PIC16F87X 5.0

TIMER0 MODULE

Counter mode is selected by setting bit T0CS (OPTION_REG<5>). In Counter mode, Timer0 will increment either on every rising, or falling edge of pin RA4/T0CKI. The incrementing edge is determined by the Timer0 Source Edge Select bit, T0SE (OPTION_REG<4>). Clearing bit T0SE selects the rising edge. Restrictions on the external clock input are discussed in detail in Section 5.2.

The Timer0 module timer/counter has the following features: • 8-bit timer/counter • Readable and writable • 8-bit software programmable prescaler • Internal or external clock select • Interrupt on overflow from FFh to 00h • Edge select for external clock

The prescaler is mutually exclusively shared between the Timer0 module and the Watchdog Timer. The prescaler is not readable or writable. Section 5.3 details the operation of the prescaler.

Figure 5-1 is a block diagram of the Timer0 module and the prescaler shared with the WDT.

5.1

Additional information on the Timer0 module is available in the PICmicro™ Mid-Range MCU Family Reference Manual (DS33023).

The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. This overflow sets bit T0IF (INTCON<2>). The interrupt can be masked by clearing bit T0IE (INTCON<5>). Bit T0IF must be cleared in software by the Timer0 module Interrupt Service Routine before re-enabling this interrupt. The TMR0 interrupt cannot awaken the processor from SLEEP, since the timer is shut-off during SLEEP.

Timer mode is selected by clearing bit T0CS (OPTION_REG<5>). In Timer mode, the Timer0 module will increment every instruction cycle (without prescaler). If the TMR0 register is written, the increment is inhibited for the following two instruction cycles. The user can work around this by writing an adjusted value to the TMR0 register.

FIGURE 5-1:

Timer0 Interrupt

BLOCK DIAGRAM OF THE TIMER0/WDT PRESCALER Data Bus

CLKOUT (= FOSC/4)

0 RA4/T0CKI pin

1

8

M

1

U X

0

M U

SYNC 2 Cycles

X

TMR0 Reg

T0SE T0CS

Set Flag Bit T0IF on Overflow

PSA PRESCALER

0

Watchdog Timer

1

M U X

8-bit Prescaler 8 PS2:PS0

8 - to - 1MUX PSA

WDT Enable bit

0

1 MUX

PSA

WDT Time-out Note: T0CS, T0SE, PSA, PS2:PS0 are (OPTION_REG<5:0>).

2001 Microchip Technology Inc.

DS30292C-page 47


PIC16F87X 5.2

Using Timer0 with an External Clock

Timer0 module means that there is no prescaler for the Watchdog Timer, and vice-versa. This prescaler is not readable or writable (see Figure 5-1).

When no prescaler is used, the external clock input is the same as the prescaler output. The synchronization of T0CKI with the internal phase clocks is accomplished by sampling the prescaler output on the Q2 and Q4 cycles of the internal phase clocks. Therefore, it is necessary for T0CKI to be high for at least 2Tosc (and a small RC delay of 20 ns) and low for at least 2Tosc (and a small RC delay of 20 ns). Refer to the electrical specification of the desired device.

The PSA and PS2:PS0 bits (OPTION_REG<3:0>) determine the prescaler assignment and prescale ratio. When assigned to the Timer0 module, all instructions writing to the TMR0 register (e.g. CLRF 1, MOVWF 1, BSF 1,x . etc.) will clear the prescaler. When assigned to WDT, a CLRWDT instruction will clear the prescaler along with the Watchdog Timer. The prescaler is not readable or writable.

5.3

Note: Writing to TMR0, when the prescaler is assigned to Timer0, will clear the prescaler count, but will not change the prescaler assignment.

Prescaler

There is only one prescaler available, which is mutually exclusively shared between the Timer0 module and the Watchdog Timer. A prescaler assignment for the

REGISTER 5-1:

OPTION_REG REGISTER R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

R/W-1

RBPU

INTEDG

T0CS

T0SE

PSA

PS2

PS1

PS0

bit 7

bit 0

bit 7

RBPU

bit 6

INTEDG

bit 5

T0CS: TMR0 Clock Source Select bit 1 = Transition on T0CKI pin 0 = Internal instruction cycle clock (CLKOUT)

bit 4

T0SE: TMR0 Source Edge Select bit 1 = Increment on high-to-low transition on T0CKI pin 0 = Increment on low-to-high transition on T0CKI pin

bit 3

PSA: Prescaler Assignment bit 1 = Prescaler is assigned to the WDT 0 = Prescaler is assigned to the Timer0 module

bit 2-0

PS2:PS0: Prescaler Rate Select bits Bit Value TMR0 Rate WDT Rate 000 001 010 011 100 101 110 111

1:2 1:4 1:8 1 : 16 1 : 32 1 : 64 1 : 128 1 : 256

1:1 1:2 1:4 1:8 1 : 16 1 : 32 1 : 64 1 : 128

Legend:

Note:

R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

x = Bit is unknown

To avoid an unintended device RESET, the instruction sequence shown in the PICmicro™ Mid-Range MCU Family Reference Manual (DS33023) must be executed when changing the prescaler assignment from Timer0 to the WDT. This sequence must be followed even if the WDT is disabled.

DS30292C-page 48

2001 Microchip Technology Inc.


PIC16F87X TABLE 5-1: Address 01h,101h

REGISTERS ASSOCIATED WITH TIMER0 Name TMR0

0Bh,8Bh, INTCON 10Bh,18Bh

Bit 7

Bit 6

Bit 5

Bit 4

Bit 3

Bit 2

Bit 1

Bit 0

Timer0 Module‟s Register PEIE

T0IE

INTE

RBIE

T0IF

Value on all other RESETS

xxxx xxxx

uuuu uuuu 0000 000u 1111 1111

INTF

RBIF

0000 000x

81h,181h OPTION_REG RBPU INTEDG T0CS T0SE PSA PS2 PS1 Legend: x = unknown, u = unchanged, - = unimplemented locations read as '0'. Shaded cells are not used by Timer0.

PS0

1111 1111

2001 Microchip Technology Inc.

GIE

Value on: POR, BOR

DS30292C-page 49


PIC16F87X 11.0

ANALOG-TO-DIGITAL CONVERTER (A/D) MODULE

The A/D module has four registers. These registers are: • A/D Result High Register (ADRESH) • A/D Result Low Register (ADRESL) • A/D Control Register0 (ADCON0) • A/D Control Register1 (ADCON1)

The Analog-to-Digital (A/D) Converter module has five inputs for the 28-pin devices and eight for the other devices. The analog input charges a sample and hold capacitor. The output of the sample and hold capacitor is the input into the converter. The converter then generates a digital result of this analog level via successive approximation. The A/D conversion of the 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 ADCON0 register, shown in Register 11-1, controls the operation of the A/D module. The ADCON1 register, shown in Register 11-2, configures the functions of the port pins. The port pins can be configured as analog inputs (RA3 can also be the voltage reference), or as digital I/O. Additional information on using the A/D module can be found in the PICmicro™ Mid-Range MCU Family Reference Manual (DS33023).

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/D‟s internal RC oscillator.

REGISTER 11-1:

ADCON0 REGISTER (ADDRESS: 1Fh) R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

R/W-0

U-0

R/W-0

ADCS1

ADCS0

CHS2

CHS1

CHS0

GO/DONE

ADON

bit 7

bit 0

bit 7-6

ADCS1:ADCS0: A/D Conversion Clock Select bits 00 = FOSC/2 01 = FOSC/8 10 = FOSC/32 11 = FRC (clock derived from the internal A/D module RC oscillator)

bit 5-3

CHS2:CHS0: Analog Channel Select bits 000 = channel 0, (RA0/AN0) 001 = channel 1, (RA1/AN1) 010 = channel 2, (RA2/AN2) 011 = channel 3, (RA3/AN3) 100 = channel 4, (RA5/AN4) (1) 101 = channel 5, (RE0/AN5) (1) 110 = channel 6, (RE1/AN6) (1) 111 = channel 7, (RE2/AN7)

bit 2

GO/DONE: A/D Conversion Status bit If ADON = 1: 1 = A/D conversion in progress (setting this bit starts the A/D conversion) 0 = A/D conversion not in progress (this bit is automatically cleared by hardware when the A/D conversion is complete)

bit 1

Unimplemented: Read as '0'

bit 0

ADON: A/D On bit 1 = A/D converter module is operating 0 = A/D converter module is shut-off and consumes no operating current Note 1: These channels are not available on PIC16F873/876 devices. Legend: R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

x = Bit is unknown


PIC16F87X REGISTER 11-2:

ADCON1 REGISTER (ADDRESS 9Fh) U-0

U-0

R/W-0

U-0

R/W-0

R/W-0

R/W-0

R/W-0

ADFM

PCFG3

PCFG2

PCFG1

PCFG0

bit 7

bit 0

bit 7

ADFM: A/D Result Format Select bit 1 = Right justified. 6 Most Significant bits of ADRESH are read as „0‟. 0 = Left justified. 6 Least Significant bits of ADRESL are read as „0‟.

bit 6-4

Unimplemented: Read as '0'

bit 3-0

PCFG3:PCFG0: A/D Port Configuration Control bits: (1)

(1)

(1)

PCFG3: PCFG0

AN7 RE2

AN6 RE1

AN5 RE0

AN4 RA5

AN3 RA3

AN2 RA2

AN1 RA1

AN0 RA0

0000

A

A

A

0001

A

A

A

A

A

A

A

A

VREF+

A

A

0010

D

D

D

0011

D

D

D

A

A

A

A

A

VREF+

A

A

0100

D

D

D

D

A

D

0101

D

D

D

D

VREF+

011x 1000

D

D

D

D

A

A

A

A

1001

D

D

A

A

1010

D

D

A

1011

D

D

1100

D

D

1101

D

D

1110

D

1111

D

A = Analog input

VREF+

VREF-

CHAN/ (2) Refs

A

VDD

VSS

8/0

A

RA3

VSS

7/1

A

VDD

VSS

5/0

A

RA3

VSS

4/1

A

A

VDD

VSS

3/0

D

A

A

RA3

VSS

2/1

D

D

D

D

VDD

VSS

0/0

VREF+

VREF-

A

A

RA3

RA2

6/2

A

A

A

A

VDD

VSS

6/0

A

VREF+

A

A

A

RA3

VSS

5/1

A

A

VREF+

VREF-

A

A

RA3

RA2

4/2

D

A

VREF+

VREF-

A

A

RA3

RA2

3/2

D

D

VREF+

VREF-

A

A

RA3

RA2

2/2

D

D

D

D

D

D

A

VDD

VSS

1/0

D

D

D

VREF+

VREF-

D

A

RA3

RA2

1/2

D = Digital I/O

Note 1: These channels are not available on PIC16F873/876 devices. 2: This column indicates the number of analog channels available as A/D inputs and the number of analog channels used as voltage reference inputs. Legend: R = Readable bit

W = Writable bit

U = Unimplemented bit, read as „0‟

- n = Value at POR

‟1‟ = Bit is set

‟0‟ = Bit is cleared

The ADRESH:ADRESL registers contain the 10-bit result of the A/D conversion. When the A/D conversion is complete, the result is loaded into this A/D result register pair, the GO/DONE bit (ADCON0<2>) is cleared and the A/D interrupt flag bit ADIF is set. The block diagram of the A/D module is shown in Figure 11-1.

x = Bit is unknown

To determine sample time, see Section 11.1. After this acquisition time has elapsed, the A/D conversion can be started.

After the A/D module has been configured as desired, the selected channel must be acquired before the conversion is started. The analog input channels must have their corresponding TRIS bits selected as inputs.

DS30292C-page 112

2001 Microchip Technology Inc.


PIC16F87X These steps should be followed for doing an A/D Conversion: 1.

2.

3. 4.

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) Configure A/D interrupt (if desired): • Clear ADIF bit • Set ADIE bit • Set PEIE bit • Set GIE bit

FIGURE 11-1:

5.

6. 7.

Wait the required acquisition time. Start conversion: • Set GO/DONE bit (ADCON0) Wait for A/D conversion to complete, by either: • Polling for the GO/DONE bit to be cleared (with interrupts enabled); OR • Waiting for the A/D interrupt Read A/D result register pair (ADRESH:ADRESL), clear bit ADIF if required. 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.

A/D BLOCK DIAGRAM CHS2:CHS0

111 110 101 100 VAIN (Input Voltage)

011 010

A/D Converter

001 VDD

000

(1)

RE2/AN7

(1)

RE1/AN6

(1)

RE0/AN5 RA5/AN4

RA3/AN3/VREF+ RA2/AN2/VREFRA1/AN1 RA0/AN0

VREF+ (Reference Voltage) PCFG3:PCFG0

VREF(Reference Voltage) VSS PCFG3:PCFG0

Note

1: Not available on PIC16F873/876 devices.

2001 Microchip Technology Inc.

DS30292C-page 113


PIC16F87X 12.10 Interrupts

The RB0/INT pin interrupt, the RB port change interrupt, and the TMR0 overflow interrupt flags are contained in the INTCON register.

The PIC16F87X family has up to 14 sources of interrupt. The interrupt control register (INTCON) records individual interrupt requests in flag bits. It also has individual and global interrupt enable bits. Note:

The peripheral interrupt flags are contained in the special function registers, PIR1 and PIR2. The corresponding interrupt enable bits are contained in special function registers, PIE1 and PIE2, and the peripheral interrupt enable bit is contained in special function register INTCON.

Individual interrupt flag bits are set, regardless of the status of their corresponding mask bit, or the GIE bit.

A global interrupt enable bit, GIE (INTCON<7>) enables (if set) all unmasked interrupts, or disables (if cleared) all interrupts. When bit GIE is enabled, and an interrupt‟s flag bit and mask bit are set, the interrupt will vector immediately. Individual interrupts can be disabled through their corresponding enable bits in various registers. Individual interrupt bits are set, regardless of the status of the GIE bit. The GIE bit is cleared on RESET.

When an interrupt is responded to, the GIE bit is cleared to disable any further interrupt, the return address is pushed onto the stack and the PC is loaded with 0004h. Once in the Interrupt Service Routine, the source(s) of the interrupt can be determined by polling the interrupt flag bits. The interrupt flag bit(s) must be cleared in software before re-enabling interrupts to avoid recursive interrupts. For external interrupt events, such as the INT pin or PORTB change interrupt, the interrupt latency will be three or four instruction cycles. The exact latency depends when the interrupt event occurs. The latency is the same for one or two-cycle instructions. Individual interrupt flag bits are set, regardless of the status of their corresponding mask bit, PEIE bit, or GIE bit.

The “return from interrupt” instruction, RETFIE, exits the interrupt routine, as well as sets the GIE bit, which re-enables interrupts.

FIGURE 12-9:

INTERRUPT LOGIC

EEIF EEIE PSPIF PSPIE ADIF ADIE

Wake-up (If in SLEEP mode)

T0IF T0IE INTF INTE

RCIF RCIE TXIF TXIE SSPIF SSPIE

Interrupt to CPU

RBIF RBIE PEIE

CCP1IF CCP1IE

GIE

TMR2IF TMR2IE TMR1IF TMR1IE CCP2IF CCP2IE BCLIF BCLIE

The following table shows which devices have which interrupts. Device

T0IF

INTF

RBIF

PIC16F876/873

Yes

Yes

PIC16F877/874

Yes

Yes

2001 Microchip Technology Inc.

PSPIF

ADIF

RCIF

TXIF

SSPIF

CCP1IF

TMR2IF

TMR1IF

EEIF BCLIF

CCP2IF

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

DS30292C-page 129


PIC16F87X 12.10.1

INT INTERRUPT

12.11

External interrupt on the RB0/INT pin is edge triggered, either rising, if bit INTEDG (OPTION_REG<6>) is set, or falling, if the INTEDG bit is clear. When a valid edge appears on the RB0/INT pin, flag bit INTF (INTCON<1>) is set. This interrupt can be disabled by clearing enable bit INTE (INTCON<4>). Flag bit INTF must be cleared in software in the Interrupt Service Routine before re-enabling this interrupt. The INT interrupt can wake-up the processor from SLEEP, if bit INTE was set prior to going into SLEEP. The status of global interrupt enable bit, GIE, decides whether or not the processor branches to the interrupt vector following wake-up. See Section 12.13 for details on SLEEP mode.

12.10.2

TMR0 INTERRUPT

An overflow (FFh → 00h) in the TMR0 register will set flag bit T0IF (INTCON<2>). The interrupt can be enabled/disabled by setting/clearing enable bit T0IE (INTCON<5>) (Section 5.0).

12.10.3

Context Saving During Interrupts

During an interrupt, only the return PC value is saved on the stack. Typically, users may wish to save key registers during an interrupt, (i.e., W register and STATUS register). This will have to be implemented in software. For the PIC16F873/874 devices, the register W_TEMP must be defined in both banks 0 and 1 and must be defined at the same offset from the bank base address (i.e., If W_TEMP is defined at 0x20 in bank 0, it must also be defined at 0xA0 in bank 1). The registers, PCLATH_TEMP and STATUS_TEMP, are only defined in bank 0. Since the upper 16 bytes of each bank are common in the PIC16F876/877 devices, temporary holding registers W_TEMP, STATUS_TEMP, and PCLATH_TEMP should be placed in here. These 16 locations don‟t require banking and therefore, make it easier for context save and restore. The same code shown in Example 12-1 can be used.

PORTB INTCON CHANGE

An input change on PORTB<7:4> sets flag bit RBIF (INTCON<0>). The interrupt can be enabled/disabled by setting/clearing enable bit RBIE (INTCON<4>) (Section 3.2).

EXAMPLE 12-1:

SAVING STATUS, W, AND PCLATH REGISTERS IN RAM

MOVWF SWAPF CLRF MOVWF MOVF MOVWF CLRF : :(ISR) : MOVF MOVWF SWAPF

W_TEMP STATUS,W STATUS STATUS_TEMP PCLATH, W PCLATH_TEMP PCLATH

MOVWF SWAPF SWAPF

STATUS W_TEMP,F W_TEMP,W

;Copy ;Swap ;bank ;Save ;Only ;Save ;Page

W to TEMP register status to be saved into W 0, regardless of current bank, Clears IRP,RP1,RP0 status to bank zero STATUS_TEMP register required if using pages 1, 2 and/or 3 PCLATH into W zero, regardless of current page

;(Insert user code here) PCLATH_TEMP, W PCLATH STATUS_TEMP,W

;Restore PCLATH ;Move W into PCLATH ;Swap STATUS_TEMP register into W ;(sets bank to original state) ;Move W into STATUS register ;Swap W_TEMP ;Swap W_TEMP into W


Smart cardiologist