Microcontroller Lab Manual
Microcontroller Lab Manual
ENGINEERING
MICROCONTROLLER
LABORATORY MANUAL
TE 1st Semester
MICROCONTROLLER
LABORATORY MANUAL
Student Name:……………………………………………………
Roll No:………………………………………………………………
Branch:……………………………..Section ……………………
Year …………………………Semester………………………..
FACULTY INCHARGE
INSTRUCTIONS TO STUDENTS
• Before entering the lab the student should carry the following things.
o Identity card issued by the college.
o Class notes
o Lab observation book
o Lab Manual
o Lab Record
• Student must sign in and sign out in the register provided when attending the lab session without
fail.
• Come to the laboratory in time. Students, who are late more than 15 min., will not be allowed to
attend the lab.
• Students need to maintain 100% attendance in lab if not a strict action will be taken.
• All students must follow a Dress Code while in the laboratory
• Foods, drinks are NOT allowed.
• All bags must be left at the indicated place.
• The objective of the laboratory is learning. The experiments are designed to illustrate phenomena
in different areas of Physics and to expose you to measuring instruments, conduct the experiments
with interest and an attitude of learning
• You need to come well prepared for the experiment.
• Work quietly and carefully
• Be honest in recording and representing your data.
• If a particular reading appears wrong repeat the measurement carefully, to get a better fit for a
graph
• All presentations of data, tables and graphs calculations should be neatly and carefully done
• Graphs should be neatly drawn with pencil. Always label graphs and the axes and display units.
• If you finish early, spend the remaining time to complete the calculations and drawing graphs.
Come equipped with calculator, scales, pencils etc.
• Do not fiddle with apparatus. Handle instruments with care. Report any breakage to the Instructor.
Return all the equipment you have signed out for the purpose of your experiment.
SPECIFIC SAFETY RULES FOR BEE LABORATORY
• You should inspect laboratory equipment for visible damage before using it. If there is a
problem with a piece of equipment, report it to the technician or lecturer. DONOT return
equipment to a storage area
• You should not work on circuits where the supply voltage exceeds 40 volts without very
specific approval from your lab supervisor. If you need to work on such circuits, you should
contact your supervisor for approval and instruction on how to do this safely before
commencing the work.
• Always use an appropriate stand for holding your soldering iron.
• Turn off your soldering iron if it is unlikely to be used for more than 10 minutes.
• Never leave a hot soldering iron unattended.
• Never touch a soldering iron element or bit unless the iron has been disconnected
from themains and has had adequate time to cool down.
• Never strip insulation from a wire with your teeth or a knife, always use an appropriate
wirestripping tool.
• Shield wire with your hands when cutting it with a pliers to prevent bits of wire flying
about the bench.
CONTENTS
Page
S.No Name of the experiment
Number
Simple program on memory Transfer
1 1-3
Parallel Port interfacing of LEDS
2 4-7
Interfacing of Multiplexed 7-segment display
3 8-10
Interfacing Push buttons, LEDs, Relay & Buzzer to PIC Microcontroller
4 11-19
Interfacing LCD to Display Message
5 20-25
6 Interfacing of Stepper motor to 8051- software delay using 26-29
Timer
Experiment No: 01
S/W PACKAGES AND H/W USED: keil uvision 5, , 8051 Development Board
THEORY:
The microcontroller like 8051 was designed in the year 1981 by Intel. The microcontroller is one
kind of integrated circuit that includes 40-pins with dual inline package or DIP, RAM-128 bytes,
ROM-4kb & 16-bit timers–2. Based on the requirement, it includes addressable & programmable
4 – parallel 8-bit ports. In the 8051 microcontroller architecture, the system bus plays a key role to
connect all the devices to the central processing unit. This bus includes a data bus- an 8-bit, an
address bus-16-bit & bus control signals. Other devices can also be interfaced throughout the
system bus like ports, memory, interrupt control, serial interface, the CPU, timers.
There are two buses in 8051 Microcontroller one for the program and another for data. As a result,
it has two storage rooms for both programs and data of 64K by 8 sizes. The microcontroller
comprises of 8-bit accumulator & an 8-bit processing unit. It also consists of 8 bit B register as
majorly functioning blocks and 8051 microcontroller programming is done with embedded C
language using Keil software. It also has several other 8 bit and 16-bit registers.
For internal functioning & processing Microcontroller, 8051 comes with integrated built-in RAM.
This is prime memory and is employed for storing temporary data. It is an unpredictable memory
i.e. its data can get be lost when the power supply to the Microcontroller switched OFF. This
microcontroller is very simple to use, affordable less computing power, simple architecture &
instruction set.
The micro-controller needs a program that is a set of commands. This program enlightens the
Microcontroller to perform precise tasks. These programs need a storage space on which they can
be accumulated and interpret by the Microcontroller to act upon any specific process. The memory
which is brought into play to accumulate the program of the Microcontroller is recognized as
Program memory or code memory. In common language, it’s also known as Read-Only Memory
or ROM.
The microcontroller also needs memory to amass data or operands for the short term. The storage
space which is employed to momentarily data storage for functioning is acknowledged as Data
Memory and we employ Random Access Memory or RAM for this principle reason.
Microcontroller 8051 contains code memory or program memory 4K so which has 4KB Rom and
it also comprises data memory (RAM) of 128 bytes.
The main features of the 8051 microcontroller architecture include the following.
• 8-bit CPU through two Registers A & B.
• 8K Bytes – Internal ROM and it is a flash memory that supports while programming the system.
• 256 Bytes – Internal RAM where the first RAM with 128 Bytes from 00H to 7FH is once more
separated into four banks through 8 registers in every bank, addressable registers -16 bit &
general-purpose registers – 80.
• The remaining 128 bytes of the RAM from 80H to FFH include Special Function Registers
(SFRs). These registers control various peripherals such as Serial Port, Timers, all I/O Ports, etc.
• Interrupts like External-2 & Internal-3
• Oscillator & CLK Circuit.
• Control Registers like PCON, SCON, TMOD, TCON, IE, and IP.
• 16-bit Timers or Counters -2 like T0 & T1.
• Program Counter – 16 bit & DPRT (Data Pointer).
• I/O Pins – 32 which are arranged like four ports such as P0, P1, P2 & P3.
• Stack Pointer (SP) – 8bit & PSW (Processor Status Word).
• Serial Data Tx & Rx for Full-Duplex Operation
SOURCE CODE:
#include<reg51.h>
int main()
{
unsigned char xdata *p;
p = ( unsigned char *) 0x8000;
*p=0x10;
&p++;
*p=0x20;
&p++;
B=*p;
return 0;
}
OUTPUT:
RESULT:
EXPERIMENT NO: 02
TITLE: Parallel Port interfacing of LEDS
PROBLEM STATEMENT:
Parallel port interacting of LEDS-
1. Flashing of Leds connected to Port 2
2. Switch off all the Leds connected to Port2 and blink only one led connected to P2.1
3. Program to show L-R & R-L Shifting
S/W PACKAGES AND H/W USED: keil u vision 5, , 8051 Development Board
THEORY:
The microcontroller like 8051 was designed in the year 1981 by Intel. The microcontroller is one kind of
integrated circuit that includes 40-pins with dual inline package or DIP, RAM-128 bytes, ROM-4kb &
16-bit timers–2. Based on the requirement, it includes addressable & programmable 4 – parallel 8-bit
ports. In the 8051 microcontroller architecture, the system bus plays a key role to connect all the devices
to the central processing unit. This bus includes a data bus- an 8-bit, an address bus-16-bit & bus control
signals. Other devices can also be interfaced throughout the system bus like ports, memory, interrupt
control, serial interface, the CPU, timers.
LED (Light Emitting Diode)
LED is a semiconductor device used in many electronic devices, mostly used for signal transmission
/power indication purposes. It is very cheaply and easily available in a variety of shape, color, and size.
The LEDs are also used for design message display boards and traffic control signal lights etc.
It has two terminals positive and negative as shown in the figure.
The only way to know polarity is either to test it with a multimeter or by carefully observing inside the
LED. The larger end inside the led is -ve (cathode) and the shorter one is +ve (anode), that is how we
Electronics & Telecommunication Engineering
Page 4
ISB&M COE
find out the polarity of the LED. Another way to recognize the polarity is, connecting leads, POSITIVE
terminal has more length than NEGATIVE terminal.
There are two ways which we can interface LED to the Microcontroller 8051. But the connections and
programming techniques will be different. This article provides the information on LED interfacing with
8051 and LED blinking code for AT89C52/ AT89C51 Microcontroller.
Observe carefully the interface LED 2 is in forward biased because the input voltage of 5v connected to
the positive terminal of the LED, So here the Microcontroller pin should be at LOW level. And vice
versa with the interface 1 connections.
The resistor is important in LED interfacing to limit the flowing current and avoid damaging the LED
and/or MCU.
• Interface 1 will glow LED, only if the PIN value of the MC is HIGH as current flows towards the
ground.
• Interface 2 will glow LED, only if the PIN value of the MC is LOW as current flows towards PIN
due to its lower potential.
SOURCE CODE:
OUTPUT:
EXPERIMENT NO: 03
TITLE: Interfacing of Multiplexed 7-segment display
PROBLEM STATEMENT:
Write an Embedded C program to display number 0-9 on SSD with 8051
THEORY:
The 7-segment display, also written as “seven segment display”, consists of seven LEDs (hence
its name) arranged in a rectangular fashion as shown. Each of the seven LEDs is called a segment
because when illuminated the segment forms part of a numerical digit (both Decimal and Hex) to be
displayed. An additional 8th LED is sometimes used within the same package thus allowing the
indication of a decimal point, (DP) when two or more 7-segment displays are connected together to
display numbers greater than ten. Each one of the seven LEDs in the display is given a positional
segment with one of its connection pins being brought straight out of the rectangular plastic package.
These individually LED pins are labelled from a through to g representing each individual LED. The
other LED pins are connected together and wired to form a common pin.So by forward biasing the
appropriate pins of the LED segments in a particular order, some segments will be light and others will
be dark allowing the desired character pattern of the number to be generated on the display. This then
allows us to display each of the ten decimal digits 0 through to 9 on the same 7-segment display. The
displays common pin is generally used to identify which type of 7-segment display it is. As each LED
has two connecting pins, one called the “Anode” and the other called the “Cathode”, there are therefore
two types of LED 7-segment display called: Common Cathode (CC) and Common Anode (CA). The
difference between the two displays, as their name suggests, is that the common cathode has all the
cathodes of the 7-segments connected directly together and the common anode has all the anodes of the
7-segments connected together and is illuminated as follows.The Common Cathode (CC) – In the
common cathode display, all the cathode connections of the LED segments are joined together to logic
“0” or ground. The individual segments are illuminated by application of a “HIGH”, or logic “1” signal
via a current limiting resistor to forward bias the individual Anode terminals (a-g).
Common Anode
Common Cathode
SOURCE CODE:
#include <reg51.h>
unsigned char array[]={0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x02,0x78,0x00,0x18}; //common
anode values
void main()
{
unsigned char i;
for(i=0;i<11;i++)
{
P0=array[i];
}
}
OUTPUT:
EXPERIMENT NO: 04
TITLE: Interfacing Push buttons, LEDs, Relay & Buzzer to PIC Microcontroller
PROBLEM STATEMENT:
Interface Push buttons, LEDs, Relay and Buzzer to PIC Microcontroller. Write a program in
Embedded C to interact with peripherals as follows.
a. LED’s start chasing from left to right and turn ON Relay, buzzer whenever pushbutton 1 is
pressed.
b. LED’s start chasing from right to left and turn OFF Relay, buzzer whenever pushbutton 2 is
pressed.
OBJECTIVE:
a. To understand the PORT Structure of PIC Microcontroller.
b. To study the SFRs to control the PORT Pins.
c. To interface common peripherals like pushbuttons, LEDs, relay.
d. To understand the use of MPLAB IDE and C18 Compiler.
e. To write a simple program in Embedded C.
S/W PACKAGES AND H/W USED:MPLAB IDE, C18 Compiler, Explore PIC Development Board
THEORY
Depending on the device selected, there are up to five general purpose I/O ports available on PIC18F
Microcontroller devices. Some pins of the I/O ports are multiplexed with an alternate function from the
peripheral features on the device. In general, when a peripheral is enabled, that pin may not be used as a
general purpose I/O pin.
LAT register (output latch): The data latch (LAT register) is useful for read-modify-write operations
on the value that the I/O pins are driving.
I/OPin Direction Control
TRISB 1 101 10 0 0
• Several PORTA pins are multiplexed with analog inputs, the analog VREF+ and VREF- inputs
and the comparator voltage reference output.
• The operation of pins RA5 and RA3:RA0 as A/D converter inputs is selected by clearing/setting
the control bits in the ADCON1 register.
• On a Power-on Reset, RA5 and RA3:RA0 are configured as analog inputs and read as ‘0’. RA4
is configured as a digital input.
excluded from the interrupt on 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
ORed together to generate the RB Port Change Interrupt with Flag bit RBIF (INTCON register).
• On a Power-on Reset, RB4:RB0 are configured as analog inputs by default and read as ‘0’;
RB7:RB5 are configured as digital inputs. By programming the configuration bit, PBADEN,
RB4:RB0 will alternatively be configured as digital inputs on POR.
• For 28-pin devices, P ORTE is only available when Master Clear functionality is disabled
(MCLRE = 0 ). In these cases, PORTE is a single bit, input only port comprised of RE3 only .
• On a Power-on Reset, RE2:RE0 are configured as analog inputs. On a Power-on Reset, RE3 is
enabled as a digital input only if Master Clear functionality is disabled.
5. Algorithm
1. As LED connected to PORTD configure these pins as output by writing 0x00 to the appropriated
TRES register.
2. As buttons are connected to RB.4 and RB.5 so configure these pins as input by writing 1 to the
appropriated bits of TRES register.
3. Check the status of RB.4, if it is zero then move 1 bit of PORTB from right to left.
4. Else check the status of RB.5, if it is zero then move 1 bit of PORTB from left to right.
5. Repeat step 3 to 4
6. Source Code
//Declarations
#define lrbit PORTBbits.RB4 //SW1 interfaced to RB4
#define rlbit PORTBbits.RB5 //SW2 interfaced to RB5
#define buzzer PORTCbits.RC2 //Buzzer interfaced to RC2
#define relay PORTCbits.RC1 //Relay interfaced to RC1
//Function Prototypes
void msdelay (unsigned int time);//Function for delay
if (val == 1)
{
buzzer = 1;
relay = 1;
PORTD = PORTD >>1; //Shift left by 1 bit
if (PORTD == 0x00)
PORTD = 0x80; // Make the MSB bit equal to 1
msdelay(250);
}
if (val == 2)
{
buzzer = 0;
relay = 0;
PORTD = PORTD<<1; //Shift right by 1 bit
if (PORTD == 0x00)
PORTD = 0x01; // Make the LSB bit eqaul to 1
msdelay(250);
}
}
} //End of the Program
//Function Definitions
Electronics & Telecommunication Engineering
Page 18
ISB&M COE
EXPERIMENT NO: 05
TITLE: Interfacing LCD to Display Message
PROBLEM STATEMENT: Interface 16x2 LCD to PIC Microcontroller in 8-bit Mode. Write a
program in Embedded C to display user defined messages on LCD without using standard library
functions.
OBJECTIVE:
c. To understand the working of Liquid Crystal Display (LCD).
d. To study the LCD interfacing modes and Timing diagram.
e. To study and use of the LCD commands to drive LCD.
f. To interface LCD in 8-bit mode to PIC Microcontroller
S/W PACKAGES AND H/W USED:
MPLAB IDE, C18 Compiler, Explore PIC Development Board
THEORY
1. LCD Interfacing
In recent years the LCD is finding widespread use replacing LED’s. This is due to the following
reason:
f. The declining prices of LCD.
g. The ability to display numbers, characters, and graphics. This is in contrast to LEDs, which are
limited to numbers and few characters.
h. In corporation of a refreshing controller into the LCD, thereby reliving the CPU of the task of
refreshing the LCD. In contrast, the LED must be refreshed by the CPU to keep displaying the
data.
i. Ease of programming for characters and graphics.
Most of LCD’s available in the market are based on controller HD44780. The LCD display can
be interfaced either in 4-bit interface or 8-bit interface mode.
1.1.4 Enable (EN): The enable pin is used by the LCD to latch information presented to its data pins.
When data is supplied to data pins, a high to low pulse must be applied to the pin in order for the
LCD to latch in the data present at the data pins. This pulse must be a minimum of 450ns wide.
1.1.5 Data bus (D0 – D7): The 8-bit data pins, D0-D7 are used to send the information to the LCD or
read the contents of the LCD’s internal registers. To display the numbers and letters, we send ASCII
codes to these pins while making RS=1.
There are also instruction command codes that can be sent to the LCD to clear the display or blink the
cursor.
We also use RS = 0 to check the busy flag bit to see if the LCD is ready to receive information. The
busy flag is D& and can be read when R/W = 1 and RS=0. When D7 =1, the LCD is busy taking care of
internal operations and will not accept any new information. When D7 = 0, the LCD is ready to receive
new information.
1.2 Pin Assignment of 16x2 LCD
15 VB+ 1 -
Backlight Supply
16 VB- 0 -
02 Return home 02
5. Algorithm
As LCD data bus is connected to PORTD and handshaking signal EN-RE0, RS-RE1, E-RE2,
configure these pins output writing 0x00 to the appropriated TRES register.
The RE0, RE1, RE2 this pins have dual function (analog/digital), by default on every reset it
work as analog input. So make this pin as digital by using ADCON1 register.
Initialize LCD.
a. Write a commands {2 line and 5X7 matrix (0x38), Display ON cursor OFF (0x0C),
Increment & shift cursor right (0x06), Clear display screen (0x01) to LCD}.
EXPERIMENT NO: 06
S/W PACKAGES AND H/W USED: keil uvision 5, , 8051 Development Board
THEORY:
A Stepper Motor or a step motor is a brushless, synchronous motor which divides a full
rotation into a number of steps. Unlike a brushless DC motor which rotates continuously
when a fixed DC voltage is applied to it, a step motor rotates in discrete step angles. The
Stepper Motors therefore are manufactured with steps per revolution of 12, 24, 72, 144,
180, and 200, resulting in stepping angles of 30, 15, 5, 2.5, 2, and 1.8 degrees per step.
The stepper motor can be controlled with or without feedback. Stepper motors work on
the principle of electromagnetism. There is a soft iron or magnetic rotor shaft surrounded
by the electromagnetic stators. The rotor and stator have poles which may be teethed or
not depending upon the type of stepper. When the stators are energized the rotor moves to
align itself along with the stator (in case of a permanent magnet type stepper) or moves to
have a minimum gap with the stator (in case of a variable reluctance stepper). This way
the stators are energized in a sequence to rotate the stepper motor.
INTERFACING DIAGRAM:
SOURCE CODE :
#include<reg52.h>
#include<stdio.h>
void delay(int);
void main()
{
do
{
P2=0x01; //0001
delay(1000);
P2=0x02; //0010
delay(1000);
P2=0x04; //0100
delay(1000);
P2=0x08; //1000
delay(1000);
}
while(1);
}
void delay(int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<100;j++)
{}
}
}
#include<reg52.h>
#include<stdio.h>
void delay(int);
void main()
{
do
{
P2 = 0x03; //0011
delay(1000);
P2 = 0x06; //0110
delay(1000);
P2 = 0x0C; //1100
delay(1000);
P2 = 0x09; //1001
delay(1000);
}
while(1);
}
void delay(int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<100;j++)
{}
}
}
#include<reg52.h>
#include<stdio.h>
void delay(int);
void main()
{
do
{
P2=0x01; //0001
delay(1000);
P2=0x03; //0011
delay(1000);
P2=0x02; //0010
delay(1000);
P2=0x06; //0110
delay(1000);
P2=0x04; //0100
delay(1000);
P2=0x0C; //1100
delay(1000);
P2=0x08; //1000
delay(1000);
P2=0x09; //1001
delay(1000);
} while(1);
}
void delay(int k)
{
int i,j;
for(i=0;i<k;i++)
{
for(j=0;j<100;j++)
{}
}
}
OUTPUT:
EXPERIMENT NO: 07
OBJECTIVE :
S/W PACKAGES AND H/W USED: MPLAB IDE, C18 Compiler, Explore PIC Development Board
THEORY:
1. ADC Devices:
Analog to digital converters are among the most widely used devices for data
acquisitions. Digital computers use binary (discrete) value but in physical world everything is analog
(continuous). A physical quantity is converted to electrical signals using device called transducer or also
called as sensors. Sensors and many other natural quantities produce an output that is voltage (or
current). Therefore we need an analog - to - digital converter to translate the analog signal to digital
numbers so that the microcontroller can read and process them.
The ADC chips are either parallel or serial. In parallel ADC, we have 8 or more pins dedicated to bring
out the binary data, but in serial ADC we have only one pin for data out.
Some of the major characteristics of ADC are a) resolution b) conversion time c) reference voltage
(Vref).
1.1 Resolution
An ADC has an n bit resolution where n can be 8, 10, 16, 0r even 24 bits. The higher resolution
ADC provides a smaller step size, where step size is smallest change that can be discerned by an ADC.
This is shown in Table 8.1. Although the resolution for ADC chip is designed at the time of its design
and cannot be changed, we can control the step size with the help of reference voltage (Vref).
The A/D conversion time per bit is defined as TAD. The A/D conversion requires 11 TAD per 10-bit
conversion. The source of the A/D conversion clock is software selectable. There are seven possible
options for TAD as shown in table 8.4
For correct A/D conversions, the A/D conversion clock (TAD) must be as short as possible
but greater than the minimum TAD. Table 8.4 shows the resultant TAD times derived from the
Electronics & Telecommunication Engineering
Page 35
ISB&M COE
2.5 Calculations
a. For Fosc = 20MHz
Tosc = 1/20MHz = 50 ns
Selected ADC clock source ADCS2:ADCS0 = 110 ie Fosc/64
TAD = 64Tosc = 64 * 50 ns
TAD = 3.2 us which is much greater than minimum TAD = 0.7 us
Selected A/D Acquisition Time Select bits ACQT2:ACQT0 = 001 i.e n= 2 Derived A/D
acquisition time = n * TAD = 2 * TAD
= 2 * 3.2 us
= 6.4 us
Which is much greater than calculated acquisition time = 2.4 us
Selected A/D Acquisition Time Select bits ACQT2:ACQT0 = 001 i.e n= 2 Derived A/D
acquisition time = n * TAD = 2 * TAD
= 2 * 1.33 us
= 2.67 us
Which is greater than calculated acquisition time = 2.4 us
5. Source Code
printf("
channel 0 %x", convert_channel(0)); //Convert a single channel and display
printf("
channel 1 %x", convert_channel(1));
printf("
channel 2 %x", convert_channel(2));
printf("
channel 3 %x", convert_channel(3));
printf("
channel 4 %x", convert_channel(4));
printf("
channel 5 %x", convert_channel(5));
printf("
channel 6 %x", convert_channel(6));
printf("
channel 7 %x", convert_channel(7));
Return: Values are returned to the calling function using the function parameters
/*-------------------------------------------------------------------------
Setup ADC in the MAX7651
--------------------------------------------------------------------------*/
#define NUMBER_OF_CHANNELS 8
/*-----------------------------------------------
Convert all ADC channels
-----------------------------------------------*/
/*-----------------------------------------------
Start a conversion and wait for it to complete.
-----------------------------------------------*/
/*-------------------------------------------------------------------------
Function: convert_channel
Copyright: Maxim Integrated
Target: MAX7651
Date: Feb 26, 2004
Electronics & Telecommunication Engineering
Page 42
ISB&M COE
Usage: The function will convert and return the result of a Channel.
Parameters: adc_ch, Select ADC channel to be converted.
/*-------------------------------------------------------------------------
Setup ADC in the MAX7651
--------------------------------------------------------------------------*/
conv_val = (ADDAT0 >> 4) | (ADDAT1 << 4); //Format the data in 12 bit
format
OUTPUT
EXPERIMENT NO: 08
TITLE: Generation of PWM Signal
PROBLEM STATEMENT:
Interface DC Motor (9V – 12V ; 200 – 300 rpm) to PIC microcontroller. Write a program
in Embedded C to control the speed of DC motor using on-chip PWM Module of PIC
Microcontroller.
OBJECTIVE:
THEORY:
j. PWM Technique:
automatically change any requirements for configuring the port pin. Users must always verify
that the appropriate TRIS register is configured correctly for CCP2 operation, regardless of
where it is located.
4. Capture Mode Applications
Event arrival time recording
Period measurement
Pulse-width measurement
Interrupt generation
Event counting
Time reference
Duty cycle measurement
Having established the PWM period, let us consider how the pulse width is determined.
A second Compare register arrangement is introduced to do this. This is made up of the
CCPR1H register, plus a second comparator. As the logic of the diagram shows, every time this
comparator finds equal input values, it resets the output flip-flop, clearing the output to zero. It is
this comparator that determines the pulse width. Again, this is shown in Figure 9.2. To change
the pulse width, the programmer writes to the CCPR1L register, which acts as a buffer. Its value
is transferred to CCPR1H only when a PWM cycle is complete, to avoid output errors in the
process. The block diagram is made more complex because three of the registers are ‘stretched’,
to make them potentially 10-bit instead of 8-bit. This increases the resolution. CCPR1L uses two
bits of the CCP1CON register. CCPR1H isextended with an internal 2-bit latch, while the
extension to Timer 2 is as described in Note 1 of Figure 9.1
Because of these two extra bits, in its 10-bit version it is effectively clocked direct from the
internal oscillator signal, undivided. If the prescaler is used, then it acts on this frequency, not the
usual Fosc/4. Notice, however, that the PR2 register remains at eight bits. This means that the
PWM period has only an 8-bit equivalent resolution.
The PWM period T is determined by the interaction of the PR2 register and the eight bits of
Timer 2. It may be calculated as follows:
PWM Period = Tpwm = (PR2 + 1) x (Timer 2 input Clock)
PWM Period = Tpwm = (PR2 + 1) x (4 * Tosc * TMR2 Prescaler value) Therefore
to find the PR2 for desired PWM Period
Where,
Timer 2 input Clock = 4 * Tosc * TMR2 Prescaler value
Fosc = Input Crystal Oscillator Frequency
Tosc = input clock period = 1/Fosc
Fpwm = PWM frequency
Tpwm = PWM Period = 1/Fpwm
The PWM pulse width Ton is determined by the interaction of the extended CCPR1H register
Electronics & Telecommunication Engineering
Page 47
ISB&M COE
(all 10 bits of it) and the extended (10-bit) Timer 2. It may be calculated as follows:
Hence,
Ton = (CCPR1L: CCP1CON<5:4>) x (Tosc * TMR2 Prescaler value)
Note that there is not here a factor of four with the Tosc term, as we are using 10-bits of Timer 2.
Rearranging the above equation, to find value of pulse width
register
Above equation can be represented in terms of frequency and percentage Duty cycle
(%DCpwm) as below.
Note: Choose TMR2PREto ensure that PR2 is in the range of 0 to 255 for the desiredPWM
frequency and CCPR1L:CCP1CON<5:4> is in the range of 0 to 1023 for the desired PWM duty
cycle.
CCP2(1) 16 RC1/T1OSI/CCP2(1)/UOE
CCP1 17 RC2/CCP1/P1A
CCP2(1) 36 RB3/AN9/CCP2(1)/VPO
Note 1: RB3 is the alternate pin for CCP2 multiplexing.
Bit 5 - 4 DCxB1:DCxB0 PWM Duty Cycle Bit 1 and Bit 0 for CCPx Module
Unused in Capture mode & Compare mode:
PWM mode: These bits are the two LSbs (bit 1 and bit
0) of the 10-bit PWM duty cycle. The eight MSbs of the
duty cycle are found in CCPR1L.
Bit 3 - 0 CCPxM3:CCPxM0 CCPx Module Mode Select bits
0000 = CCP disabled (resets CCPx module)
0001 = Reserved
0010 = Compare mode: toggle output on match (CCPxIF
bit is set)
0011 = Reserved
0100 = Capture mode: every falling edge
0101 = Capture mode: every rising edge
0110 = Capture mode: every 4th rising edge
0111 = Capture mode: every 16th rising edge
1000 = Compare mode: initialize CCPx pin low; on
•
1111 = 1:16 Postscaler
4. Timer 2 Module
The Timer2 module timer incorporates the following features:
• 8-bit timer and period registers (TMR2 and PR2, respectively)
• Readable and writable (both registers)
• Software programmable prescaler (1:1, 1:4 and 1:16)
• Software programmable Postscaler (1:1 through 1:16)
• Interrupt on TMR2 to PR2 match
• Optional use as the shift clock for the MSSP module
The module is controlled through the T2CON register which enables or disables the timer and
configures the prescaler and Postscaler. Timer2 can be shut off by clearing control bit, TMR2ON
(T2CON<2>), to minimize power consumption. A simplified block diagram of the module is
shown in Figure9.3.
In normal operation, TMR2 is incremented from 00h on each clock (FOSC/4). A 2-bit
counter/prescaler on the clock input gives direct input, divide-by-4 and divides-by- 16 prescale
options. These are selected by the prescaler control bits, T2CKPS1:T2CKPS0 (T2CON<1:0>).
The value of TMR2 is compared to that of the period register, PR2, on each clock cycle. When
the two values match, the comparator generates a match signal as the timer output. This signal
also resets the value of TMR2 to 00h on the next cycle and drives the output counter/ Postscaler.
The TMR2 and PR2 registers are both directly readable and writable. The TMR2 register
is cleared on any device Reset, while the PR2 register initializes at FFh. TMR2 is not cleared
when T2CON is written. Both the prescaler and postscaler counters are cleared on the following
events:
a write to the TMR2 register
a write to the T2CON register
any device Reset (Power-on Reset, MCLR Reset, WDT Reset or Brown-out)
3. Timer2 Interrupt
Timer2 also can generate an optional device interrupt. The Timer2 output signal (TMR2
to PR2 match) provides the input for the 4-bit output counter/postscaler. This counter generates
the TMR2 match interrupt flag which is latched in TMR2IF (PIR1<1>). The interrupt is enabled
by setting the TMR2 Match Interrupt Enable bit, TMR2IE (PIE1<1>). A range of 16 postscale
options (from 1:1 through 1:16 inclusive) can be selected with the postscaler control bits,
T2OUTPS3:T2OUTPS0 (T2CON<6:3>).
Drivers are enabled in pairs, with drivers 1 and 2 enabled by 1,2EN and drivers 3 and 4
enabled by 3,4EN as shown in pin diagram and function table. When an enable input is high, the
associated drivers are enabled, and their outputs are active and in phase with their inputs. When the
enable input is low, those drivers are disabled, and their outputs are off and in the high-impedance
state. With the proper data inputs, each pair of drivers forms a full-H (or bridge) reversible drive
suitable for solenoid or motor applications.